我创建了一个简单的问题应用程序,当点击问题时,它会显示其选项或选择。我制作了登录和注册表单以进行用户登录。我想知道如何限制用户删除仅由他们创建的问题。每个问题前面都有一个删除键。我阅读了有关权限的大部分内容,但没有了解如何操作。我可以申请不删除任何问题的权限,但如何限制用户不只删除某些特定问题或不是由他们创建的问题。下面是views.pydef addquestion(request): item_to_add = request.POST['content'] item = Question.objects.create(question_text=item_to_add,pub_date=timezone.now()) user_now = Question(user = request.user) item.save() return HttpResponseRedirect('/home/questions')def deletequestion(request,question_id): item_to_delete = Question.objects.get(id=question_id) if item_to_delete.user == request.user: item_to_delete.delete() else: return HttpResponse('You are not authorised to delete this question')这是模型.pyfrom django.db import modelsfrom vote.models import VoteModelfrom django.contrib.auth.models import User# Create your models here.class Question(VoteModel,models.Model): question_text = models.TextField(max_length=300) pub_date = models.DateTimeField('date published') user = models.OneToOneField(User,on_delete = models.CASCADE,null=True) def __str__(self): return self.question_textclass Choice(models.Model): choice_text = models.CharField(max_length=300) votes = models.IntegerField(default=0) question = models.ForeignKey(Question,on_delete = models.CASCADE) def __str__(self): return self.choice_text
2 回答
四季花海
TA贡献1811条经验 获得超5个赞
也许 request.user 是一个包含用户 id 的字符串,因此您必须先获取该 id 的用户对象,然后再将其与 item_to_dele.user 进行比较。
logged_user = User.objects.get(id=request.user)
if logged_user == item_to_delete.user:
# delete
item_to_delete.delete()
else:
return HttpResponse('You are not authorised to delete this question')
添加回答
举报
0/150
提交
取消