简体   繁体   中英

Django: How to access other model's primary key in urlpatterns?

I am getting NoReverseMatch when routing to a specific path.

It is not able to find the primary key <int:pk> for only one urlpattern while getting results for all other similar paths.

I am assuming this error is because the model here is different, ex,

Not getting error for:

class PostUpdateView():
   model = A

and the error I am getting is for:

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')]

Both classes are in same views.py file because I need model A's primary key in my routing url so that I can reverse to the original page.

Error:

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

What is the correct way to include both models' keys in same route?

Note: A's primary key is present in B as foreign key.

You get_absolute_url method should look like this the kwargs argument.

from django.urls import reverse

class AddCommentView():
   model = B

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM