Python 将两个pk传递到url
如果“学年”值已更改,则不会显示404。 我希望数据仅在“学年”和“pk”在url中都具有正确的值时显示 比如说 如果您有以下数据(学年=2020,pk=33) 当您输入url和 两者都是相同的结果 但是,我只想在两个值都正确时显示结果 我真的不知道我的解释是否正确,谢谢 view.pyPython 将两个pk传递到url,python,django,Python,Django,如果“学年”值已更改,则不会显示404。 我希望数据仅在“学年”和“pk”在url中都具有正确的值时显示 比如说 如果您有以下数据(学年=2020,pk=33) 当您输入url和 两者都是相同的结果 但是,我只想在两个值都正确时显示结果 我真的不知道我的解释是否正确,谢谢 view.py class StudentDetail(DetailView,FormView): model = Student template_name = 'student/member
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'),
我将删除
get\u context\u数据
并使用get\u object\u或
覆盖get\u object
:
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
但我发现第一个没那么神奇:)干杯!它起作用了。get_context_数据和get_对象之间有什么区别?get_对象用于填充模板中的对象变量,get_context_数据用于向模板上下文添加更多内容
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