May 22, 2010

Don't add unnecessary Context Processors

I guess we've all came across problem of using some attributes of our models in the templates. We know the solution for this : create your own context processor, add necessary values there, and voila ! We can use them across our site. But do we really always need to do this ?

Probably the most commonly used object is our User. We often need to check if the user is logged etc. But do we really have to add our user to a new Context Processor like this :
def user(request):
    if hasattr(request, 'user'):
        return {'user':request.user }
    return {}

Let's just take a look at our file. By default (in Django 1.2) TEMPLATE_CONTEXT_PROCESSORS variable looks like this :


And looking into documentation we can find :

"user -- An auth.User instance representing the currently logged-in user (or an AnonymousUser instance, if the client isn't logged in)."

Voila again ! Orly ? Well not exactly. Yes, this gives us ability to check {{ user.username }} and check if a User is authenticated. But what if we have another Model defining our user, with additional fields (and inheriting from contrib User)? Don't panic. There's also solution concerning this fact. Let's say our extended user model is called UserProfile. Open once again and insert this line :

AUTH_PROFILE_MODULE = 'accounts.UserProfile',

where 'accounts' is the name of the app where you're storing your extended model. And now as Django Docs say :

"When a user profile model has been defined and specified in this manner, each User object will have a method -- get_profile() -- which returns the instance of the user profile model associated with that User."

No comments:

Post a Comment