Restrict access by url

1

In my application I have the user model that extends AbstractUser and I have added two boolean fields, my question is, how can I make the user not enter certain views by url depending on whether it is validator or is a digitizer? So far I have only done such validations at the template level but if I type in the address bar the template is rendered, it would be nice if I can make it return to the previous view.

User model:

class User(AbstractUser):
    creado_por = models.ForeignKey('self', null=True)
    es_digitador = models.BooleanField(default=False, help_text=_('Indica si el usuario tiene permisos de crear y modificar.'),)
    es_validador = models.BooleanField(default=False, help_text=_('Indica si el usuario tiene permisos de validar la informacion.'),)
    
asked by Mauricio Villa 25.07.2017 в 02:28
source

1 answer

1

This can be done in several ways, it also depends on whether you are using generic views or not.

from django.core.exceptions import PermissionDenied


def my_view(request):
    # esta vista solo la puede ver un digitador
    if request.user.es_digitador:
        return render(request, {}, 'template.html')
    else:
        raise PermissionDenied

Another way to do it would be:

from django.contrib.auth.decorators import user_passes_test

def digitador_check(user):
    return user.es_digitador

@user_passes_test(digitador_check)
def my_view(request):
    ...

For more documentation you can go to the official documentation Here I leave some links where I have used them in some of the applications that I have developed and I have uploaded them to gitlab :

using mixins:

class SuperUserRequiredMixin(ProfileMixin, View):
   # clase mixin que se encarga de comprobar si el usuario es superuser o no
    def dispatch(self, request, *args, **kwargs):
        if request.user.is_superuser:
            return super(SuperUserRequiredMixin, self).dispatch(request, *args, **kwargs)
        else:
            raise PermissionDenied


class DashboardView(SuperUserRequiredMixin, TemplateView):
    # vista que solo puede ser vista si el usuario es superuser, sino, muestra un error 403 (forbidden)
    template_name = 'account/dashboard.html'

using Mixins and decorators

these examples are for class-based views, I think the code explains everything. Greetings

    
answered by 25.07.2017 / 03:03
source