简体   繁体   中英

Django - Login required for specific user type

I extended the user login from Django with AbstractUser like this:

class User(AbstractUser):
    pass
class Seller(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    verified = models.BooleanField(default=False)
    money = models.IntegerField(default=0)

def __str__(self):
    return str(self.user)

I would like now to create a view and a form that can only be access by the "Seller" user, like this in views.py:

@login_required
def account(request):
    return render(request= request,
               template_name='main/account.html',
               context = {})

Any idea on how can I do it? Thank you

You can make use of the @user_passes_test decorator [Django-doc] :

from django.contrib.auth.decorators import user_passes_test

def (user):
    try:
        
    except Seller.DoesNotExist:
        return False


def account(request):
    # …

This will only allow users that are authenticated, and for which the related Seller object exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM