亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將兩個 pk 傳遞到 url 中

將兩個 pk 傳遞到 url 中

搖曳的薔薇 2023-09-12 17:10:27
如果更改“學年”值,則不會出現 404。我希望僅當 'school_year' 和 'pk' 的 url 值都正確時才顯示數據。例如,如果您有數據 (School_Year = 2020, pk = 33),當您輸入 url https://190.0.1/190/190/33和https://190.0.1/190/whatthell/33時 ,兩者都是相同的結果。但是,我想僅當兩個值都正確時才顯示結果。我真的不知道我解釋是否正確,謝謝。view.pyclass 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 contexturl.pypath('student/<school_year>/<pk>/', views.StudentDetail.as_view(), name='student_detail'),html鏈接<a href='{% url 'student_detail' student.school_year student.pk %}'>models.pyclass Student(models.Model):    school_year = models.CharField(        max_length=10,        choices=SCHOOL_YEAR_CHOICES,        default='2021N',        verbose_name='school year'    )    ... etc 
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

我將使用以下方法刪除get_context_data并覆蓋:get_objectget_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

但我發現第一個不那么神奇:)


查看完整回答
反對 回復 2023-09-12
  • 1 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號