Search code examples
djangoblogs

Django get_absolute_url() doesn't seem to work in comment section


I'm trying to get my users to the article page after comments, but something is missing.

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments" ,on_delete=models.CASCADE)
    name = models.CharField(max_length=30)
    body = RichTextUploadingField(extra_plugins=
    ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')])
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)

    class Meta:
        verbose_name = "comentario"
        verbose_name_plural = "comentarios"
        ordering = ['date_added']

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

urls.py

 path('article/<int:pk>/comment/', AddCommentView.as_view(), name='add_comment'),
    path('article/<int:pk>', ArticleDetailView.as_view(), name="article-detail"),
    path('article/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'),
    path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'),

For the update_post the get_absolute_url() works. Thanks in advance.


Solution

  • You would need to pass a parameter which belongs to the ArticleDetailView model. For example if the model for the ArticleDetailView is Post:

    class ArticleDetailView(DetailView):
        model = Post
    

    The get_absolute_url should use a post.pk:

    class Comment(models.Model):

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

    In your case it is not working as it is using the Comment pk with the Article(Post) view