Django:如何在urlpatterns中访问其他模型的主键?

时间:2019-11-10 17:38:23

标签: python django

路由到特定路径时,我得到NoReverseMatch

在获取所有其他类似路径的结果时,无法仅找到一个 urlpattern 的主键<int:pk>

我认为这个错误是因为这里的模型不同,例如,

未收到以下错误消息:

class PostUpdateView():
   model = A

我得到的错误是由于:

class AddCommentView():
   model = B
urlpatterns = [
    path('post/<int:pk>/update/', PostUpdateView.as_view(), name = 'post-update'),
    path('post/<int:pk>/comment', AddCommentView.as_view(), name = 'post-comment')]

这两个类都在同一个 views.py 文件中,因为我需要在路由网址中使用模型A的主键,以便可以返回到原始页面。

错误:

Reverse for 'post-comment' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/comment$']

将两个模型的键包含在同一路径中的正确方法是什么?

注意:A的主键作为外键出现在B中。

1 个答案:

答案 0 :(得分:0)

您的get_absolute_url方法应类似于kwargs参数。

from django.urls import reverse

class AddCommentView():
   model = B

   def get_absolute_url(self):
       return reverse('post-comment', kwargs={'pk': self.pk})