Sam Starling
Sam Starling

Reputation: 5378

Django: Context processors in views, bad practice?

In my Django project, I have a context processor which returns a FacebookUser object based on the cookies present in the request (using Facebook's Python SDK). This means that when the user is logged in, their corresponding FacebookUser object is always available in my templates.

However, what should I do when I want to access this in views too?

Option 1: In each view where I want to access this FacebookUser object, call the context processor method, or a method that does exactly the same thing.

Option 2: Again, in each view, call RequestContext(request) in order to get access to the existing object added to the context by the context processor.

Which is better practice, and are there any recommended ways of working here?

Upvotes: 0

Views: 2101

Answers (3)

Mp0int
Mp0int

Reputation: 18737

If you need your FacebookUser object a lot then use middleware. Documentation is here

For a sample middleware class:

class FacebookApiIntegrator(object):

    def process_request(self, request):
        if request.user.is_authenticated():# check if user has logged in
            request.facebook = <your profile func or obj..>

and in any view you can just use:

request.facebook

But do not forget, that your middeleware will run for every request and add your facebook profile object to request for every request of a logged in user. So using middleware for an object that do not used often is not a good idea.

Upvotes: 3

S.Lott
S.Lott

Reputation: 391962

You're already using middleware.

https://docs.djangoproject.com/en/1.3/topics/http/middleware/#middleware

You just need to implement process_request and it's done in every request.

https://docs.djangoproject.com/en/1.3/topics/http/middleware/#process_request

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799160

Option 1. Delegate the context processor's work to another function, and call that function.

Upvotes: 1

Related Questions