I know a similar question might have been asked here a couple of times before, but I am still not able to find a solution to my problem with the answers provided. So I have five templates. index.html(base template), allposts.html, trending.html and religion.html and political.html. All make up different sections of the homepage complete with there own classes in the database. How do I create a template that extends all these templates? I.e merges all their contents, including data into one. I have tried extending trending.html, using index.html as the base, and then extending allposts.html using trending.html as the base, but the problem is I lose all the data associated to the new base template. Is there an easy way to do this?
religion.html
{% extends 'index.html' %}
{% block religion %}
<section class="category-section">
<div class="container" data-aos="fade-up">
<div class="section-header d-flex justify-content-between align-items-center mb-5">
<h2>Religion</h2>
<div>See All Religion</div>
</div>
<div class="row">
{% for religion in religions %}
{% if forloop.counter < 11 %}
<div class="post-entry-1 col-2 mx-1">
<img src="{{religion.image.url}}" alt="" class="post_img">
<div class="post-meta">
<span class="date">{{religion.category}}</span>
<span class="mx-1">•</span>
<span>{{religion.created_at}}</span>
</div>
<h2 class="mb-2">{{religion.title}}</h2>
<span class="author mb-3 d-block">Ole Pundit</span>
<p class="mb-4 d-block">{{religion.body|truncatewords:20}}</p>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</section>
{% endblock %}
political.html
% extends 'index.html' %}
{% block content %}
<section class="category-section">
<div class="container" data-aos="fade-up">
<div class="section-header d-flex justify-content-between align-items-center mb-5">
<h2>Politics</h2>
<div>See All Politics</div>
</div>
<div class="row">
{% for politic in politics%}
{% if forloop.counter < 11 %}
<div class="post-entry-1 col-2 mx-1">
<img src="{{politic.image.url}}" alt="" class="post_img">
<div class="post-meta">
<span class="date">{{politic.category}}</span>
<span class="mx-1">•</span>
<span>{{politic.created_at}}</span>
</div>
<h2 class="mb-2">{{politic.title}}</h2>
<span class="author mb-3 d-block">Ole Pundit</span>
<p class="mb-4 d-block">{{politic.body| safe | truncatewords:20}}</p>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</section>
{% endblock %}
trending.html
{% extends 'index.html' %}
{% load static %}
{% block trending %}
<div class="col-lg-3 trendingslide">
<div class="trending">
<h3>Trending</h3>
<ul class="trending-post table">
{% for trendingpost in trendingposts %}
{% if forloop.counter < 6 %}
<li>
<a href="">
<span class="number count"></span>
<h3>{{trendingpost.title}}</h3>
<span class="author">OlePundit</span>
</a>
</li>
{% endif %}
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
allposts.html
{% extends 'index.html' %}
{% load static %}
{% block allposts %}
{% for post in posts reversed %}
{% if forloop.counter < 5 %}
<div class="post-entry-1 col-lg-2 box mx-1">
<img src="{{post.image.url}}" class="post_img">
<div>
<div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">•</span> <span>{{post.created_at}}</span></div>
<h2>{{post.title}}</h2>
</div>
<p class="mb-4 d-block">{{post.body|truncatewords:75}}</p>
<div class="d-flex align-items-center author">
<div class="photo"><img src="{% static 'assets/img/person-1.jpg' %}" alt="" class="img-fluid"></div>
<div class="name">
<h3 class="m-0 p-0">OlePundit</h3>
</div>
</div>
</div>
{% endif %}
{% endfor %}
{% endblock %}
index.html(base template)
<section id="posts" class="posts">
<div class="container" data-aos="fade-up">
<div class="row g-5">
{% block allposts %}
{% endblock %}
<!-- Trending Section -->
{% block trending %}
{% endblock %}
<!-- End Trending Section -->
</div>
<!-- End .row -->
</div>
</section> <!-- End Post Grid Section -->
<!-- ======= Politics Category Section ======= -->
{% block content %}
{% endblock %}
<!-- End Politics Category Section -->
<!-- ======= Religion Category Section ======= -->
{% block religion %}
{% endblock %}
<!-- End Religion Category Section -->
views.py
def allposts(request):
posts = Post.objects.all()
return render(request, 'allposts.html', {'posts':posts})
def trending(request):
trendingposts = Post.objects.all()
return render(request, 'trending.html',{'trendingposts':trendingposts})
def political(request):
politics = Politics.objects.all()
return render(request, 'Politics/political.html', {'politics':politics})
def religion(request):
religions = Religion.objects.all()
return render(request, 'Religion/religion.html', {'religions':religions})
```
I recently started learning Django and can't solve one problem. I created my validator for the form, but instead of showing an error window, it just resets the form.
Here is the code models.py:
from django.db import models
from django.urls import reverse_lazy
from django.core.exceptions import ValidationError
class News(models.Model):
title = models.CharField(max_length=150, verbose_name='Title')
content = models.TextField(blank=True, verbose_name='Content')
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Date of publication')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Update')
photo = models.ImageField(upload_to='photos/%Y%m/%d/', verbose_name='Photo', blank=True)
is_published = models.BooleanField(default=True, verbose_name='Is_published ')
category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, verbose_name='Category')
def get_absolute_url(self):
return reverse_lazy('read', kwargs={'news_id' : self.pk})
def __str__(self):
return self.title
class Meta:
verbose_name = 'new'
verbose_name_plural = 'news'
ordering = ['-created_at', 'title']
class Category(models.Model):
title = models.CharField(max_length=150, db_index=True, verbose_name='Title of category')
def get_absolute_url(self):
return reverse_lazy('category', kwargs={'pk' : self.pk})
def __str__(self):
return self.title
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
ordering = ['-title']
This is the code forms.py:
from django import forms
from .models import News, Category
from django.core.exceptions import ValidationError
import re
class NewsForm(forms.Form):
title = forms.CharField(max_length=150, min_length=1, label='Title', widget=forms.TextInput(attrs={'class' : 'form-control'}))
content = forms.CharField(label='Text', required=False, widget=forms.Textarea(attrs={'class' : 'form-control', 'rows' : 15}))
# photo = forms.ImageField(upload_to='photos/%Y%m/%d/')
is_published = forms.BooleanField(label="To publish", initial=True)
category = forms.ModelChoiceField(label='Category', queryset=Category.objects.all(), empty_label='Select a category', widget=forms.Select(attrs={'class' : 'form-control'}))
def clean_title(self):
raise ValidationError('Error!')
# class NewsForm(forms.ModelForm):
# class Meta:
# model = News
# fields = ['title', 'content', 'is_published', 'category']
# widgets = {
# 'title' : forms.TextInput(attrs={'class' : 'form-control'}),
# 'content' : forms.Textarea(attrs={'class' : 'form-control', 'rows' : 15}),
# 'category' : forms.Select(attrs={'class' : 'form-control'})
# }
And here is the code views.py:
from django.shortcuts import render, get_object_or_404, redirect
from .models import News, Category
from .forms import NewsForm
def news(request):
news = News.objects.all()
return render(request, 'news/news.html', {'news': news, 'title': 'List of news:'})
def get_category(request, pk):
news = News.objects.filter(category_id=pk)
return render(request, 'news/category.html',
{'news': news, 'title': f'List of news in the {str(Category.objects.get(pk=pk))} category :'})
def view_news(request, news_id):
back = request.GET.get('back')
new = get_object_or_404(News, pk=news_id)
return render(request, 'news/read_news.html', {'new' : new, 'back' : back})
def add_news(request):
if request.method == 'POST':
form = NewsForm(request.POST)
if form.is_valid():
new = News.objects.create(**form.cleaned_data)
# new = form.save()
return redirect(str(new.get_absolute_url())+'?back=False')
return render(request, 'news/add_news.html', {'form' : NewsForm() })
Here is the code urls.py:
from django.urls import path
from .views import *
urlpatterns = [
path('news/', news, name='news_all'),
path('news/category/<int:pk>/', get_category, name='category'),
path('news/read/<int:news_id>/', view_news, name='read'),
path('news/add-news/', add_news, name='add'),
]
Code news_tags.py:
from django import template
from ..models import Category
register = template.Library()
#register.simple_tag(name='g_cat')
def get_categories():
return Category.objects.all()
#register.inclusion_tag('news/tags/news_tag.html', name='news_tag')
def news_tag(news, link=False):
return {'news' : news, 'link' : link}
Code news_tag.html:
<div class="col-md-9">
{% for item in news %}
<div class="card mb-3">
<div class="card-header">
{% if link %}
Category: {{ item.category.title }}
{% else %}
Category: {{ item.category.title }}
{% endif %}
</div>
<div class="card-body">
<div>
{% if item.photo %}
<img src="{{ item.photo.url }}" alt="" class="news-media-photo">
{% endif %}
<div class="media-body">
<h5 class="card-title" style="color: {% cycle 'red' 'green' %}">{{ forloop.revcounter }}. {{ item.title }}</h5>
<p class="card-text">{{ item.content|linebreaks|truncatewords:50 }}</p>
Читать дальше...
</div>
</div>
</div>
<div class="card-footer text-muted">
{{ item.created_at|timesince }} назад...
</div>
</div>
{% empty %}
<h2>Ooops...</h2>
{% endfor %}
</div>
Here is the code 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="{% static 'bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<title>{% block title %}News:{% endblock %}</title>
</head>
<body>
{% block navbar %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item"><a class="nav-link" href="{% url 'news_all' %}">Главная</a></li>
<li class="nav-item"><a class="nav-link" href="{% url 'add' %}">Add new</a></li>
</ul>
</div>
</nav>
{% endblock %}
<div class="container mt-3">
<h2>{% block list_title %}News:{% endblock %}</h2>
<div class="row">
{% block sidebar %}
<div class="col-md-3">
{% load news_tags %}
<div class="list-group">
{% g_cat as g_cat %}
Все
{% for i in g_cat %}
<a href="{{ i.get_absolute_url }}" class="list-group-item list-group-item-action">
{{ i.title }}
</a>
{% endfor %}
</div>
</div>
{% endblock %}
{% block content %}
{% endblock %}
</div>
</div>
<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://cdn.jsdelivr.net/npm/popper.js#1.14.6/dist/umd/popper.min.js"
integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
crossorigin="anonymous"></script>
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
Here is the code add_news.html:
{% extends 'base.html' %}
{% block title %}Add new{% endblock %}
{% block list_title %}
<p align="center">{{ new.title }}</p>
{% endblock %}
{% block navbar %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item"><a class="nav-link" href="{% url 'news_all' %}">Home</a></li>
<li class="nav-item"><a class="nav-link" href="#" onclick="history.back();return false;">Cancel</a></li>
</ul>
</div>
</nav>
{% endblock %}
{% block sidebar %}{% endblock %}
{% block content %}
<div class="col-md-12">
<h1>Add new</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{% comment %}
{{ form.non_field.errors }}
{% for i in form %}
<div class="form-group">
{{ i.label_tag }}
{{ i }}
<div class="invalid-feedback">
{{ i.errors }}
</div>
</div>
{% endfor %}
{{ form.non_field.errors }}
<div class="form-group">
<label for="{{ form.title.id_for_label }}">Title</label>
{{ form.title }}
<div class="invalid-feedback">
{{ form.title.errors }}
</div>
</div>
<div class="form-group">
<label for="{{ form.content.id_for_label }}">Text</label>
{{ form.content }}
<div class="invalid-feedback">
{{ form.content.errors }}
</div>
</div>
<div class="form-group">
<label for="{{ form.is_published.id_for_label }}">To publish</label>
{{ form.is_published }}
<div class="invalid-feedback">
{{ form.is_published.errors }}
</div>
</div>
<div class="form-group">
<label for="{{ form.category.id_for_label }}">Category</label>
{{ form.category }}
<div class="invalid-feedback">
{{ form.category.errors }}
</div>
</div>
{% endcomment %}
<button type="submit" class="btn btn-primary btn-block">Add new</button>
</form>
</div>
{% endblock %}
Code read_news.html:
{% extends 'base.html' %}
{% block title %}Новость - {{ new.title }}{% endblock %}
{% block list_title %}
<p align="center">{{ new.title }}</p>
{% endblock %}
{% block navbar %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item"><a class="nav-link" href="{% url 'news_all' %}">Главная</a></li>
{%if back is None %}
<li class="nav-item"><a class="nav-link" href="#" onclick="history.back();return false;">Back</a></li>
{% elif back == False %}
<li class="nav-item"><a class="nav-link" href="/news/news/">Back</a></li>
{% endif %}
</ul>
</div>
</nav>
{% endblock %}
{% block sidebar %}{% endblock %}
{% block content %}
<div class="col-md-12">
<div class="card mb-3">
<div class="card-header">
Category: {{ new.category.title }}
</div>
<div class="card-body">
<div>
{% if new.photo %}
<img src="{{ new.photo.url }}" alt="" height="250" class="news-media-photo">
{% endif %}
<div class="media-body">
<p class="card-text">{{ new.content|linebreaks }}</p>
</div>
</div>
</div>
<div class="card-footer text-muted">
{{ new.created_at|timesince }} ago...
</div>
</div>
</div>
{% endblock %}
Here is the code news.html:
{% extends 'base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block list_title %}
{{ title }}
{% endblock %}
{% block content %}
{% load news_tags %}
{% news_tag news True %}
{% endblock %}
Here is the code category.html:
{% extends 'base.html' %}
{% block title %}
{{ title }}
{% endblock %}
{% block list_title %}
{{ title }}
{% endblock %}
{% block content %}
{% load news_tags %}
{% news_tag news %}
{% endblock %}
For displaying custom error messages, you have to disable the default behavior of html5 of required field, you can use novalidate in the form.
You can also show particular field error messages in loop.
Try this code:
add_news.html
<div class="col-md-12">
<h1>Add new</h1>
<form method="POST" novalidate>
{% csrf_token %}
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
{{error|striptags}}
{% endfor %}
{% endif %}
{% for field in form %}
<div class="form-group">
{{ field.label_tag }}
{{field}}
<div class="invalid-feedback">
{% for error in field.errors %}
{{error}}
{% endfor %}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary btn-block">Add new</button>
</form>
</div>
I am having some trouble getting a drilldown for mptt in my template.
I have the following model.
models.py
class Dimension_value(MPTTModel):
name = models.CharField(max_length = 200, null=True, blank = True, default = '')
parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children")
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
return self.name
views.py
def show_dimensions(request):
return render(request, "accounts/dimension_detail.html", {'dimensions': Dimension_value.objects.all()})
template.py
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{%block body%}
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h2>My dimensions</h2>
{% load mptt_tags %}
{% drilldown_tree_for_node dimensions as drilldown cumulative count accounts.Dimension_value.name in game_count %}
{% for node,structure in drilldown|tree_info %}
{% if structure.new_level %}<ul><li>{% else %}</li><li>{% endif %}
{% if node == dimension %}
<strong>{{ node.name }}</strong>
{% else %}
{{ node.name }}
{% if node.parent_id == dimension.pk %}({{ node.game_count }}){% endif %}
{% endif %}
{% for level in structure.closed_levels %}</li></ul>{% endfor %}
{% endfor %}
</div>
</div>
<br>
<br>
<a class="btn btn-primary" href="{% url 'add_plan' %}" role="button">Add a plan</a>
<button onclick="goBack()" class = "btn btn-secondary">Go Back</button><br><br><a class="btn btn-primary" href="{% url 'subscribeusertoplan' %}" role="button">Add a user to plan</a>
</div>
{%endblock%}
I have added the view according to the documentation found here: https://django-mptt.readthedocs.io/en/latest/templates.html?highlight=examples#examples
However I get the following error.
Exception Type: AttributeError
Exception Value:
'TreeQuerySet' object has no attribute '_tree_manager'
Hope someone can nudge me in the right direction. Thanks!
You can do this by using some css and jquery
{% block head %}
{% endblock %}
{%block body%}
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h2>My dimensions</h2>
{% load mptt_tags %}
{% recursetree dimensions %}
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{node.level}}" aria-expanded="false" aria-controls="collapsed">
{{ node.name }}</a>
{% if not node.is_leaf_node %}
<ul class="children">
<div id="collapse{{node.level}}" class="children panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
{{ children }} </div>
</div>
</ul>
{% endif %}
{% endrecursetree %}
</div>
</div>
<br>
<a class="btn btn-primary" href="{% url 'add_plan' %}" role="button">Add a plan</a>
<button onclick="goBack()" class = "btn btn-secondary">Go Back</button><br><br><a class="btn btn-primary" href="{% url 'subscribeusertoplan' %}" role="button">Add a user to plan</a>
</div>
{%endblock%}
I am working on library website in which I want to display data from database which is Book name and description. But I'm not able to do that. Here is my code
views.py
from django.shortcuts import render
from .models import *
def index(request):
book_list = Book.objects.all()
return render(request,template_name='index.html', context={'book_list':book_list})
index.html
{% extends "base_generic.html" %}
{% block new_books %}
{% for b in book_list %}
<div class="card">
<img class="card-img-top" src=".." alt="Image">
<div class="card-body">
<h5 class="card-title">{{ book_list }} </h5>
<p class="card-text">Hello this is card text</p>
<a class="btn btn-primary">View this book</a>
</div>
</div>
{% endfor %}
{% endblock %}
You should work with b variable instead of book_list inside of for loop.
If your Book model contains title field, your code might look like this:
{% extends "base_generic.html" %}
{% block new_books %}
{% for b in book_list %}
<div class="card">
<img class="card-img-top" src=".." alt="Image">
<div class="card-body">
<h5 class="card-title">{{ b.title }} </h5>
<p class="card-text">Hello this is card text</p>
<a class="btn btn-primary">View this book</a>
</div>
</div>
{% endfor %}
{% endblock %}
I have the following code in a template and am having difficulty showing when a user is logged in. I will be able to login, but when I revisit the page, it shows that I'm still not authenticated.
{% extends "base.html" %}
{% load catalog_tags %}
{% block site_wrapper %}
<div id = "main">
Skip to main content
<div id = "banner">
<div class="bannerIEPadder">
<div class="cart_box">
{% cart_box request %}
</div>
</div>
</div>
<div style="float:right;">[search box goes here]</div>
<div id="navigation">
<div class="navIEPadder">
<!--navigation tabs at the top of each page -->
{% comment %}{% include "tags/navigation.html" %} {% endcomment %}
{% category_list request.path %}
</div>
</div>
<div id="middle">
<div id="sidebar">
<!--<div class="sidebarIEPadder">[search box goes here]</br>
{% comment %}{% category_list request.path %}{% endcomment %}
</div>-->
</div>
<div id="content">
<!-- <a name = "content"></a>-->
<div class="contentIEPadder">
{% block content %}{% endblock %}
</div>
</div>
</div>
<div id="footer">
<div class="footerIEPadder">
{% footer_links %}
</div>
</div>
</div>
{% endblock %}
And here's the file it references. Since this will be an extension of all templates, is there something I need to consider?
###category_list.html
<!--<h3>Categories</h3>-->
<!--<ul id="categories">-->
<ul>
{% with active_categories as cats %}
{% for c in cats %}
<li>
{% comment %}
{% ifequal c.get_absolute_url request_path %}
{{c.name}}
{% else %}
{% endcomment %}
<div>{{c.name}}</div>
{% comment %}{% endifequal %}{% endcomment %}
</li>
{% endfor %}
<div class="fr">
<ul>
<li>
{% if user.is_authenticated %}
Logout
{% else %}
Login
{% endif %}
</li>
</div>
{% endwith %}
</ul>
<div class="cb"></div>
Am I missing something here?
You need to pass a RequestContext to the template. The easiest way to do this is to import django.shortcuts and use the render method in your view:
return render(request, "my_template.html")
Is django.contrib.auth.context_processors.auth in your TEMPLATE_CONTEXT_PROCESSORS setting.py?
Do you use requestContext rendering template?
Check that sessions are enabled: MIDDLEWARE_CLASSES should contains 'django.contrib.sessions.middleware.SessionMiddleware'