Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a piece of code in every view in django?

Tags:

python

django

I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed.

Code looks like this:

try:
    admin_from_session = request.session['admin'];
    admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
except KeyError, Administrator.DoesNotExist:
    return HttpResponseRedirect('/controlpanel/login')

Question is: how can I run this code at the beginning of every view, without repeating it every time?

If I would write my program on PHP, i would put this code in separate file and write something like this at the beginning of every page that requires authorization:

include("redirect_if_not_logged_in.inc.php");

The solutions I found was:

  • inclusion tags - doesn't do, because I can't redirect anywhere from there
  • custom function - also doesn't do, because of the same reason.

The task seems trivial, but I can't find a solution. I would be very grateful for any help.

like image 459
Silver Light Avatar asked Feb 19 '10 12:02

Silver Light


1 Answers

Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.

BTW, why don't you use the built-in auth? You can use it with custom authentication backends...

like image 174
Ludwik Trammer Avatar answered Oct 15 '22 05:10

Ludwik Trammer