How do I test the user type and send to different views in DJANGO's generic views

0

Hello, I have a question in 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 the root "seller", etc. Disregarding the django admin, since I have more than two levels of access.

EX: I would like to allow in my view of user creation that only the "seller" user can create another user. How do I do that ? I have already tried to get the user object logged in with the "request.user" in generic view, but it does not work. Thank you very much from now on. If they can send a small piece of code as an example. Thanks!

Follow the view generic:

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

I would like to send to "new.html" only if the logged in user was a "seller" type, otherwise it would send to "accounts: dashboard".

My user template:

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)
    
asked by anonymous 02.06.2017 / 14:58

2 answers

1

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')
    
02.06.2017 / 19:14
1

Why do not you create groups instead of creating a custom User Model? Then treat everything with the permissions provided to the group. And to not have chance of forgetting to register a group or permission in the implantation of the site you can load data in syncdb using fixtures. fixture documentation

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

    
02.06.2017 / 19:44