I can't expand the template base.html template header.html
Content base.html
<div id="main-container">
<!-- HEADER -->
{% block header %}{% endblock %}
<!-- END HEADER -->
</div>
Content header.html
{% extends "blog/base.html" %}
{% block header %}
<header id="header">
***
</header>
{% endblock %}
The output in the browser get the code:
<div id="main-container">
<!-- HEADER -->
<!-- END HEADER -->
Why not be able to extend the template?
Using {% include "blog/header.html"%} code inserted. using extends no.
Use Django 1.10.1
views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Post
from django.shortcuts import render, get_object_or_404
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/index.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404 (Post, pk=pk)
return render(request, 'blog/base.html', {'post': post})
def header(request):
return render(request, 'blog/header.html')
Through
{% include "blog/header.html" %} works. So the way spelled out correctly.
Thought the error here:
def header(request):
return(request, 'blog/header.html')
def header(request):
render(request, 'blog/header.html')
def header(request):
return render_to_response (request, 'blog/header.html')
Not working (((
If you want to extend some template, you should render template with {% extends ... %} tag (in your case header.html), if you want to include something to renedered template, you should use {% include ... %} tag. You can make new template for particular page and ovreload {% block head %}, for example:
base.html:
{% block header %}
{% include 'std_header.html' %}
{% endblock %}
{% block content %}
{% endblock %}
{% block footer%}
{% endblock %}
And particular page, for example landing page will overload default header:
landing.html:
{% extends 'base.html' %}
{% block header %}
{% include 'landing_header.html' %}
{% endblock %}
{% block content %}
<!-- landing page content -->
{% endblock %}
So for view called landing_page you have to render landing.html template.
I think you would have confused between the include and extend in django templates.
Based on your file names, I assume that header.html is the partial which is to be included in the base.html and you are rendering base.html .
Django templating engine does not work this way.
Use include {% include "path/to/header.html" %} in base.html and juse have the header html in header.html.
Related
I am learning django and I really can't solve this error, I tried modifying every file but I can't find where the issue is.
Error:
OperationalError at /topics/
no such table: pizzas_topic
I have to mention that this exercise is from Python Crash Course 2nd Edition
Thanks
Here is the code from my project:
base.html:
<p>
Pizzeria -
Pizzas
</p>
{% block content %}{% endblock content %}
index.html
{% extends "pizzas/base.html"%}
{% block content %}
<p>Pizzeria</p>
<p>Hi</p>
{% endblock content%}
topic.html
{% extends 'pizzas/base.html' %}
{% block content %}
<p>Topic: {{topic}}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{entry.date_added|date:'M d, Y H:i'}}</p>
<p>{{entry.text|linebreaks}}</p>
</li>
{% empty %}
<li>There are no entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}
topics.html
{% extends "pizzas/base.html" %}
{% block content %}
<p> Topics</p>
<ul>
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>No topics have been addet yet.</li>
{% endfor %}
</ul>
{% endblock content %}
urls.py
"""Defines URL patterns for pizzeria."""
from django.urls import path
from . import views
app_name = 'pizzas'
urlpatterns = [
# Home page
path('',views.index, name='index'),
# Page that shows all pizzas.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic.
path('topics/<int:topic_id>/', views.topic, name='topic'),
]
views.py
from django.shortcuts import render
from .models import Topic
def index(request):
"""The home page for Learning Log."""
return render(request, 'pizzas/index.html')
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request,'pizzas/topics.html',context)
def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'pizzas/topic.html', context)
Run:
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
I am learning django, I added a new app,
the link can be displayed in friendly_link.html,
the code is as follows:
admin.py
from django.contrib import admin
from .models import FriendlyLink
admin.site.register(FriendlyLink)
models.py
from django.db import models
class FriendlyLink(models.Model):
title = models.CharField(max_length=100, default='', verbose_name='title')
url = models.CharField(max_length=100, default='', verbose_name='url')
class Meta:
verbose_name_plural = 'links'
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from .models import FriendlyLink
def friendly_link(request):
friendly_link = FriendlyLink.objects.order_by('title')
context = {'friendly_link': friendly_link}
return render(request, 'friendly_link.html', context)
urls.py
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^links$', views.friendly_link, name='friendly_link'),
]
friendly_link.html
{% extends "base.html" %}
{% block title %}Links{% endblock %}
{% block content %}
<ul>
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
{% endblock %}
base.html
{% load i18n static %}<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
{% block content %}{% endblock %}
<footer>
<ul>
<!--This code doesn't work-->
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
</footer>
...
</body>
I want to put the link inside the <footer> element in base.html. How do I change the code? Thank you.
You should really read this documentation page:
https://django-adminlte2.readthedocs.io/en/latest/templates_and_blocks.html
Each block is clickable there and there's a detailed description on how to overwrite each one.
For your problem, you will probably nav_footer
{% block nav_footer %}
{{ block.super }}
...
{% endblock %}
{{ block.super }} is optional and will append your content to the block instead of overwriting it.
I'm trying to figure out a way to build a list of URLs for my content in my django app. I have the Models and Views setup properly, and I already figured out how to access this data in the Templates, but I'm not quite sure how I can start making URLs for them.
The data I have is continents and the countries of these continents. The template should render a list of the continents, but as links.
Here's an example with one continent:
<ul id="continentMenu">
<li>Scandinavia</li>
</ul>
My urls.py looks like
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('countrydata.urls')),
url(r'^', include('selectui.urls')),
]
and my index.html looks like
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
{% if user.is_authenticated %}
Hi {{ user.username }}!
<p>logout</p>
{% else %}
<p>You are not logged in</p>
login
{% endif %}
{% endblock %}
My continentmenu.html, which I'm trying to have the links for the continents in, looks like
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div class="container-fluid">
<div class="l">
{% for continent in all_continents %}
<h1> {{ continent.name }}</h1>
<p> {{ continent.code }}</p>
{% for country in continent.countries.all %}
<p> {{country.name}}</p>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock %}
At the moment, but I only made it print all the continents and countries as plain text to make sure that I was successfully parsing through the objects (which I was). I'm having trouble at figuring out what kind of instructions I need to put into {% url %}, as my first attempts lead to nothing but errors.
The ajax.js I've been given to work with looks like
/* Run once document ready. */
$(function() {
"use strict";
#continentMenu.
$("#continentMenu a").on("click", function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("#continentName").text($(this).text());
$("#tableContainer").load(url);
});
});
and the views.py looks like
from django.shortcuts import render, get_object_or_404
from countrydata.models import Continent
def show_continent(request, continent_code=None):
context = {
"all_continents": Continent.objects.all()
}
if continent_code:
continent = get_object_or_404(Continent, code=continent_code)
context["continent"] = continent
return render(request, "selectui/index.html", context)
I have a site with some ajax pages. If user types in a browser /login/, he should get a full rendered template, extended from a base template. But if user clicks a login button, $('#content').ajax('/login/'); called, so i don't need to render a full template.
I.e. i have this (login_ajax.html):
{% load i18n %}
{% block title %}
{% trans "Login" %}
{% endblock %}
{% block content %}
{% include "social.html" %}
{% endblock %}
In login.html:
{% extends "base.html" %}
{% block ajax_content %}
{% include "login_ajax.html" %}
{% endblock %}
Simple login view:
def login(request):
c = Context({'user': request.user})
if request.is_ajax():
return render_to_response('login_ajax.html', c, context_instance=RequestContext(request))
return render_to_response('login.html', c, context_instance=RequestContext(request))
This problem refers to documentation of include tag:
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.
But i don't want to place title name in a view, or place it twice in login.html and login_ajax.html also.
I think you need to move {% block title %} back out into login.html then make two ajax calls. One to override {% block ajax_content %} and one to override {% block title %}. You could use the same pattern for overriding {% block title %} as you've used for overriding {% block ajax_content %}, but you'd probably manage without actually creating a new title.html template.
I can't see any other way round your problem.
Ok, i've found a simple solution. In fact, the problem is in question: "to extend from base, or not to extend".
In fact, i don't care a template from what login.html should be extended. So, for ajax request, the parent template will be empty.html, and for default request, it will be base.html. So, i'll point a parent template in the view:
def login(request):
c = Context({'user': request.user, 'extends': 'empty.html'})
if request.is_ajax():
return render_to_response('login.html', c, context_instance=RequestContext(request))
c['extends'] = 'base.html'
return render_to_response('login.html', c, context_instance=RequestContext(request))
The empty.html just contain a placeholder for a block:
{% block content %}{% endblock %}
And here is login.html:
{% extends extends %}
{% load i18n %}
{% if extends != 'empty.html' %}
{% block title %}{% trans "Login" %}{% endblock %}
{% else %}
<div style="display: none;" class="ajax-title">{% trans "Login" %}</div>
{% endif %}
{% block content %}
{% include "social.html" %}
{% endblock %}
Also, i suppose, there is a way to turn login.html into a snippet, that could be included using with. i.e. {% include 'snippet.html' with extends='base.html' %}
I am attempting to use markdown to avoid having to type HTML within my wiki form, but for some reason the form is displaying HTML code instead of the intended formatting.
My view function is as follows:
from django.shortcuts import render_to_response
from mywiki.wiki.models import Page
from django.http import HttpResponseRedirect
import markdown
def view_page(request, page_name):
try:
page = Page.objects.get(pk=page_name)
except Page.DoesNotExist:
return render_to_response('create.html', {'page_name':page_name})
content = page.content
return render_to_response('view.html', {'page_name':page_name, 'content':markdown.markdown(content)})
This is my view.html template:
{% extends 'base.html' %}
{% load wikilink %}
{% block title %}{{page_name}}{% endblock %}
{% block content %}
<h1>{{page_name}}</h1>
{{content|wikify}}
<hr/>
<a href='/mywiki/{{page_name}}/edit/'>Edit this page?</a>
{% endblock %}
And this is my base.html:
<html>
<head>
<title>{{% block title %}{% endblock %}</title>
</head>
<body>
<div>
Menu: <a href='/mywiki/Start/'>Start Page</a>
</div>
{% block content %}
{% endblock %}
</body>
</html>
I do have markdown installed, and my Django version is 1.4.1 (Mac).
Thanks.
Use Django's safe filter so as for your Html not to be escaped.
{{ content|safe }}
{% autoescape off %}
{{content|wikify}}
{% endautoescape %}
maybe ...