将两个 pk 传递到 url 中

如果更改“学年”值,则不会出现 404。我希望仅当 'school_year' 和 'pk' 的 url 值都正确时才显示数据。

例如,如果您有数据 (School_Year = 2020, pk = 33),当您输入 url https://190.0.1/190/190/33https://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 


摇曳的蔷薇
浏览 81回答 1
1回答

MMTTMM

我将使用以下方法删除get_context_data并覆盖:get_objectget_object_or_404class StudentDetail(DetailView, FormClass):&nbsp; &nbsp; model = Student&nbsp; &nbsp; template_name = 'student/member.html'&nbsp; &nbsp; context_object_name = 'student'&nbsp; &nbsp; form_class = AddConsultation&nbsp; &nbsp; def get_object(self, queryset=None):&nbsp; &nbsp; &nbsp; &nbsp; return get_object_or_404(Student, pk=self.kwargs['pk'], school_year=self.kwargs['school_year'])其他解决方案可能是:class StudentDetail(DetailView, FormClass):&nbsp; &nbsp; model = Student&nbsp; &nbsp; template_name = 'student/member.html'&nbsp; &nbsp; context_object_name = 'student'&nbsp; &nbsp; form_class = AddConsultation&nbsp; &nbsp; slug_field = 'school_year'&nbsp; &nbsp; slug_url_kwarg = 'school_year'&nbsp; &nbsp; query_pk_and_slug = True但我发现第一个不那么神奇:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python