Django render_to_response displaying raw text - django

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.

Related

flask include template with variable

Just curious why this is working, since haven't found such examples in flask and jinjia2 official docs. It seems include is just simply put the content to the place just as it is, right?
# app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
names = ['John', 'James', 'Jenny']
return render_template('index.html', names=names)
if __name__ == '__main__':
app.run(port=5200)
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
Welcome!
<!-- I know this is working as official docs -->
{% for name in names %}
<div class='card'>Welcome {{ name }}!</div>
{% endfor %}
<!-- but haven't found any examples like below, but it works -->
{% for name in names %}
{% include "card.html" %}
{% endfor %}
</body>
</html>
<!-- card.html -->
<div class='card'>Welcome {{ name }}!</div>
code example in vscode
From https://jinja.palletsprojects.com/en/3.0.x/templates/
Include
The include tag is useful to include a template and return the
rendered contents of that file into the current namespace:
{% include 'header.html' %}
Body {% include 'footer.html' %}
Included templates have access to the variables of the active context
by default.
This code will work because cards.html will be reloaded at each step of the "for" loop.
We can include a template in another template in the jinja structure. We don't have to use "for" when doing this.
The list elements to be navigated in the "for" loop are rendered from the flask view. In this way, we can use the rendered list and its elements as we want in the specified template while rendering.
{% for name in names %}
{% include "card.html" %}
{% endfor %}

django common templates for apps with variables

I want to make project-wide templates, but with app variables and app base subtemplates:
/home/project/
templates/document.html
app1/templates/app1/base.html
app2/templates/app2/base.html
And app1/views.py:
def page1(request):
document = get_document('title',app_email='test#example.com')
context = {
'document' : document,
'app_title_header' : document.header
}
return render(request,'document.html', context)
templates/document.html
{% extends app_name|add:'/base.html' %}
{% load static %}
{% block content %}
{% autoescape off %}
{{ document.body }}
{% endautoescape %}
{% endblock %}
(app_name is set by context_processors.py registered in settings.py)
def appname(request):
return {'app_name': request.host.name, 'app_base' : '{}/base.html'.format(request.host.name) }
app1/templates/app1/base.html (almost identical like app2)
{% load static app1 %} <--- difference with app2
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
{% block head %}
{% endblock %}
<title>{% app_title %} - {{ app_title_header }}</title>
{% include "app1/google.html" %}
</head>
app1/templates/app1/google.html
{% load app1 %}
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={% g_tag %}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{% g_tag %}');
</script>
and now:
render takes document.html from project/templates. First it extends app_name/base.html - so it is including google.html (Google Analytics ).
And it works. But now I want to move google.html and fb.html to project templates, but theres unique G_TAG, so it has to be a tag or sth for this. I can't just move it because of {% load app1 %} in google.html.
I think it is too complicated - and I think there's easy solution - but don't have idea which way to go.
The most important limitation - I don't want to use context_processors from apps. I use context_processor only for common things, because i use the same variables in app1 and app2 and context_processor overrides it.
(Note: you may be suffering from DRY fascination ~:))
You need to hardcode the value somewhere, whether it's property in a ViewMixin, retrieve it from a shared storage or a template file - thing is, you have come to the point where you the shared functionality is as insignificant as the variable that differentiates each call: you need to output the value of a variable with some surrounding elements. That variable needs to come from somewhere, so repetition of variable = value is going to happen in one form or another.
My 2 cents...If I didn't understand the question well enough, let me know.
So if this is in your template:
<script async src="https://www.googletagmanager.com/gtag/js?id={{ g_tag }}"></script>
And this is a view mixin:
from django.views import generic
from centralapp.models import ConfigModel
class GoogleTagMixin(generic.base.ContextMixin):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
app_config = ConfigModel.objects.get(host=self.request.get_host())
context['g_tag'] = app_config.google_tag
return context
Then you have one template and can just use the mixin in whatever view you need it to be.
If you don't want a mixin, you can do the same with Middleware and set the value on the request object.
I'm not sure what you're looking for that is "better".

Django - name 'title' is not defined

An hour ago I started to make a web application, with Django. I watched this video https://www.youtube.com/watch?v=qDwdMDQ8oX4
I'm following all his steps, but after changing some stuff, I've got an error which says
title is not defined in /about/.
Here's my code for the route /about/. The code is equal to my other home page, but this one doesn't work.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
{% if title %}
<title>Django BLog - {{ title }}</title>
{% else %}
<title>Django blog</title>
{% endif %}
</head>
<body>
</body>
</html>
As shown in the traceback, title is not defined in your view. This happens because title is not wrapped in quotes so it assumes it's a variable.
Add the quotation marks like so 'title' and you should be fine.
So, you should change line 29 in views.py to
return render(request, 'blog/about.html', {'title': 'About'})

Do I have t paste google analytics on evey page of my dgango app or just the base template?

Do I have to paste my ananlytics code into every page of my django app or can I just do it in one spot, the base, similar to disqus?
You can do it in the base page and that will be included in every actually generated page.
You can have, for example, a master_page.html in which you put the main wrapper HTML including your Google Analytics code. The main part of your master page would have:
<html>
<head>
<!-- Google Analytics code -->
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Then your content page will have something like:
{% extends "master_page.html" %}
{% block content %}
Your content for the page.
{% endblock %}

Django template extends tag added extra space on top

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>
....