Divide Django base.html template into header, content and footer.html - django

Hi I have extended Django Admin templates into my app/templates/admin directory..
in that directory I have base.html which contains
<header> header content<header>
<body> body Content </body>
<footer> Footer Content</footer>
so I have created header.html which contains
{% extends "admin/base_site.html" %}
<!-- I also tried to include base.html here-->
{% block header %}
Header Html here...
{% endblock %}
and replaced base.html to below content
{% block header %} {% endblock %}
<body> body content </body>
<footer> Footer Content </footer>
but header content is not getting loaded.. so please suggest.

Use include before using block header from header.html.
And you don't need to create a block to include an HTML file into another.
In your header.html file, just write the code of header files.
Like this :
{% extends "admin/base_site.html" %}
Header Html here...
And, In your base.html try this code :
{% include "templates/header.html" %}
<body> body content </body>
<footer> Footer Content </footer>
Note : Use include "templates/header.html" as per your location of header.html

There is something missing in your approach. Let's see how the admin app loads a template:
The user asks for a page, eg /admin/.
The respective view in the admin app handles the request.
The view renders the index.html template.
This template extends the base.html template.
That's all of it. When you replaced the base.html template and added the new block, django looks for this block definition in the index.html. Your new header file is nowhere to be involved in this process.
No matter what you do with your templates, django will always try to render the corresponding view's template like the index.html (unless of course you change the views themselves). So you have the option to override any template starting from the last down to the first extend.
As Prakhar's answer recommended, in order to make django acknowledge your new header template file, you need to use an include directive.
If this is not working, make sure that you use the correct path to both your base file and to your include file.
Please also take into account that includes are far more expensive performance-wise than extends or simple overrides.

Related

How to create reusable components for UI in Django

I am building a project in Django which has 5 different applications inside it. Some applications are falling under same pattern and some are not. Can I create a UI components using bootstrap on the top of all these applications to reuse over the entire project. Any help would be appreciated.. Thanks in advance
Usually that is done by creating a base template and making other templates inherit from it like this:
base.html
<html>
<head>
<title>Title</title>
</head>
<body>
<navbar> # example navbar that will be visible in each template that will extend this one
<ul>
Home
Contact
Something else
</ul>
</navbar>
{% block content %} # here is where the content of child templates will be seated
{% endblock %}
</body>
</html>
then you will make any other template and extend it with base.html
your_other_template.html
{% extends 'base.html' %} # this line makes sure your child templates inherit the html of your main template
{% block content %} # here is where you will place the content of your other templates
<h1> This is the content of a child template </h1>
{% endblock %}
Paste your component in an empty html file and then use an include statement to load that file into you template html.
https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#include
This way you can insert you components more dynamically throughout your project.

Django asset manager for Views or template tags?

I come to Django having used the Yii2 PHP framework. One of the good features about that is it allows you to create asset files for CSS and JS which are then loaded into the base layout file at runtime. This allows you to keep the base template clean of CSS and JS markup within the head and at the bottom of the HTML document. The CSS and JS files you specify in the asset file are automatically placed in the correct position in the document and you can also specify dependencies if needed.
At the moment, with Django I am having to edit the base.html file manually which is not ideal.
I know you can use the Media class for forms, and in admin.py, which does a similar job. However, what I would like to do is to something like this (for example) in inclusion template tags or in a class based view perhaps.
Is this possible?
Many thanks!
UPDATE
Here is a similar question Is it possible to use django's custom template tags to insert code in other blocks in the template?
do you find block tag?
base.html
<head>
{% block extra_css %}{% endblock %}
<head>
view.html
{% extends 'base.html' %}
{% block extra_css %}
<link rel="stylesheet" href="YOUR URL">
{% endblock %}

Django how to dynamically add js and CSS in sub templates?

I am new to Django.
I have a basic template set up where I have base.html using {% block body %}{% endblock %} to include a sub template of index.html and test.html where they have {% extends 'base.html' %} at the top.
The base.html template includes Bootstrap. It is where the CSS and JS are included. index.html needs to include select2 but test.html does not.
I could use blocks here to solve my problem (adding CSS and JS block to base.html) but I see that as getting very messy very quickly.
Is there anyway I can use assets in Django to create a select2 asset and have that called in the sub template to register the needed JS and CSS with the parent template?
All I see is compression and numerous searches have, so far, come up empty.
It okay to add 2 more blocks in your base.html:
<some css>
{% block additional_css %}
{% endblock additional_css %}
...
<some js>
{% block additional_js %}
{% endblock additional_js %}
and the override them in any page extended from base.html:
{% extends "base.html" %}
{% block additional_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap-datetimepicker.min.css' %}">
{% endblock additional_css %}
...
{% block additional_js %}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.min.js"></script>
<script type="text/javascript" src="{% static 'js/bootstrap-datetimepicker.min.js' %}"></script>
{% endblock additional_js %}
That is a good practice because in this case the scripts will load in the very end and if some of your added script require for example JQuery, you won't face any problems.
It doesn't make the code messy, it's flat and easy to explain. It's better to think how not to make JS messy, and as you pointed, there are several ways to do this, on of them is to compress all the JS.
There are a few options that I can think of
The first is the ugly way that involves an {% if include_my_js_please %} in the base.html that is ignored if the context variable isn't included and for obvious reasons, arguments would be had if this made its way into our production code
The second is the way that you say can get very messy but its the way we do it and works very well for us, we have an {% extended_head %} and {% extended_footer %} in the base.html and as you'd expect we use this sparingly when required. Although we are very careful about what is included into this.
The third way is to just include everything in the base.html and only worry about it when it actually becomes a problem (I can see both the pros and con's of this)
and the fourth and final way I can think of is to make use of the Forms Media class
Django allows you to associate different files – like stylesheets and scripts – with the forms and widgets that require those assets. For example, if you want to use a calendar to render DateFields, you can define a custom Calendar widget. This widget can then be associated with the CSS and JavaScript that is required to render the calendar. When the Calendar widget is used on a form, Django is able to identify the CSS and JavaScript files that are required, and provide the list of file names in a form suitable for easy inclusion on your Web page.
Obviously this doesn't work in all use cases

Can't access tags with Django Includes

I have the following setup.
base.html
<html>
//etc
<body>
{% include "partials/footer.html" %}
</body>
</html>
partials/footer.html
<div class="footer">
<h2>{% block footer_headline %}Default footer headline{% endblock %}</h2>
</div>
page1.html
{% extends 'base.html' %}
{% block footer_headline %}NEW Footer Headline {% endblock %}
However, the footer headline does not change. What am I doing wrong?
This is a documented limitation. See the documentation: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include
The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process.
Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered - not blocks that can be overridden by, for example, an extending template.
The simplest solution is to not include templates that contain blocks you wish to overwrite. Just put the footer markup in the base.html

include static files from django template

I'm trying to include a static html page from a django template.
I tried using {% include the_static.html %} but this doesn't work for some unknown reason.
the_static.html page is a data page that will be modified often with an html editor.
and my_model has a url to this html and include it. But django refuses to find it although I'm sure I've setup the path correctly.
You can write your custom template tag to do this.
Create a file named includestatic.py under appname/templatetags/. Also, remember to create appname/templatetags/__init__.py, to include the app in settings and to restart the server.
includestatic.py should have this code:
from django import template
from django.contrib.staticfiles import finders
from django.utils.html import escape
register = template.Library()
#register.simple_tag
def includestatic(path, encoding='UTF-8'):
file_path = finders.find(path)
with open(file_path, "r", encoding=encoding) as f:
string = f.read()
return escape(string)
To use it in your template, put {% load includestatic %} at the top of your template, and then use the tag like {% includestatic "app/file.txt" %}.
I am not sure I understand everything yet...
You've an HTML page served by Django on a given url, let's suppose it to be http://mydjangodomain/get_the_static/. This URL is set in the urls.py of your model. Ok, that's normal.
You have a django template for this model. Let's suppose it's defined in a template directory mytemplates/mymodeltemplates/ and it's called myfrontpage.html (since in Django templates are html files).
I guess you've an URL defined in your urls.py to server that front page ? Let's suppose it's http://mydjangodomain/get_the_front_page/
Now I don't understand how your front page use your static html. Do your final front page html need the static's URL for a "src" attribute or something like it, or do you need to include the static's html into the front page's html ?
In the 1st case, you already have the URL, it's http://mydjangodomain/get_the_static/ so just use it as if.
In the 2nd case, you don't need the previous URL, get ride of it. Furthermore, put the_static.html in mytemplates/mymodeltemplates/. Then you need the {% include "/mymodeltemplates/the_static.html" %} tag. If this doesn't work, make sure you've the following in your settings:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
APPLI_ROOT_PATH = "<absolute_path_to_the_application_root_on_your_server>"
TEMPLATE_DIRS = (
'%s/mytemplates' % APPLI_ROOT_PATH,
)
Sort of resurrecting the dead, but at least with django 1.10, there's a very clean answer here:
http://www.effectivedjango.com/tutorial/static.html
an excerpt from that page:
Simple Template Inclusion We want to add the Boostrap CSS to all of
our templates, but we’d like to avoid repeating ourself: if we add it
to each template individually, when we want to make changes (for
example, to add another stylesheet) we have to make them to all the
files. To solve this, we’ll create a base template that the others
will inherit from.
Let’s create base.html in the templates directory of our contacts app.
{% load staticfiles %}
<html>
<head>
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}"
rel="stylesheet" media="screen">
</head>
<body>
{% block content %}
{% endblock %}
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
base.html defines the common structure for our pages, and includes a
block tag, which other templates can fill in.
We’ll update contact_list.html to extend from base.html and fill in
the content block.
{% extends "base.html" %}
{% block content %}
<h1>Contacts</h1>
<ul>
{% for contact in object_list %}
<li class="contact">{{ contact }}</li>
{% endfor %}
</ul>
add contact
{% endblock %}
Having followed this exactly, I now have a base.html that includes all my style references and the navigation bars/etc, so the html in the block content is merely the central contents of each (varying) page.
Do you mean that you want to EXTENDS the parent template the_static.html?
If yes, you should add below code at the first line of your children template:
{% extends "the_static.html" %}
Details documentation can be found here