Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have specific users see different webpages in Django?

I was wondering how one would handle a website that, once a user logged in, would be able to show a completely different page to each user?

  • Think of a master login/registration page.
  • Once a user registers, depending on their permissions, they would be redirected to the appropriate page for their user type (whilst not being able to access those of any other type).

So would this be an individual user/group permissions thing (using Django auth to do so)? Or would this be able to be implemented using models (i.e. have models of each type of user account and just hold instances in the database)?

This is my first week or so with Django (and web dev), so I am not at all familiar with this stuff.

like image 814
Ian Avatar asked Sep 20 '15 14:09

Ian


1 Answers

Redirecting users based on permissions

On the After a user logs in, let's say they land on a URL set by settings.LOGIN_REDIRECT_URL that can you can change to e.g./enter/ URL , and you can map that /enter/ URL to be backed by below view called enter_view()

from django.shortcuts import redirect

def enter_view(request):
    if request.user.has_perm('app_label.permission_codename'):
        return redirect('/page-A')
    elif request.user.has_perm('app_label.another_permission'):
        return redirect('/page-B')
    else:
        return redirect('/page-C')

To change your LOGIN_REDIRECT_URL simply put in settings.py

LOGIN_REDIRECT_URL = '/enter/' # or any URL you want

References

https://docs.djangoproject.com/en/1.8/ref/settings/#login-redirect-url https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#django.contrib.auth.models.User.has_perm https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#redirect

Checking permissions in your template

Further more if you need to customize small parts of a template, you can also check user permissions in similar manner using the {{ perms }} object

{% if perms.foo.can_vote %}
    <p>You can vote!</p>
{% endif %}

https://docs.djangoproject.com/en/1.8/topics/auth/default/#permissions

like image 188
bakkal Avatar answered Nov 14 '22 23:11

bakkal