Tarek Allam
Tarek Allam

Reputation: 139

How can I set up site-wide password protection and privilege requirements on views with Django?

My Django app is meant for internal use at the company I work at; however, it needs to be set up such that only certain employees with login credentials can access any of the web pages. Furthermore, I need to be able to customize the views so that only accounts with the right privileges can access them. How would I go about this?

My gut instinct is to use the same password protection and privilege system that the admin site uses since my project is basically just meant for viewing and editing the database easily. However, Google doesn't seem to turn up any information on how to do this, and I've only been working with Django for a month and half so I don't quite have the chops to figure this out myself. Is there a way to use the admin site's password protection and privilege system or is it inaccessible?

Upvotes: 1

Views: 127

Answers (1)

danny bee
danny bee

Reputation: 870

If staff privileges are enough this can easily be done using the staff_member_required view decorator. All you need is to apply the decorator to your view

staff_member_required Example:

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def random_view(request):
    #If the user does not have staff privileges he will be redirected to a login page 

If you are looking to test more specific privileges you should use the user_passes_test decorator. See: Django User Passes Test Decorator

You apply the decorator to your view and pass a function as a parameter that validates if a user should have access to that page, if the function returns True access is given normally, otherwise the user will be redirected.

user_passes_test Example:

from django.contrib.auth.decorators import user_passes_test

def user_is_author(user)
    #your test goes here, pseudo code example ignore syntax.
    return user.is_author

@user_passes_test(user_is_author)
def random_view(request):
    #if user passed the test the view will work normally

Upvotes: 1

Related Questions