How do I test user type and send to different views in DJANGO Generic views

Asked

Viewed 594 times

1

Hello, I have a question at Django. I’m trying to do it this way. My user model has a "level" field, this field has some levels, among them "root", "seller" etc.. However, I would like to know how I can restrict some views only to "root", others only to "seller", etc. Disregarding the Django admin, since I have more than two levels of access.

EX: I would like to allow in my user creation view that only the "seller" user can create another user. How do I do that? I’ve tried to get the user object logged in with "request.user" in Generic view, but it doesn’t work. I really appreciate it already. If you can send a small piece of code as an example. Thanks!

Follow the Generic view:

class RegisterView(LoginRequiredMixin, CreateView):
    model = User
    template_name = 'new.html'
    form_class = UserAdminCreationForm
    success_url = reverse_lazy('accounts:login')

I would like to send it to "new.html" only if the logged in user was of the "seller" type, if it were not, send it to "Accounts:Dashboard".

My user model:

class User(AbstractBaseUser, PermissionsMixin):
    ADM = 0
    MAIN = 1
    SEL = 2
    AUT = 3
    USER = 5
    TYPES = (
        (ADM, 'root'),
        (MAIN, 'maintainer'),
        (SEL, 'seller'),
        (AUT, 'author'),
        (USER, 'user')
    )
    username = models.CharField(
            'Apelido / Usuário', max_length=30, unique=True, validators=[
            validators.RegexValidator(
            re.compile('^[\w.@+-]+$'),
            'Informa um nome de usuário válido. '
            'Este valor deve conter apenas letras, números '
            'e os caracteres: @/./+/-/_ .',
            'invalid'
            )
        ], help_text='Um nome curto que será usado para identificá-lo de forma única na plataforma'
    )
    name = models.CharField('Nome',max_length=100)
    email = models.EmailField('Email', unique=True)
    nivel = models.IntegerField(choices=TYPES, default=USER)
    is_staff = models.BooleanField('Equipe', default=False)
    is_active = models.BooleanField('Ativo', default=True)
    date_joined = models.DateTimeField('Data de Entrada', auto_now_add=True)

2 answers

2


You can try something like this:

from django.contrib.auth.mixins import AccessMixin


class SellerLoginRequiredMixin(AccessMixin):

    def dispatch(self, request, *args, **kwargs):
        if not request.user.nivel == User.SEL:
            return redirect('accounts:dashboard')
        return super(SellerLoginRequiredMixin, self).dispatch(request, *args, **kwargs)

And in the view:

class RegisterView(LoginRequiredMixin, SellerLoginRequiredMixin, CreateView):
    model = User
    template_name = 'new.html'
    form_class = UserAdminCreationForm
    success_url = reverse_lazy('accounts:login')
  • Man, it’s all right. Perfect! very good the solution. Just one more thing, when I try to access as Anonymoususer returns an error, as I can treat in this method Sellerloginrequiredmixin if it is not Anonymoususer. From now on, thank you very much!

  • 1

    I edited the code to meet the Anonymoususer request

  • Thanks, all right! Thank you very much, and congratulations on your knowledge :)

2

Why don’t you create groups instead of creating a custom User model? It handles everything with the permissions provided to the group. And in order not to have a chance to forget to register a group or permission to deploy the site you can upload data to syncdb using fixtures. Documentation of fixtures

And to check the permissions you use the has_perm() method of the User class Documentation of has_perm()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.