如何在Django中为特定用户和特定项目使用deleteview?

时间:2018-02-09 01:59:14

标签: python django views

我有这些模特。每个回复都可以没有,一个或多个帖子。帖子是用户特定的。如何制作删除视图,以便用户只能在回复时删除其他帖子而不删除其他帖子。 我尝试了很多次,但我的观点是删除其他用户的帖子。意味着任何用户都可以删除任何其他用户的帖子。 我想在每个帖子旁边留一个按钮来删除,但只有那些写过帖子的人才能看到按钮。

class Reply(models.Model):
    User = models.ForeignKey(settings.AUTH_USER_MODEL)
    Question = models.ForeignKey(Doubt, on_delete=models.CASCADE)
    reply = models.TextField(max_length=40000)
    last_updated = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to = upload_image_path, null = True, blank = True)
    created_at = models.DateTimeField(auto_now_add=True)

    def Post(self):
        return reverse("community:post", kwargs={"pk": self.pk})



class Post(models.Model):
    post = models.TextField(max_length=4000)
    reply = models.ForeignKey(Reply, on_delete = models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    time = models.DateTimeField(null=True)
    User = models.ForeignKey(settings.AUTH_USER_MODEL)

1 个答案:

答案 0 :(得分:2)

如果AuthenticationMiddleware中启用了settings.py,则视图函数中的请求对象将包含用户模型。您的视图将如下所示:

from django import http

def get_post_from_request(request):
    ... something to pull up the post object from the request ...
    return the_post

def delete_post(request):
    the_post = get_post_from_request(request)
    if request.user == the_post.User:
        the_post.delete()
        return http.HttpResponseRedirect("/your/success/url/")
    else:
        return http.HttpResponseForbidden("Cannot delete other's posts")

如果您使用基于通用类的视图,那么您的视图可能看起来更像这样:

from django.views.generic import DeleteView
from django import http

class PostView(DeleteView):
    model = Post
    success_url = '/your/success/url/'

    # override the delete function to check for a user match
    def delete(self, request, *args, **kwargs):
        # the Post object
        self.object = self.get_object()
        if self.object.User == request.user:
            success_url = self.get_success_url()
            self.object.delete()
            return http.HttpResponseRedirect(success_url)
        else:
            return http.HttpResponseForbidden("Cannot delete other's posts")

如果您想帮助导航基于类的视图(它们具有密集的继承层次结构),我可以推荐http://ccbv.co.uk - 它们在删除视图中的细分为here