简体   繁体   中英

Django models.py does not have pk

I am creating a blog app. In this app, users create blog posts and see those. I have a problem to let the posts have its url related with pk and slug.

models.py

class BlogPost(models.Model):
title                   = models.CharField(max_length=50, null=False, blank=False)
body                    = models.TextField(max_length=5000, null=False, blank=False)
image                   = models.ImageField(null=True, blank=True)
date_published          = models.DateTimeField(auto_now_add=True, verbose_name="date published")
date_updated            = models.DateTimeField(auto_now=True, verbose_name="date updated")
author                  = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug                    = models.SlugField(blank=True, unique=False)



def __str__(self):
    return self.title

def get_absolute_url(self):                                             
    print(self.pk, self.slug)
    return reverse('blog:detail', kwargs={
        'pk': self.pk,
        'slug': self.slug
    })

views.py

app_name = 'blog'

urlpatterns = [
    path('create/', create_blog_view, name="create"),
    path('<pk>/<slug>/', detail_blog_view, name="detail"),
    path('<slug>/edit/', edit_blog_view, name="edit"),
 ]

The problem is that models.py only has slug not pk. So it fails to create the url. How could I do with this problem? Thank you in advance.

...
def get_absolute_url(self):                                             
    return reverse('blog:detail', args=[self.id, self.slug])
...

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