'How do you add primary keys in a Django URL?

I am making a blog and I want to go to a specific blog post by clicking on a button. I know I need to use a primary key in the URL, but what is the syntax? And how can I implement it?



Solution 1:[1]

Here is some syntax for when you want to use a URL to go to a particular model's instance. You can tweak it for your needs, eg the "int:pk" and the kwargs={"pk": self.pk}.

In your app's urls.py, add

path('mypage/int:pk/',views.myPageDetail.as_view(),name='mypage_detail'),

in your models.py class based Model, add a function to your model

def get_absolute_url(self):
    return reverse("mypage_detail", kwargs={"pk": self.pk})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Lipschitz