This example show quickly how to apply django_roles
. As is necessary a
simple Django project and application, this example use Django’s
documentation polls app example for this. This example can be found
at Django_example.
Note
This example assume you have all the code of polls app.
Make sure you name views in polls/urls.py as in example you can found in
writing more views. Also note how app_name = 'polls'
is configured.
django_roles
¶Imagine you want to keep polls application public, in this way all users (anonymous or not) can vote a polls; but result should be restricted to a special users with specific role.
Achieve this is very simple with django_roles
:
Install django_roles
middleware; or add django_roles
decorators to
results views
...
from django_roles.decorator import access_by_role
...
@access_by_role
def results(request, question_id):
response = "You're looking at the results of questions %s."
return HttpResponse(response % question_id)
Go to admin site.
Create a new django_roles.models.ViewAccess
configure it:
polls:results
.By role
.django.contrib.auth.models.Group
representing the specific role.If new users need access to the view, you only need to add that user to the any of the groups added to roles attributes. This can be done in run time from admin site.
Note
Is not nice at all to receive 403 Forbidden after voting!!!. A simple code modification could help:
...
def vote(...
...
return HttpResponseRedirect(reverse('polls:index'))
Mar 15, 2019