2014-11-09

Surprise in Django render()

The doc says render() (Note 1) is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.

It happens that render() takes a request object as its first argument, and a context_instance and a dictionary as two of its optional arguments. The context_instance is the context instance to render the template with. By default, the template will be rendered with a RequestContext instance (filled with values from request and dictionary).

As a Django beginner, I naively assume the request object will be automatically available in the template as I pass it as the first argument in the first place, and also because the context_instance argument forces the use of a RequestContext instance which is filled with values from the request object. Turns out that is not the case.

The request object is for the construction of the RequestContext only, which by default (as of Django 1.7) does not include the request object itself (Note2). It took me some time to figure that out.

To have the request object available in the template, I will have to pass it to render() in the dictionary argument:
    return render(request, template_name, {'request':request})
Or enable the request context processor at the settings, such that the request object will be automatically added to every RequestContext instance:
=== settings.py ===

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
    'django.core.context_processors.request',
)

2014-11-02

Appending to Django default settings

You can have a very minimal settings.py file in Django 1.7. Have you ever wondered how Django provides all the default settings?

All the default settings are defined in the module django/conf/global_settings.

There is usually no need to access the global_setting directly as explained in the doc..

The settings object will automatically get the default from the global_setting module on demand:
from django.conf import settings

if settings.DEBUG:
    # Do something
Or you can override a setting in settings.py like below:
DEBUG = True
However, if you ever want to add something to an existing setting instead of replacing it, you will need to do something like below in settings.py:
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
    'django.core.context_processors.request',
)