Extending a base file in Django

Recently I was in need to have a code that could enable the extending of base file in other template files depending on type of user logged in into the site. This basically is used when we want different different look of site for different types of users. Following are the methods which I used before I finally got the right solution :

First I used the code something like this in my template file :

{% if user.is_superuser %}
{% extends "base.html" %}
{% else if user.is_active %}
{% extends "base_client.html" %}
{% else %}
{% extends "base_noclient.html" %}

But this code gave error.  It then did not set the correct blocks in the templates.

Then I thought to use include instead of extend, like :

{% if user.is_superuser %}
{% include "base.html" %}
{% else if user.is_active %}
{% include "base_client.html" %}
{% else %}
{% include "base_noclient.html" %}

This code managed to have different looks for different users but through this  all the site got de-structured.

Then finally with the help of Internet and Django mailing list I got the solution which goes as follows :
In the templates, use this code..
{% extends base_template|default:"base.html" %}

Here base_template is the variable that context manager will automatically insert into all the template contexts.
In some context_processors.py file(if there isn’t any, create it)  somewhere in your project, inclue this code :
def  base_template(request):
    if not request.user.is_active:
        return {“base_template”: “base_noclient.html”}
    if not request.user.is_staff:
        return {“base_template”: “base_client.html”}
    return “base.html”
After you have that file you need to add it to your settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
    ….
    “project.app.path.context_processors.base_template”, # make sure this is the actual path to the file.
)

 

When the views are defined and the templates are rendered, the request portion will automatically send the base_template variable into your template.
Thus this way we can extend as many files into he other depending on some conditions.
Toodles…  🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s