限制用户对Django中不同应用程序的访问

编程入门 行业动态 更新时间:2024-10-20 05:39:42
本文介绍了限制用户对Django中不同应用程序的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的项目中有两个模型.两者都引用User类(我使用User模型来访问诸如authenticate和login_required之类的方法)

I have two models in my project. Both of which reference the User class (I used the User model to gain access to methods such as authenticate and login_required)

class Customer(models.Model): Customer = models.OneToOneField(User) CustomerID = models.CharField(max_length = 15) phone_regex = RegexValidator(regex = r'\d{10}', message = 'Enter your 10 digit Mobile number') Phone_no = models.CharField(max_length = 10,validators = [phone_regex],blank = True) Customer_wallet = models.IntegerField(default = 100) class Merchants(models.Model): merchant = models.OneToOneField(User) MerchantID = models.CharField(max_length = 15) Storename = models.CharField(max_length = 25)

当前,任何用户(无论他是商人还是客户)都可以访问整个网站.我该怎么使用以将客户限制为/Customer URL,将商人限制为/Merchant URL?

Currently any user(regardless of him being a merchant or a customer) has access to the entire site. What do I use to restrict a customer to /Customer url and a merchant to a /Merchant url?

def check_if_merchant(user): try: user.__getattribute__('merchants') except AttributeError: return False

我尝试了user_passes_test装饰器来检查用户是否具有商家或客户属性.但它似乎会自动重定向到尚未在urls.py中设置的/accounts/Merchants等.

I tried the user_passes_test decorator to check if the user has a merchant or a customer attribute. But it seems to be automatically redirecting to /accounts/Merchants etc which hasnt been set up in urls.py.

推荐答案

user_passes_test 只是一个简单的修饰符,是的,它确实重定向至记录的URL.

user_passes_test is just a simple decorator, and yes it does redirect to the login url as documented.

现在,由于 user_passes_test 调用了您自己的测试函数,因此,如果您要返回 403 Forbidden ,则只需提高 PermissionDenied 即可返回 False :

Now since user_passes_test calls your own test function, if you want to return a 403 Forbidden instead you just have to raise PermissionDenied instead of returning False:

from django.core.exceptions import PermissionDenied, ObjectDoesNotExist def check_if_merchant(user): try: user.merchants except (AttributeError, ObjectDoesNotExist): raise PermissionDenied else: return True

或者,您可以首先检查您是否有登录用户,如果没有,则返回False,以将未登录的用户重定向到登录页面:

Alternatively you can first check if you have a logged in user and return False if not, to redirect non logged in users to the login page:

from django.core.exceptions import PermissionDenied, ObjectDoesNotExist def check_if_merchant(user): if user.is_anonymous(): return False try: user.merchants except (AttributeError, ObjectDoesNotExist): raise PermissionDenied else: return True

更多推荐

限制用户对Django中不同应用程序的访问

本文发布于:2023-10-24 19:57:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   用户   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!