如果“学年”的值被更改,则不会出现404。 我希望仅当'school_year'和'pk'在url中都具有正确的值时才显示数据。
例如 如果您有数据(School_Year = 2020,pk = 33) 当您输入网址https://190.0.1/190/190/33和https://190.0.1/190/whatthell/33时 两者都是相同的结果。
但是,我只想在两个值都正确时才显示结果。
我真的不知道我的解释是否正确,谢谢。
view.py
class StudentDetail(DetailView,FormView):
model = Student
template_name = 'student/member.html'
context_object_name = 'student'
form_class = AddConsultation
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['pk'] = Student.objects.filter(pk=self.kwargs.get('pk'))
return context
url.py
path('student/<school_year>/<pk>/', views.StudentDetail.as_view(), name='student_detail'),
html链接
<a href='{% url 'student_detail' student.school_year student.pk %}'>
models.py
class Student(models.Model):
school_year = models.CharField(
max_length=10,
choices=SCHOOL_YEAR_CHOICES,
default='2021N',
verbose_name='school year'
)
... etc
答案 0 :(得分:0)
我将删除get_context_data
并使用get_object
覆盖get_object_or_404
:
class StudentDetail(DetailView, FormClass):
model = Student
template_name = 'student/member.html'
context_object_name = 'student'
form_class = AddConsultation
def get_object(self, queryset=None):
return get_object_or_404(Student, pk=self.kwargs['pk'], school_year=self.kwargs['school_year'])
其他解决方案可能是:
class StudentDetail(DetailView, FormClass):
model = Student
template_name = 'student/member.html'
context_object_name = 'student'
form_class = AddConsultation
slug_field = 'school_year'
slug_url_kwarg = 'school_year'
query_pk_and_slug = True
但是我发现第一个少了魔法:)