Django template blocks not showing? - python

I'm having a problem with displaying the contents within the block tags of a child template. I have a base.html and a dash.html which extends the base. When I go to the dash.html page the base.html is extended but the contents set within the block tags of dash.html do not show up. So I get the same thing when I go base.html and dash.html.
Here is my code:
base.html
<!DOCTYPE HTML>
<!--[if lt IE 7 ]> <html class="no-js ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]> <html class="no-js ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]> <html class="no-js ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>SCV Discount</title>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<link rel="stylesheet" href="static/css/main.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.6/modernizr.min.js"></script>
</head>
<body>
<!-- Main Header -->
<div id="top">
<div id="header">
<div id="logo"></div>
{% block head %}{% endblock %}
</div>
</div>
<!-- Middle -->
<div id="mid">
{% block mid %}{% endblock %}
</div>
<!-- Content -->
<div id="analytics-content">
{% block main %}{% endblock %}
</div>
<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="static/js/libs/jquery-1.6.2.min.js">\x3C/script>')</script>
<script src="static/js/libs/select.js"></script>
<script src="static/js/main.js"></script>
</body>
</html>
dash.html
{% extends 'base.html' %}
{% block head %}
<p class="dashboard-title">Elephant Bar</p>
<p class="cp_badge round">Control Panel</p>
{% endblock %}
{% block mid %}
{% include 'modules/meters.html' %}
{% include 'modules/client_ctl.html' %}
{% endblock %}
{% block main %}
{% include 'modules/history.html' %}
{% endblock %}
view.py
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
import datetime
def index(request):
return render_to_response('base.html', RequestContext(request))
def dash(request):
return render_to_response('dash.html', RequestContext(request))
Hope that is enough information. Please let me know what other info I can provide. Thanks in advance. I appreciate it.

I just copied & pasted this code into a new project and it is working for me. What does your urls.py look like? Is it possible you are sending your dash url to the index view? Here is the quick urls.py that I wrote to get this up and running:
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
(r'^index/', views.index),
(r'^dash/', views.dash),
)
When you view dash.html in your browser (through whatever URL you want to be tied to the dash view), how do you know that it is extending base.html if you do not see any of code that is specific to dash.html?

Related

Html is not recognizing block, endblock arguments. Django query

*I am having trouble in my index.html file. {% extends 'base.html' %} works. But everything b/w
{% block content %}{% endblock content %} doesn't execute. Here are my files.
views.py:-*
from django.shortcuts import render
def index(request):
return render(request, 'main/index.html')
base.html:-
<!doctype html>
{%load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<title>To Do App</title>
</head>
<body>
<div>
<nav class=" navbar fixed-top navbar-dark bg-dark">
<a class="navbar-brand" href="/">To Do App</a>
</nav>
<div class="container">
{% block content %}
{% endblock content %}
</div>
</div>
</body>
</html>
index.html:-
{% extends 'base.html'%}
{% block content %}
<div class="row">
<div class="col">
<h2>Add Item</h2>
</div>
</div>
{% endblock content %}
All it shows is a navbar of dark color saying To Do App
I also tried adding advanced things like form but it didn't work so then i added this heading saying Add Item. And guess what it doesn't work
When I inspect elements in browser I can see your Heading "Add Item". The only problem was that the whole <div class="container">...</div> was hidden behind nav bar. And the reason was CSS.
Adding something like margin-top: 56px to .container may solve the problem.
Based on documentation you must use only 'endblock' tag when you are closing tag.So you must replace {% endblock content %} with {% endblock %}.

django cannot read css file in static folder

I am trying to make a base.html template and inserting a css file in the header. in the page it includes all the styling by it does not do any styling when the link the other page is pressed.
I have two files extending base.html one color_choose.html the other statistics.html which have the exact same lines for linking files. color_choose.html works and it is the first page that opens when navigated and the other is statistics.html
here is the base.html:
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>ColorStore</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
{% block styles %} {%endblock%}
</head>
<body>
<div id="ColorFavor">
<div style="float: right;">
<h2 id="title" class="page-name">Color Picker</h2>
</div>
</div>
{% block navigation %}
{% endblock %}
{% block display %}
{% endblock %}
{% block modal %}
{% endblock %}
{% block scripts %}
{% endblock %}
</body>
</html>
here is the urls.py in the app file:
from django.urls import path
from . import views
urlpatterns = [
path('', views.ColorPageView.as_view(), name='color'),
path('statistics/',views.StatsPageView.as_view(), name='statistics'),
this is the file css is applied and is also the same text in the other file:
{% extends 'base.html' %}
{% block styles %}
<link rel="stylesheet" href="static/styles/main.css" type="text/css">
{% endblock %}
And this is the part in the settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
If I am missing anything I will edit this post as soon as possible, just leave a comment for it.
You are missing a slash '/' before 'static/...'
<link rel="stylesheet" href="/static/styles/main.css" type="text/css">
Your template should have {% load static %} and you should refer to the stylesheet either as /static/styles/main.css or (preferably) you should use the macro "{% static styles/main.css %}"
See the django doc here.

Django base template (using bootstrap3) overwrites index.html completely

I've created a base.html file where I want my bootstrap3 navbar and footer to live. These will be used on every page of my site.
However, the base.html & corresponding css file that goes with it seems to overwrite all of the index.html file and specific css for that view.
I've read the django documentation and closely-related questions like this one on overriding the base template. Other website have tutorials but still aren't making sense. I believe I am misunderstanding something fundamental.
Here is the code:
base.html:
<!DOCTYPE html> {% load staticfiles %}
<html>
<head>
<link rel="stylesheet" href="/static/css/main.css" />
<!-- jquery -->
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- [/] jquery -->
</head>
<body>
{# Load the tag library #} {% load bootstrap3 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {# Navigation Menu #}
<header>
<nav class="navbar navbar-default">
----->Navbar code here<-----
</nav>
</header>
<footer>
<div class="container">
<p>Good stuff is here in the footer</p>
</div>
</footer>
</body>
</html>
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="description" content="Online community">
<meta name="author" content="My name">
<title>Planet</title>
<link href="/static/css/homepage.css" rel="stylesheet">
</head>
<body>
{% extends 'base.html' %}
{% block content %}
<p>WORDS WORDS WORDS WORDS</p>
<h1>HERE ARE SOME BIG WORDS ON THE MAIN PAGE</h1>
{% endblock content %}
</body>
</html>
I can include the css files for index.html & base.html if it helps but I believe the problem lies somewhere with my understanding of extending the base template and how to use {% block content %}. I can remove that block and it doesn't seem to matter either.
Thank you for any insights you can provide.
It looks like you're trying to use template extending
In simplicity, you should structure your files like so:
base.html
<head> </head>
<body>
{% block content %}
index.html will be loaded and everything within
the block named "content" will display here
{% endblock %}
</body>
<footer> </footer>
index.html
{% extends 'base.html' %}
{% block content %}
Everything within this block, named "content", will
be inserted into the "content" block of base.html
{% endblock %}
Your combined HTML would look like this once it passes through Django's templating system:
<head> </head>
<body>
Everything within this block, named "content", will
be inserted into the "content" block of base.html
</body>
<footer> </footer>
Your view will need to return the rendered index.html. This system is designed such that you can continue to use base.html with other templates to maintain a standard structure or page design, while modifying only the content on those pages with different versions of index.html.

Django 1.9. template inheritance. Block doesn't display

I have 2 html pages in my Django templates. I am trying to insert cats.html in index.html as a block, but nothing happens. No errors, no display. I already looked in django documentation and in the youtube. Just can't understand where is problem
index.html:
{% load static %}
<!DOCTYPE doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<link rel="stylesheet" type="text/css" href="{% static 'items/index-style.css' %}" />
<title>
my site
</title>
</head>
<body>
{% block cats %}
{% endblock cats %}
</body>
</html>
cats.html:
{% extends "index.html" %}
{% block cats %}
<div class="row column">
<p class="lead">
Категории товаров
</p>
</div>
<div class="row small-up-1 medium-up-2 large-up-3">
{% for category in categories %}
<div class="column">
<a href="/{{category.alias}}">
<div class="callout">
<p>
{{category.name}}
</p>
<p>
<img alt="image of a planet called Pegasi B" src="{{category.image}}"/>
</p>
<p class="lead">
<!-- Цена: {{tovar.price}} -->
</p>
<p class="subheader">
<!-- {{tovar.short_description}} -->
</p>
</div>
</a>
</div>
{% endfor %}
</div>
{% endblock cats %}
views.py:
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.template.loader import render_to_string
from items.models import *
# Create your views here.
def home(request):
try:
categories = Category.objects.all()
except:
raise Http404()
context = {
'categories':categories,
}
return render(request,"index.html",context)
You are confusing the block name with template name. You are not inserting cats.html into index.html as you expect, but you are extending index.html in your cats.html. You should use your child template (cats.html) in your view, ie change the last line to:
return render(request, 'cats.html', context)
actually the problem is you use index.html as a base template
and then inherit in your cats.html
so you have to render cat.html to get the desired result THIS IS HELPFUL FOR YOU
return render(request, 'cats.html', context)
thanks :)

Jinja2 is duplicating content when extends

I'm getting issues when index.html inherits from base.html Jinja2 is duplicating content.
I'm using the example code from http://jinja.pocoo.org/docs/dev/templates/#template-inheritance but the content in the browser is duplicated completely. I don't know if it's because of jinja environment setting mistake, extends tag or something like that.
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
{% block head %}
<link rel="stylesheet" href="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 2008 by you.
{% endblock %}
</div>
</body>
index.html
{% extends "base.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.
</p>
{% endblock %}
This is that I'm getting ( the same html code twice ):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" />
<title>Index - My Webpage</title>
<style type="text/css">
.important { color: #336699; }
</style>
</head>
<body>
<div id="content">
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
</div>
<div id="footer">
© Copyright 2008 by you.
</div>
</body>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" />
<title>Index - My Webpage</title>
<style type="text/css">
.important { color: #336699; }
</style>
</head>
<body>
<div id="content">
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
</div>
<div id="footer">
© Copyright 2008 by you.
</div>
</body>
Any idea? Thanks so much.
UPDATE!!
Here my handler. I'm using webapp2.
class LandingHandler(webapp2.RequestHandler):
def get(self):
template = settings.JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(dict()))
UPDATE 2!!
In my settings.py
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
It's something odd about Jinja (& Bootstrap). It takes into account html comments as well, before it gives out warnings. So if you have any comments on that file, probably a commented out {% block content %} ... {% endblock %} section, then remove it completely from there and it will work.

Categories