Django template extends tag added extra space on top - django

I am using Django template with the built-in extends tag, I didn't put too much code in it, just a nav bar, but I get extra space on top of the browser, and that can not be traced in chrome developer tools. That extra space still exists, even if, I did like this:
# base.html
<!doctype html>
<html>
<head>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/layout.css" %}" />
</head><body>
<div><p>something here.</p>
</div>
</body>
</html>
and then I extend it with just one line of code:
# home.html
{% extends "base.html" %}
Then rendered file still have this problem. I am using Django3.3 Python 3.3 with Django1.6.
It was really strange.

Finally I find the problem was due to UTF-8 BOM in encoding.
I use Django1.6, Python3.3, on Windows7. My text editor is Notepad++, and I used to save files under UTF-8 encoding. By default, UTF-8 is saved with a byte order mark(BOM). It was this that affects the rendering of templates, at least for the tag of extends and include. Let's say, I put it in an example:
# home.html
{% extends "base.html" %}
{% block content%}
{% include "a.html" %}
{% include "b.html" %}
{% endblock %}
and
# base.html
<!doctype html>
<html>
<head>
<!-- This file saved with encoding UTF-8, which is by default with BOM.-->
</head>
<body>
<div><p>something here, base.</p></div>
{% block content%}{% endblock %}
</body>
</html>
and
# a.html
<p>a.html, saved in utf-8 without BOM. </p>
and
# b.html
<p>b.html, saved in utf-8, which is by default with BOM in Notepad++.</p>
what will be the output? It will look like this
___________ ( top of your browser )
( extra space on top, due to extended file `base.html` is with BOM )
something here, base.
a.html, saved in utf-8 without BOM. (no extra space above the content of a.html)
( extra space on top, due to included file `b.html` is with BOM )
b.html, saved in utf-8, which is by default with BOM in Notepad++.
so, basically, for any file loaded by the template, if it is with BOM, then the rendered html will add extra spaces on top of its section. Therefore, remember to save all the files with UTF-8 without BOM.
Note: I have tried earlier to use {% spaceless %}{% endspaceless %} on my base.html or home.html, but this cannot solve the problem, the extra spaces wasn't due to spaces or \n between html tags.

Django most recent version is 1.7 not 3.3, and your first code comment will be base.html not base.py.
You got this extra space because of you have leave space in your base.html file. remove the top extra space of your base.html file.

First of all, you might have Django 1.7, and Python 3.3 because Django 3.3 doesn't exists (and will maybe exists in a decade only :-) )
Second, extra spaces are present in the HTML rendered because Django keeps everything except tags from the template. So if you have a template like this:
{% load static cache compress %} <!-- <- You have here a \n to create a new line -->
{% block htmlheader %}
<!DOCTYPE html>
<html lang="fr">
<head>
....
the rendered will interpret ths {% load %} tag, remove it (actually not include it) in the rendered HTML page, and continue to parse the content. Same behaviour with the {% block %} tag, which will leave a \n too. The result will be
<!-- A blank line due to the load tag -->
<!-- A second blank line due to the block tag -->
<!DOCTYPE html>
<html lang="fr">
<head>
....

Related

using Django "include" template tag as nested - side effects?

Does anyone know or have any experience about bad side effects of using "nested include tags"?
(I mean including a template file which itself includes another template)
For example:
file x.html:
{% include "z.html" %}
file y.html:
{% inclide "x.html" %}
Bad side effects are messed up CSS rules and some headache while debugging. It is generally better to keep them rather flat.
x.html:
{% extends "_base.html" %}
{% block main_content %}
<h1>I am X</h1>
{% include "includes/z.html" %}
{% endblock main_content %}
y.html:
{% block main_content %}
<h1>I am Y</h1>
{% include "x.html" %}
{% endblock main_content %}
z.html:
<h2>I am Z</h2>
Check the code:
https://github.com/almazkun/templating
I think you are confusing include and extends
Logically, extending a template when used in the likes of a base.html is great, and if you design your templates in a way which allows you to extend certain base html files for certain sections of your site. This is generally when they have shared snippets of html, like the main css block, meta block, script block etc..
You can extend n number of times.
Where you are getting confused with include, is that this is more for including snippets of code which are additive or sort of "drop-in" and great examples would be sidebars, navbars, and even custom css or javascript!
The question is, do you want to shared html snippets, or do you want to add extra snippets to certain sections but not others?
If its the latter, you'll want include, and for the former, you'll want extends.
Edit #1:
You have asked for clarity regarding the drawbacks of the two aforementioned template tags. As I sit here and ponder that question, I cant think of any significant disadvantages of using either include or extends providing that you have used them where they should be used. If you have used an include, where actually you should have used extended the template, you may find, as is described in someone else's answer, that css rules may not be applied in the way you would expect them to be.
The question is about nested include tags and the answers show that "there is no actual problem if you know what you expect and how to handle it".
There is a paragraph in the docs about the include tag that sets some limits, nonetheless:
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.
Trying to make ends meet about rendering and parsing:
https://stackoverflow.com/a/35966477/2996101
Shared state between included templates is a complicated issue even for big front end frameworks, such as React.
No problem! It's usual to use inheritance in Django templates. You can make a template with some blocks and override blocks in children templates and children of children can override or use superblock content.
I didn't have any issues chaining include. You might have issues if have extend or blocks with similar names in the included template.
There are no issues when you include a number of templates.
for example
base.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
{% block title %}{% endblock %}
</head>
<body>
{% block content %}
{% endblock %}
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
-->
</body>
</html>
a.html
<h1>I am from A</h1>
b.html
<h2>I am from B</h2>
c.html
{% extends 'base.html' %}
{% load static %}
{% block title %}<title>Welcome in C!</title>{% endblock %}
<h3>I am from C . I am mother of A and B </h3>
{% block content %}
{% include 'a.html' %}
{% include 'b.html' %}
{% endblock %}

Django 3.0: How to use different Boostrap versions in same template

I have made a template (Base.html) in my django project, of Bootstrap 4 which working is fine independently.
I have also made another template (Child_Base.html) which is made with Bootstrap 3 and supposed to be injected in Base.html.
But what happening here is, when I include BS3 template in first one it is ruining many things. So, I am looking for a solution in which both co-exist and doesn't spoil other one.
Code of Base.html is supposed as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<p>
{% block bodyblock %}
Hello World!
{% include "Child_Base.html" %}
{% endblock %}
</p>
</body>
</html>
Code of Child_Base.html is supposed as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body>
<p>
{% block bodyblock %}
Good Morning!
{% endblock %}
</p>
</body>
</html>
In actual scenario, there is product page, displaying all the books available for user to add in cart (made in BS4) in which I want to include search box (made in BS3). But code is tangled and not so self-elaborated so I have used above examples. Thanks.
why you want this?
you either include CSS files in your templatename.html file or in a different name.css file that is linked to your template, when you include bt3 and bt4 browser DOM looks like this:
pages:
index.html
files:
bt3.min.css
bt4.min.css
and then it gets crazy cause two different CSS files with same tags are in browser DOM.
I'm not telling this is not possible cause in frontend frameworks like vue.js you can config it to use CSS locally just for one component, but Django doesn't generate files like that so you can't have two different CSS files isolated from each other for one HTML page.
on second Thought:
maybe if you make your page.html with a scheme like this:
headers and other head tags...
<body>
<section>
<style>
include the entire bootstrap 4 css here
</style>
enter your bt4 elements here
</section>
<section>
<style>
include entire bootstrap 3 css here
</style>
enter your bt3 elements here
</section>
</body>
you should put .min.css in this may cause the browser to render the page with your desired styles as always CSS files are overwritten by lower CSS's in the file.

Removing newlines from the end of base.html file makes some elements disappear from DOM

This is a strange bug. I have an html file that extends a base template called base.html. I noticed that a script tag right before the end body tag in the base template doesn't show up in the DOM in the Elements tab of the Chrome dev tools, and the tag is cut off completely along with the rest of the html file in the Sources tab. This happens in Chrome, Mozilla, and Safari, so it must be a problem on the Django side. And obviously the observable effects on the page that the script should create aren't happening either.
Here's the end of the rendered html in the Sources tab:
<section>
what is going on
</section>
<footer></footer>
<script src="/static/home/js/ba
Completely cut off. Here's the end of that base template:
{% block main %}{% endblock %}
<footer></footer>
<script src="{% static 'home/js/base.js' %}"></script>
{% block js %}{% endblock %}
</body>
</html>
Now, here's where it gets funny. The trouble is at the end of the file, so I just added some newlines to see if there's any difference in the DOM is rendered:
{% block main %}{% endblock %}
<footer></footer>
<script src="{% static 'home/js/base.js' %}"></script>
{% block js %}{% endblock %}
</body>
</html>
And the Sources tab showed a cut off later in the tag:
<section>
what is going on
</section>
<footer></footer>
<script src="/static/home/js/base.j
I won't paste it here, but I added about 35 newlines to the end of the file before I got what I wanted in the Sources. It seems that every newline cuts off the rendered html one character later.
<section>
what is going on
</section>
<footer></footer>
<script src="/static/home/js/base.js"></script>
</body>
</html>
And the effects from the script finally worked. This feels like a temporary solution to something deeper that needs to be fixed. Anybody have any clue what the hell is going on or where to look?
Edit: Here's the template (located in the work app) that extends base.html (located in the home app), called work.html:
{% extends 'home/base.html' %}
{% block css %}
<link rel="stylesheet" href="{% static 'work/css/work.css' %}">
{% endblock %}
{% block main %}
<section>
hello
</section>
{% endblock %}
And here is the view that renders it:
from django.shortcuts import render
def work(request):
return render(request, 'work/work.html', {})
Edit 2: some more unexpected results:
When I deleted the script (so that I can paste it in head as suggested in the comments), the end of the rendered html was this:
<section> what is going on </section>
And pasting right before the </head> tag resulted in:
<section> what is going on </section>
<
Same result above when I commented it out in head.
Commenting out the script when it's before the </body> results in this:
<section> what is going on </section>
<footer></footer>
<!-- <script src="/static/home/js/base.j
And replacing single quotes with double quotes resulted in the rendered html showing double quotes instead of single quotes as the only difference. :/
Then I deleted almost everything so that my code was this:
<!DOCTYPE html>
<html lang="en-US">
<head>
</head>
And that rendered:
<!DOCTYPE html>
<html lang="en-US">
<head>
<scrip
I added back some tags:
<!DOCTYPE html>
<html lang="en-US">
<head>
</head>
<body>
</body>
</html>
And the result:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="http://127.0.0.1:357
For some reason, the script tag generated by django-livereload-server remains. This is what the full script tag looks like:
<script src="http://127.0.0.1:35729/livereload.js"></script></head>
Mystery's over everybody. The problem is that you should not pip install django-livereload-server. I don't know what it does behind the scenes but some of my html disappear based on some weird algorithm.
So, to uninstall django-livereload-server, remove 'livereload', from your INSTALLED_APPS, remove 'livereload.middleware.LiveReloadScript', from your MIDDLEWARE, hit Control-C to get out of that livereload terminal process, Control-C in the window running the runserver process to apply the changes (because livereload latches onto runserver like a leech, so you have to restart), and enjoy expected output. And pip uninstall django-livereload-server. If anybody has any suggestions for a livereload type of app that works (where the browser reloads the page when you type something new in your html/js/css), let me know. For now I guess it's back to the old manually typed Command-R.

Django render_to_response displaying raw text

I am new to Django and I'm trying to create a simple html skeleton to verify everything is working properly. Everything is working (server is running and it loads the file) yet when I put in HTML code it is displayed as raw text instead of rendering it correctly.
My views.py is as follows
def home(request):
return render_to_response('index.html')
My 'index.html' is as follows
<!DOCTYPE html >
<html>
  <head>
   <meta charset="UTF-8">
   <title> awesome </title>
  </head>
  <body>
  
  </body>
</html>
What should I do to have it render correctly? (Display only "awesome")
EDIT
As far as this problem goes, the error came in that I saved the raw code as html. When I chose this option, it added the code to make html render it look like a raw input.
Moral of the story: Make sure you do your edits in a text editor and change extension by hand
A few problems..
1: what's with the spaces inside your tags?
< title > is invalid. It needs to be <title>Foo</title> That's why you're seeing "html".
2: Even if the title tag was written correctly, a title tag does not render, so you will get a blank page. If you want to display "awesome" -- you need to write it inside the body tag.
<body>awesome</body>
1) Remove spaces in < title > tag
2) And add bellow code in your urls.py file no need to map with view you can render html page from url also
(r'^home/$', 'django.views.generic.simple.direct_to_template',
{'template': 'index.html'}),
The first thing you need to do is create a "base" template so the other templates can extend from. You will normally call it base.html but you can use the name you want. You also need to create blocks that extended templates can use:
base.html
<!DOCTYPE html >
<html>
<head>
<meta charset="UTF-8">
< title > awesome < /title >
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Then, you have to extend base.html from your index.html and use the content block we have created:
index.html
{% extends "base.html" %}
{% block content %}
{% endblock %}
At this point, index.html will be exactly as base.html because you are not showing anything inside the content block. Update your view with some data like this:
views.py
def home(request):
data = {'name': 'YourName', 'age': 25}
return render_to_response('index.html', data)
Now, again, update your index.html:
index.html
{% extends "base.html"%}
{% block content %}
<p>My name is {{ name }}</p>
<p>I'm {{ age }} years old</p>
{% endblock %}
Don't forget to read the fine tutorial.

UnicodeDecodeError in extended template

I have base.html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>{% block head.title %}{% endblock %}</title>
</head>
<body>
{% block body.content %}{% endblock %}
</body>
</html>
and 500.html file:
{% extends "base.html" %}
{% block head.title %}
500 ł
{% endblock %}
{% block body.content %}
500 -
{% endblock %}
When I generate some error I don`t see 500 ł but
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb3 in position 54: unexpected code byte
When I change ł to l everything is fine. I creates new html files with eclipse. What is wrong?
EDIT:
I cannot use any of polish diactric characters
It looks like your template file might not being saved in utf8 by Eclipse. According to this bug it chooses your OS's default encoding, which may not be utf8.
You can configure Eclipse like this:
Set the global text file encoding preference Workbench > Editors to "UTF-8".
If an encoding other than UTF-8 is required, set the encoding on the individual file rather than using the global preference setting. To do this use the File > Properties > Info menu selection to set the encoding on an individual file.
Or you can use the HTML entity which is Ł and then it doesn't matter what encoding the file is saved as.
ł is not a valid utf8 character, you will have to replace it with it's ascii character reference Ł
This website has a useful list of ascii codes for any special characters you want to include in your web pages.