Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Django base template

I need to extend the base template for a page in my Django application, but there are a few HTML elements that I need to exclude from this new page that is in the base. What is the best way to remove them? Do I just delete the elements with JQuery?

like image 928
user995469 Avatar asked Oct 14 '11 13:10

user995469


People also ask

Can we customize Django admin template?

The Django admin is a powerful built-in tool giving you the ability to create, update, and delete objects in your database using a web interface. You can customize the Django admin to do almost anything you want.

How do you solve template does not exist in Django?

Django TemplateDoesNotExist error means simply that the framework can't find the template file. To use the template-loading API, you'll need to tell the framework where you store your templates. The place to do this is in your settings file ( settings.py ) by TEMPLATE_DIRS setting.

What does {% %} mean in Django?

{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.


1 Answers

You can use template blocks to achieve this. For example, in base.html, surround the HTML elements in a named block:

{% block a_unique_name %}<div>This is only relevant in base.html</div>{% endblock %}

The HTML in the block will be used only if no other template overrides it. You can override it in your sub-template like this:

{% extend base.html %}
{% block a_unique_name %}{% endblock %}

Now the value from sub-template will be used and will override the default value from base.html.

like image 78
George Cummins Avatar answered Nov 15 '22 07:11

George Cummins