简体   繁体   English

如何在类视图的 success_url 中包含 get_absolute_url

[英]how do i include get_absolute_url in my success_url of a class view

how do i include the get_absolute_url defined in the model in the class based view?如何在基于类的视图中包含模型中定义的 get_absolute_url?

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)

You can override the .get_success_url() method [Django-doc] :您可以覆盖.get_success_url()方法[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.但是我认为您在这里使用.get_absolute_url()方法的方式是错误的:请参阅下面的注释。


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.注意get_absolute_url()方法[Django-doc]应该返回一个规范的 URL,这意味着对于两个不同的模型对象,URL 应该不同,因此指向特定于该模型对象的视图。 You thus should not return the same URL for all model objects.因此,您不应为所有模型对象返回相同的 URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM