python - Restricting User access to different apps in Django -


i have 2 models in project. both of reference user class (i used user model gain access methods such authenticate , 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 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) 

currently user(regardless of him being merchant or customer) has access entire site. use restrict customer /customer url , merchant /merchant url?

def check_if_merchant(user):     try:         user.__getattribute__('merchants')     except attributeerror:         return false 

i tried user_passes_test decorator check if user has merchant or customer attribute. seems automatically redirecting /accounts/merchants etc hasnt been set in urls.py.

user_passes_test simple decorator, , yes does redirect login url documented.

now since user_passes_test calls own test function, if want return 403 forbidden instead have 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 

alternatively can first check if have logged in user , return false if not, redirect non logged in users 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 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -