views:

64

answers:

3

So I have an app called stats that lets me query my database in various ways and return information in a JSON format so I can have a nice ajaxy dashboard for graphing and visualizing. I'd like this app to be as reusable as possible, naturally, so I don't want to necesarily use the @login_required decorator on its views. In my case, however, I do want a login to be required before viewing any of the apps views. Is there a way to do this somewhere other than the views?

Perhaps something like this in my site's urls.py? (I know this won't work, an example of what I'm looking for)

urlpatterns = patterns('',
        (r'^stat/', include('stats.urls'), login_required), 
)
+2  A: 

If you're concerned about reusability, rather than using login_required, you could use a decorator which requires login if a particular argument is passed to the view (which might default to a value of True). Off the top of my head, it might look a little like this:

from django.contrib.auth.decorators import login_required

def login_possibly_required(view_func):
    def inner(request, *args, **kwargs):
        try:
            require_login = kwargs.pop('require_login')
            if require_login:
                return login_required(view_func)(request, *args, **kwargs)
        except KeyError:
            pass
        return view_func(request, *args, **kwargs)
    return inner

Then you'd define your views like so:

@login_possibly_required
my_view(request, arg1, arg2, require_login=True):
    pass

Not tested, but you get the idea.

ozan
This seems like a fairly nice way of doing it, I was thinking of doing something like this based off of something like STATS_LOGIN_REQUIRED being set in settings.py, but I think I like your way better.
gct
+6  A: 

You can apply decorator for individual urls in urls.py in this manner:

from django.contrib.auth.decorators import login_required
import views

(r'^stat/', login_required(views.index))
Eugene Morozov
Huh. I had not thought of that.
Ignacio Vazquez-Abrams
Very nice to know, but I'd still have to use the login_required in my stats app (as I just include the urls.py from the site). I think ozan's answer is the best for my application. Nice to know I can decorate other people's views easily if I want though.
gct
+3  A: 

you can use a middleware for that

here is example snippet - http://www.djangosnippets.org/snippets/1179/

you can use this snippet and define LOGIN_EXEMPT_URLS in your settings or modifiy it a little bit for your case

Pydev UA
That's actually quite nice, and might be what I want since this is for a website that's internal-use only, we might want to require logins for (almost) every view, so this might be a good solution.
gct