Django: Generic detail view must be called with either an object pk or a slug

后端 未结 6 968
别那么骄傲
别那么骄傲 2021-02-01 14:26

Getting this error when submitting the form associated with this view. Not sure what exactly is the problem, considering I have a form with a very similar structure and it works

6条回答
  •  眼角桃花
    2021-02-01 15:15

    Like Robin said, you can use pk_url_kwarg if you want custom pk name.

    But as addition, issue Generic detail view must be called with either an object pk or a slug raises also in slug.

    So if you want to create custom slug field (no need to use pk or slug name). You can override slug_field and slug_url_kwarg in your DetailView class.

    Here is just another example if you want url as Slug Field.

    models.py

    class Post(models.Model):
        title = models.CharField(max_length=255)
        url = models.SlugField()
        body = models.TextField()
        image = models.ImageField(upload_to='blog/', blank=True, null=True)
    

    views.py

    class ListPost(ListView):
        model = Post
        template_name = 'blog/list.html'
        paginate_by = 2
        context_object_name = 'posts'
    
    class DetailPost(DetailView):
        model = Post
        template_name = 'blog/detail.html'
        slug_field = 'url'
        slug_url_kwarg = 'url'
    

    urls.py

    urlpatterns = [
        path('', ListPost.as_view()),
        path('/', DetailPost.as_view()),
    ]
    

提交回复
热议问题