[英]How to restrict user acces to see/modify objects created by other users with Django
I'm making a hobby project with Django to store my ideas seperated by idea groups as the following: 我正在使用Django创建一个爱好项目,以按想法组存储我的想法,如下所示:
class Idea(models.Model):
name = models.CharField(unique=True, max_length=50)
description = models.TextField()
in_process = models.BooleanField()
is_done = models.BooleanField()
group = models.ForeignKey(Group, on_delete=models.CASCADE, blank=False)
class Group(models.Model):
name = models.CharField(unique=True, max_length=25)
description = models.CharField(max_length=50, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False)
Is there any way to restrict the currently logged in user from being able to see or modify ideas and idea groups created by other users using generic class based views? 有什么方法可以限制当前登录的用户使用基于通用类的视图来查看或修改其他用户创建的想法和想法组?
class GroupDelete(LoginRequiredMixin, generic.DeleteView):
model = Group
pk_url_kwarg = "id"
success_url = reverse_lazy('ideas:list')
...and a url for example: ...以及网址,例如:
urlpatterns = [
path('<int:id>/delete', views.GroupDelete.as_view(), name='delete'),
]
I'm using Django 2.0. 我正在使用Django 2.0。
I would suggest writing a custom mixin where you'd inherit the LoginRequiredMixin
and then add your own logic verifying that the currently logged in user (which you can retreive from request.user
) is the one who actually created the Group
object. 我建议您编写一个自定义的混合 ,在其中您将继承
LoginRequiredMixin
,然后添加您自己的逻辑,以验证当前登录的用户(可以从request.user
检索)是实际上创建Group
对象的用户。
Simple example would look something like this: 一个简单的示例如下所示:
# mixins.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseNotFound, HttpResponseRedirect
class YourCustomMixin(LoginRequiredMixin):
def dispatch(self, request, *args, **kwargs):
can_access = ... logic to check if user can access Group ...
disp = super().dispatch(request, *args, **kwargs)
if not isinstance(disp, HttpResponseRedirect) and not can_access:
return HttpResponseNotFound()
return disp
Once you have a value for the can_access
flag, you call the LoginRequiredMixin
's dispatch
method and check if the result of that call is a redirect (to the login page) and check against the can_access
flag, and then either return HttpResponseNotFound()
or the original disp
result. 一旦有了
can_access
标志的值,就可以调用LoginRequiredMixin
的dispatch
方法,并检查该调用的结果是否是重定向(到登录页面)并对照can_access
标志进行检查,然后返回HttpResponseNotFound()
或原始disp
结果。
Of course, you could also return HttpResponseForbidden()
instead of HttpResponseNotFound()
. 当然,您也可以返回
HttpResponseForbidden()
而不是HttpResponseNotFound()
。
You can then use it in your views, eg: 然后可以在视图中使用它,例如:
from your_app.mixins import YourCustomMixin
class GroupDelete(YourCustomMixin, generic.DeleteView):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.