Home > Software design >  How do you add pK's in a django url
How do you add pK's in a django url

Time:05-09

I am makeing a blog and I want to go to a specific blog post by clicking on a button. I know I need to use a pk in the URL but I do not know the syntax or how to implement it any help would be appreciated.

CodePudding user response:

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})
  • Related