Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django context processor

Tags:

django

I have a bunch of variables that need to be available to the view for all templates. It seems the best choice would be a context processor.

The documentation says:

A context processor has a very simple interface: It’s just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

If I need to do more advanced lookups, can I define other functions? Do the functions need to be in a class? I was thinking of creating a file named context_processors.py in my app folder.

like image 475
Chris Muench Avatar asked Feb 12 '13 20:02

Chris Muench


People also ask

What is Django context processor?

A context processor is a Python function that takes the request object as an argument and returns a dictionary that gets added to the request context. They come in handy when you need to make something available globally to all templates.

What is RequestContext Django?

Context, but Django also comes with a subclass, django. template. RequestContext, that acts slightly differently. RequestContext adds a bunch of variables to your template context by default – things like the HttpRequest object or information about the currently logged-in user.

What is render in Django?

Rendering means interpolating the template with context data and returning the resulting string. The Django template language is Django's own template system. Until Django 1.8 it was the only built-in option available. It's a good template library even though it's fairly opinionated and sports a few idiosyncrasies.


1 Answers

You can define other functions, and the functions don't need to be in a class.

Typically people put their context processors into a context_processors.py like you're thinking of as functions, and then name them all in settings.TEMPLATE_CONTEXT_PROCESSORS.

For example, here's an app that has the context_processors.py inside it: django-seo.

like image 175
girasquid Avatar answered Sep 27 '22 23:09

girasquid