Child template isn't rendering - python

I have a layout template and a child template. However, none of the extra information from the child template is showing up. Why isn't the information in the child template being used?
FlaskTest.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template('layout.html')
if __name__ == '__main__':
app.run()
layout.html
<!doctype html>
<html>
<head>
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2010 by you.
{% endblock %}
</div>
</body>
</html>
child.html
{% extends 'layout.html' %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important {
color: #336699;
}
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
{% endblock %}
On http://localhost:5000/ I get:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/static/style.css">
<title> - My Webpage</title>
</head>
<body>
<div id="content"></div>
<div id="footer">
© Copyright 2010 by you.
</div>
</body>
</html>

You need to render child.html, not layout.html. Child will extend layout, but the way you've written it, only layout will be rendered.
return render_template('child.html')

Related

Django template blocks not appearing in correct place in rendered template - resulting in jQuery "$ is not defined" error

I am using Django 3.2
This is my base template (snippet):
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content={% block page_description %}""{% endblock page_description %}>
<meta name="keywords" content={% block page_keywords %}""{% endblock page_keywords %}>
<link rel='icon' href='{% static "img/favicon.ico" %}' type='image/x-icon'/ >
<title>{% block page_title %}Demo{% endblock page_title %}</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans%3A400%2C300%2C500%2C600%2C700%7CPlayfair+Display%7CRoboto%7CRaleway%7CSpectral%7CRubik">
<link rel="stylesheet" href="{% static 'css/footer.css' %}">
<link rel="stylesheet" href="{% static 'css/header.css' %}">
{% block head_styles %}
{% endblock head_styles %}
{% block head_js %}
{% endblock head_js %}
</head>
<body>
{% block header %}
{% include "partials/header.html" %}
{% endblock header %}
{% block messages %}
{% include 'partials/messages.html' %}
{% endblock messages %}
<!-- Page Content -->
<div class="d-flex flex-column sticky-footer-wrapper">
{% block content %}
{% endblock content %}
</div>
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
<!-- Bootstrap core JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
<!-- Site footer -->
{% block footer %}
{% include 'partials/footer.html' %}
{% endblock footer %}
{% block body_js %}
{% endblock body_js %}
<script>
$().ready(function() {
});
</script>
</body>
</html>
/path/to/header.html
{% load static %}
<!-- Header -->
<header id="js-header" class="u-header u-header--static">
<!-- ... # snipped -->
<form action="/action_page.php" method="GET">
<button id="btn-submit-item" type="submit" class="btn" style="margin-right: 10px;border: 1px solid #CACACA;">Submit</button>
</form>
{% if not user.is_authenticated %}
<a class="btn btn-success btn" href="#" role="button">Sign In</a>
{% else %}
<a class="nav-link text-dark" href="#">{{ user.username }}</a>
{% endif %}
</ul>
</div>
<!-- End Navigation -->
</div>
</nav>
</div>
</header>
<!-- End Header -->
{% block body_js %}
<script>
$().ready(function(){
$( "#btn-submit-item" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
{% endblock body_js %}
In rendered page HTML, I get something like this:
# ...
<!-- End Header -->
<script>
$().ready(function(){
$( "#btn-submit-photo" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
# ...
</div>
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
<!-- Bootstrap core JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
<!-- Site footer -->
The placement is in the wrong place - so the JQuery operator $ is attempting to be used - BEFORE the JQuery library is loaded - hence the error.
My question is - why is Django rendering the block in the wrong place - and how do I fix this error?
You're rendering header.html in {% block header %} which is added before the jquery script. Therefore, $ is undefined.
Solution 1:
Move the jquery include to the <head></head> of your html, like you did with the bootstrap.min.css file.
Solution 2:
If you want to have your jquery loaded just before the body closing tag (</body>), you should move your inline jquery to a .js file and include that after including jQuery. For example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js"
integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g=="
crossorigin="anonymous"></script>
<script src="your_script.js"></script>
</body>
Read more about django and static files here: https://docs.djangoproject.com/en/3.2/howto/static-files/

Make success messages disappear after few second :(

it is my layout.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<title>Mikayıl`ın Bloğu</title>
</head>
<body>
{% include "includes/navbar.html" %}
<div style = "margin-top : 100px; margin-bottom:100px;" class = "container">
{% include "includes/messages.html" %}
{% block body %}
{% endblock body %}
</div>
<script src="{% static 'js/jquery-3.2.1.min.js'%} "></script>
<script src="{% static 'js/bootstrap.min.js'%} "></script>
<script>
$(document).ready(function() {
// messages timeout for 10 sec
setTimeout(function() {
$('.message').fadeOut('slow');
}, 10000); // <-- time in milliseconds, 1000 = 1 sec
// delete message
$('.del-msg').live('click',function(){
$('.del-msg').parent().attr('style', 'display:none;');
})
});
</script>
</body>
</html>
and it is my message.html this file is intor the folder in templates/includes but i added this into layout.html to
{% if messages %}
{% for message in messages %}
{% if message.tags == "info" %}
<div class="alert alert-danger">{{ message }}</div>
{% else %}
<div class="alert alert-{{ message.tags }}">{{ message }}</div>
{% endif %}
{% endfor %}
{% endif %}
i looked stackoverflow there was topic same as me i tried but i couldnt reach my goal
but i cant make succes message which one disappear after 5 second who can help me :)
Class names are different in your js and html parts, just change .message to .alert to work.

Django : Register or load { % block content % } tag in HTML

I am trying to extend my templates .
base_layout.html:
{% load static from staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Articles</title>
<link rel = "stylesheet" href = "{% static 'styles.css' %}">
</head>
<body>
<div class="wrapper">
{% block content %}
{% endblock %}
</div>
</body>
</html>
article_list.html:
{% extends 'base_layout.html' %}
{% block content %}
<h1>Article List</h1>
<div class = "articles">
{% for article in articles %}
<div class = "article">
<h2>{{ article.title}}</h2>
<p>{{ article.body }}</p>
<p>{{ article.date }}</p>
</div>
{% endfor %}
</div>
{% endblock %}
When i run this i am getting the error like this:
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 11: 'blockcontent'. Did you forget to register or load this tag?
What mistake am i doing?

Why is extending a template in Flask breaking the rest of the code?

I'm learning Flask and this is the file structure of my first project:
This is my app.py:
from flask import Flask, request, render_template
from data import Articles
app = Flask(__name__)
Articles = Articles()
#app.route('/')
def index():
return render_template('home.html')
#app.route('/about')
def about():
return render_template('about.html')
#app.route('/contact')
def contact():
return render_template('contact.html')
#app.route('/articles')
def articles():
return render_template('articles.html', articles = Articles)
#app.route('/article/<string:id>/')
def article(id):
return render_template('article.html', id=id)
if __name__ == '__main__':
app.run(debug=True)
This is my layout.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
{% block head %}
<meta charset="utf-8">
<title>Learning Flask - App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
{% endblock head %}
</head>
<body>
{% include 'components/_navbar.html' %}
<div class='container'>
{% block content %}
{% endblock %}
</div>
</body>
</html>
This is my home.html which is the only page working properly:
{% extends 'layout.html' %}
{% block content %}
<div class="jumbotron">
<div class="container">
<h1 class="display-3">Hello, world!</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
{% endblock %}
This is my contact.html which doesn't show anything after the navigation bar, same problem with rest of the templates:
{% extends 'layout.html' %}
{% block content %}
<h1>WHY THE HELL DOESNT THIS SHOW UP!!</h1>
{% endblock %}
Well, changing the navbar HTML fixed the problem. Don't know what exactly caused the issue but it was probably a matter of conflicting CSS.

What should I write for my detail view to inhert DB fields for my Django template?

I am new in Python. I have a problem with fetching DB fields to my Django template. File detail.html successfully extends my master.html, but it doesn't get anything I wrote under {% block h1 %} {% endblock %}
What should I write under views.py to make it work?
detail.html
{% extends "master2.html" %}
{% block h1 %}
<div class="box first">
<div class="row">
<div class="container">
{% for question in latest_question_list %}
<div class="col-xs-12 col-sm-4 col-md-3">
<div class="center">
<h4>{{ question.naslov }} </h4>
<p>{{ question.opis }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
{% block title %} Detail {% endblock %}
views.py
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.all()
context = {'latest_question_list': latest_question_list}
return render(request, 'papers/index.html', context)
def detail(request, slug):
question = Question.objects.get(slug=slug)
return render(request, 'papers/detail.html', {'question': question})
index.html
{% extends "master.html" %}
{% block h1 %}
<div class="box first">
<div class="row">
<div class="container">
{% for question in latest_question_list %}
<div class="col-xs-12 col-sm-4 col-md-3">
<div class="center">
<h4>{{ question.naslov }} </h4>
<p>{{ question.opis }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
{% block title %} Index {% endblock %}
master2.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="/static/font.min.css" rel="stylesheet">
<link href="/static/bootstrap.min.css" rel="stylesheet">
<link href="/static/font-awesome.min.css "rel="stylesheet">
<link href="/static/main.css" rel="stylesheet">
</head>
<body data-spy="scroll" data-target="#navbar" data-offset="0">
{% include "header.html" %}
{% include "carausel.html" %}
{% block h1 %}{% endblock %}
{% include "footer.html" %}
{% include "nav.html" %}
<script src="/static/jquery.js"></script>
<script src="/static/bootstrap.min.js"></script>
<script src="/static/jquery.isotope.min.js"></script>
<script src="/static/jquery.prettyPhoto.js"></script>
<script src="/static/main.js"></script>
</body>
</html>
master.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="/static/font.min.css" rel="stylesheet">
<link href="/static/bootstrap.min.css" rel="stylesheet">
<link href="/static/font-awesome.min.css "rel="stylesheet">
<link href="/static/main.css" rel="stylesheet">
</head>
<body data-spy="scroll" data-target="#navbar" data-offset="0">
{% include "header.html" %}
{% include "carausel.html" %}
{% block h1 %}{% endblock %}
{% include "footer.html" %}
<script src="/static/jquery.js"></script>
<script src="/static/bootstrap.min.js"></script>
<script src="/static/jquery.isotope.min.js"></script>
<script src="/static/jquery.prettyPhoto.js"></script>
<script src="/static/main.js"></script>
</body>
</html>
You loop over latest_question_list, but pass {'question': question} in the context
{% extends "master.html" %}
of index.html to be changed to
{% extends "master2.html" %}

Categories

Resources