gpt4 book ai didi

python - 如何在 Django 中对特定用户和特定项目使用 deleteview?

转载 作者:行者123 更新时间:2023-12-01 02:11:00 24 4
gpt4 key购买 nike

我有这些模型。每个回复可以没有、一个或多个帖子。帖子是特定于用户的。如何创建删除 View ,以便用户只能删除自己的帖子,而不能删除其他人回复的帖子。我尝试了很多次,但我的观点是删除其他用户的帖子。意味着任何用户都可以删除任何其他用户的帖子。我想在每个要删除的帖子旁边创建一个按钮,但只有那些撰写该帖子的人才能看到该按钮。

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)

最佳答案

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

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")

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

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")

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

关于python - 如何在 Django 中对特定用户和特定项目使用 deleteview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48697645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com