开发者

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

I ne开发者_如何学JAVAed 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.


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...


I found the answer I was looking for. Function decorators allow to run a peace of code at the beginning of a function.

You must define a decorator function

def login_please_decorator(view_func):
    """
        Redirect if admin was not logged in
    """
    def _decorated(request, *args, **kwargs):
        #Check authorization
        try:
            admin_from_session = request.session['admin'];
            admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
            return view_func(request,*args, **kwargs);
        except KeyError, Administrator.DoesNotExist:
            return HttpResponseRedirect('/cp/login?ret=' + request.path);

    return _decorated 

And decorate a view using this function name:

@login_please_decorator
def some view(request):   
    # do something ...
    # ...

Ludwik Trammer, bugspy.net, thank you for your help.


Function decorators comes to mind


Take a look at the User authentication page here http://docs.djangoproject.com/en/dev/topics/auth/

Read on to "The login_required decorator".

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
   ...

You can setup where the user is to be redirected if not authenticated via the setting "settings.LOGIN_URL".

At the page there is also an example for a special authentication template you can style to anything you like!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜