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)
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!
– Leonardo Freitas
I edited the code to meet the Anonymoususer request
– Eduardo Silva
Thanks, all right! Thank you very much, and congratulations on your knowledge :)
– Leonardo Freitas