Search code examples
djangohttp-status-code-404slug

Django: No post found matching the query when creating a post


I just got slugs to work for my Post model using django-autoslug. But i'm now experiencing this error when i try to create a new post:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/post/new/
Raised by:  blog.views.PostDetailView
No post found matching the query

Post Model

       class Post(models.Model):
            
            title = models.CharField(max_length=100)   
            author = models.ForeignKey(User, on_delete=models.CASCADE)
            slug = AutoSlugField(populate_from='title', null=True)
        
            def save(self, *args, **kwargs):
                self.slug = self.slug or slugify(self.title)
                super().save(*args, **kwargs)
            
            def get_absolute_url(self):
            return reverse('post-detail', kwargs={'slug': self.slug, 'author': self.author})

views.py

class PostDetailView(DetailView):

    model = Post

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(author__username=self.kwargs['author']) 

urls.py

urlpatterns = [

    path('', views.home, name='blog-home'),
    path('<str:author>/<slug:slug>/', PostDetailView.as_view(), name='post-detail')
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('<str:author>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'),
    path('<str:author>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Solution

  • If you request the /post/new URL, then this will match the post-detail view, since it can match post with the author, and new with the slug.

    You should reorder the url patterns, such that it first matches the post-create view:

    urlpatterns = [
        path('', views.home, name='blog-home'),
        path('post/new/', PostCreateView.as_view(), name='post-create'),
        path('<str:author>/<slug:slug>/', PostDetailView.as_view(), name='post-detail')
        path('<str:author>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'),
        path('<str:author>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'),
    
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

    By first specifying the post-create view, if a user visits /post/new/, it will thus trigger the post-create view.

    This thus also means that an author named post can not write an article named new, since then it will not trigger the post-detail view.