Eric
Eric

Reputation: 793

NoReverseMatch at /update/

I'm using the author name for posts in the url. I get this error after clicking on the submit button when updating the post or creating a new post:

Reverse for 'post-detail' with keyword arguments '{'id': 2, 'author': 'john'}' not found. 1 pattern(s) tried: ['(?P<author>[^/]+)\\/(?P<pk>[0-9]+)\\/$']

models.py

class Post(models.Model):
    

    title = models.CharField(max_length=100, blank="true")
    content =models.TextField(default="Enter details", verbose_name="Content")
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title 



    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'id' :  self.pk, 'author': self.author.username})

Views.py

class PostUpdateView(LoginRequiredMixin, UpdateView):
    model = Post 
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user ##author = current logged in user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True 
        return False 

urls.py

urlpatterns = [

    
    path('<str:author>/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('<str:author>/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
    path('<str:author>/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
   

]

Upvotes: 0

Views: 262

Answers (1)

danish_wani
danish_wani

Reputation: 872

'post_detail' URL accepts two keyword argument by the names 'pk', and 'author', so you need to change get_absolute_url to

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk': self.pk, 'author': self.author})

Upvotes: 1

Related Questions