How to restrict access to pages based on user type in Django

django restrict access to url
django restrict access by group
django custom permissions
django permissions
django restrict access to media files
django user model
django check user permission
django custom login page

I have a basic question which can be useful for new Django developers.

I created my own UserProfile in Django. This UserProfile has a specific field called 'type'. This field can have two values (until now maybe more in the future) : Male - M / Female - F :

from django.contrib.auth.models import User

GENDER = (
    (M, 'Male'),
    (F, 'Female'),
)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    type = models.CharField( max_length=2,
                             choices=GENDER,
                             default='F')

Basically, I wanted to allow access to restrict access or to adapt page content depending on user Type. Until now, I used a really basic and beginner approach which is to test user type in a view and then process the page:

def OnePage(request):
    if request.user.type == 'M':
        ....
    else if request.user.type =='F':
        ....

Then I also need to adapt the template rendered depending on user type: a male user will not have the same profile page that a Female User.

I am sure there are better ways to do this but as a Django beginner I am quite lost with all of Django possibilities. So if you have any best practices to implement this please tell me (obviously I would like a DRY code I could use on every view!)

Thank you for your help.

One solution could be to change the base template name depending on the user type:

@render_to('some_template.html')
def some_view(request):
    base_template = 'base_%s.html' % request.user.profile.type
    # …
    return {
        'base_template': base_template,
    }

And in your template :

{% extends base_template %}
{% block some-block %}
…
{% endblock %}

If you need to do this on every view, you could use a middleware to set this value.

How to restrict access with Django Permissions · Coderbook, Restrict access to unauthenticated users in Django Views. To simply restrict access to a view based on if the user is authenticated (logged in) or not does not require you to dive deep into the permission system at all, you can simply do it with Decorators, Mixins or the user is_authenticated property. Restrict access to unauthenticated users in Django Views. To simply restrict access to a view based on if the user is authenticated (logged in) or not does not require you to dive deep into the permission system at all, you can simply do it with Decorators, Mixins or the user is_authenticated property. Restrict access to logged in users in Function based views

To restrict access, use the user passes test decorator:

from django.contrib.auth.decorators import user_passes_test

male_only = lamda u: u.type == 'M'
female_only = lamda u: u.type == 'F'


@user_passes_test(male_only)
def myfunc(request):
   pass

@user_passes_test(female_only)
def myotherfunc(request):
   pass

Django Tutorial - User Specific Pages/Access, This django tutorial covers how to restrict access to pages or information to specific Text Duration: 14:14 Posted: Apr 30, 2019 Login Required & Permission Required Decorators If you have worked with Django, you probably have used the login_required decorator already. Adding the decorator to a view limits access only to the logged in users. If the user is not logged in, s/he is redirected to the default login page.

To add extra data to User see

Storing additional information about users

Then add the profile to your context and you can use {{profile}} variable in your template

{% if profile.type == "F" %}
    blah, blah
{% else %}
    blah, blah
{% endif %}

Configure Role Based Access Control In Django, Role Based Access Control provides restrictive access to the users in a system All of the permissions that Django creates underclass Permission will have a You need Role-Based Access control for this kind of permission in your a login_url which can be used to pass the URL to your login/error page. Introduction. Restricting the access to some kind of resource it is a common need in any web application, by far, the most frequent implementation of such restriction is checking if the user is authenticated using a login form, and this is the topic of this post on Django.

Depending on what you want to do, if you need to use very different html for different genders, you can try this approach:

def gender_filter(func):
    def _view(request,*args,**kwargs):
        res=func(request,*args,**kwargs)
        if request.user.get_profile().type=='F':
            res.template_name='template_f.html'
            res.context_data['gender']='female'
        elif request.user.get_profile().type=='M':
            res.template_name='template_m.html'
            res.context_data['gender']='male'
        return res.render()
    return _view

@gender_filter
def my_view(request):
    t=TemplateResponse(request,'template_f.html',{...})
    return t

So instead of returning Http resonpse in views, you can make them return TemplateResponse objects and use decorators to change templates, add in general context, and them convert them to HttpResponse.

Or something like a permission check:

def gender_only(gender):
    def _dec(func):
        def _view(request,*args,**kwargs):
            if request.user.get_profile().type==gender
                return func.render(request,*args,**kwargs)
            else:
                raise Exception("You do not have the right gender")
        return _view
    return _dec

@gender_only('F')
def my_view(request):
    ...
    return render_to_response('template.html',{...},context_instance=RequestContext(request))

Django Tutorial Part 8: User authentication and permissions, The framework includes built-in models for Users and Groups (a generic way The database tables for users and model permissions were created when Note​: In this case, we could reasonably put the authentication pages,  Restricting Pages. Now time to restrict access to users that are not logged in. For this example we will only restrict access to viewing a To Do List that is not yours but you can do this anywhere. If a user tries to access a To Do List that they did not create we will simply redirect them to the home page.

How to Implement Multiple User Types with Django, Never user the built-in Django User model directly, even if the built-in Django User The is_superuser flag is an additional flag to assign all permissions a certain type of users can see and interact with some specific pages. Django admin site: access, filtering and restricting¶ Tags: django. I’m going to show you how to filter what’s shown in django’s admin based on the current request, so for instance limiting the list of objects to what the current user has permission to see. Django’s build-in admin site is pretty great.

Using the Django authentication system, Django comes with a built-in permissions system. Permissions can be set not only per type of object, but also per specific object instance. The raw way to limit access to pages is to check request.user.is_authenticated and either redirect to  Hide or show HTML based on user's role If the information you're hiding is sensitive, this may not be a workable solution for you since the full text can be shown by Viewing Source in the browser. However, find below a sample code to implement in your Help Center and a screencast showing where to put it.

User authentication in Django | Django documentation, It handles user accounts, groups, permissions and cookie-based user sessions. is the Django content type system, which allows permissions to be associated  2. Never user the built-in Django User model directly, even if the built-in Django User implementation fulfill all the requirements of your application. At least extend the AbstractUser model and switch the AUTH_USER_MODEL on your settings. Requirements always change.

Comments
  • What do you mean by a middleware ?
  • It's in the documentation
  • Yes that's what I did until now. But is there a way to not repeat myself on every page where I need to do this process ? Like a decorator or something else ?