Home > OS >  how do i include get_absolute_url in my success_url of a class view
how do i include get_absolute_url in my success_url of a class view

Time:07-08

how do i include the get_absolute_url defined in the model in the class based view?

model

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
    name = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField(default="This is the Body of a Comment.")
    date_added = models.DateField(auto_now_add=True)
    time_added = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateField(auto_now=True)
    time_updated = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "Post Comments"
        ordering = ["-time_updated"]

    def __str__(self):
        return self.post.title   " | "   self.name.username

    def get_absolute_url(self):
        return f"/blogs/post/{self.post.slug}"

view

class DeleteCommentView(DeleteView):
    model = Comment
    template_name = "delete_comment.html"
    success_url = (refer the get_absolute_url)

CodePudding user response:

You can override the .get_success_url() method [Django-doc]:

class DeleteCommentView(DeleteView):
    model = Comment
    template_name = 'delete_comment.html'
    
    def get_success_url(self):
        return self.object.get_absolute_url()

But I think you are here using the .get_absolute_url() method the wrong way: see the note below.


Note: The get_absolute_url() method [Django-doc] should return a canonical URL, that means that for two different model objects the URL should be different and thus point to a view specific for that model object. You thus should not return the same URL for all model objects.

  • Related