Django extended template not displaying content - django

There have been a few other threads about this topic, but specifically one with an answer of a urls.py issue didn't resolve mine...
I'm attempting to extend a base template. I have two files, base.html and index.html. Base has basic navigational elements, CSS, etc., and index.html extends base. I'm pointing to index.html in my view, but all I can see is code from base.html -- the index.html code is not displaying. Any help is appreciated. Also, there are no errors reported anywhere for any of this code.
views.py:
class DashboardView(TemplateView):
context_object_name = 'home_list'
template_name = 'index.html'
queryset = Media.objects.all()
def get_context_data(self, **kwargs):
context = super(DashboardView, self).get_context_data(**kwargs)
context['jobs'] = Job.objects.all()
return context
Relevant portions of urls.py:
url(r'^admin/', include(admin.site.urls)),
url(r'^apiroot/', router.get_api_root_view()),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', dashboard_views.DashboardView.as_view(), name="home_list"),
base.html in the templates dir: (Note that the "Test." part of this does show up on the screen, but that is the last element on the page when loaded.)
{# load the tag library #}
{% load bootstrap3 %}
{% load staticfiles %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{{STATIC_URL}}bootstrap3/css/bootstrap.min.css" rel="stylesheet">
{# load CSS and Javascript #}
{% bootstrap_css %}
{% bootstrap_javascript %}
{# Display django.contrib.messages as bootstrap alerts #}
{% bootstrap_messages %}
<div class = "container">
Backup Administraton (test)
</div>
<!------Navbar ---------->
<header class = "navbar navbar-inverse navbar-fixed-top" role = "banner">
<div class = "container">
<div class ="navbar-header">
<button type = "button" class= "navbar-toggle" data-toggle = "collapse" data-target = "#dropdown">
<span class = "sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
Backup Administration
</div><!-- End Navbar Header-->
<div class = "collapse navbar-collapse" id = "dropdown">
<ul class = "nav navbar-nav navbar-right" role = "navigation">
<li>Home</li>
<li>Reports</li>
<li>Snapshots</li>
<li>Restores</li>
</ul>
</div><!-- End Nav Contents -->
</div><!-- End Container -->
</header>
Test.
Contents of index.html:
{% extends "base.html" %}
<BR><BR><BR><BR>
Testing contents of index.html
{% block content %}
<BR><BR><BR><BR><BR>
This is index.html<BR>
{% endblock %}
The index.html contents (ie the "Testing contents") never displays on the screen. FWIW, the BR's were to make sure the text didn't display behind the black nav bar.
Thanks for your time.

You need to add a content block to your base.html, for example:
...
<div class = "container">
Backup Administraton (test)
</div>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!------Navbar ---------->
...

Related

Django Breadcrumb error: Reverse for 'projectnotes_list' with no arguments not found

I am trying to use django-views-breadcrumbs to add breadcrumbs to a site. I can get it to work with some views but I am getting an error with a particular listview. When I attempt to visit this listview page I see the error.
The error appears to be related to a need for the correct context. So far I have not been able to figure this out.
The error:
NoReverseMatch at /projects/project/1/notes/
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Request Method: GET
Request URL: http://co1.localhost:8000/projects/project/1/notes/
Django Version: 3.1.14
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Exception Location: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages/django/urls/resolvers.py, line 689, in _reverse_with_prefix
Python Executable: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/bin/python
Python Version: 3.9.6
Python Path:
['/Users/user/Desktop/otools',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages']
Server time: Sun, 20 Feb 2022 15:52:17 +0000
The list view:
class ProjectNotesList(ListBreadcrumbMixin,ListView):
model = ProjectNotes
template_name = 'company_accounts/project_notes.html'
comments = ProjectNotes.comments
def related_project(self, **kwargs):
project = get_object_or_404(Project, id=self.kwargs.get('pk'))
notes = ProjectNotes.objects.all
return notes
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk'))
return context
commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments'))
The urls.py
from django.urls import path, include
from .views import CompanyProjects, CompanyProjectsDetailView, TodoCreateView, ProjectNotesList, ProjectNotesCreateView, ProjectCreateView, ProjectNotesDetailView, CompanyCompletedProjects, CompanyPausedProjects, TodosList, ProjectTodosDetailView, ProjectDocumentsList, ProjectDocumentsCreateView, ProjectDocumentsDetailView
from . import views
app_name = 'company_project'
urlpatterns = [
path('', CompanyProjects.as_view(), name='project_list'),
path('completed_projects', CompanyCompletedProjects.as_view(), name='completed_projects'),
path('paused_projects', CompanyPausedProjects.as_view(), name='paused_projects'),
path('add_project/', ProjectCreateView.as_view(), name='add_project'),
path('project/<int:pk>/', CompanyProjectsDetailView.as_view(), name='project_detail'),
path('project/<int:pk>/todos/', TodosList.as_view(), name='project_todos'),
path('project/<int:project_pk>/todo/<int:pk>/', ProjectTodosDetailView.as_view(), name='project_todo_detail'),
path('project/<int:pk>/add_todo/', TodoCreateView.as_view(), name='add_todo'),
path('project/<int:pk>/add_project_note/', ProjectNotesCreateView.as_view(), name='add_project_note'),
path('project/<int:pk>/notes/', ProjectNotesList.as_view(), name='projectnotes_list'),
#path('note/<int:pk>/add_project_note_comment/', ProjectNotesCommentCreateView.as_view(),
# name='add_project_note_comment'),
path('project/<int:project_pk>/note/<int:pk>/', ProjectNotesDetailView.as_view(), name='project_note_detail'),
path('project/<int:pk>/documents/', ProjectDocumentsList.as_view(), name='project_documents'),
path('project/<int:pk>/add_project_document/', ProjectDocumentsCreateView.as_view(), name='add_project_document'),
path('project/<int:project_pk>/document/<int:pk>/', ProjectDocumentsDetailView.as_view(), name='project_document_detail'),
]
The base and page templates:
base
<!DOCTYPE html>
{% load static %}
{% load view_breadcrumbs %}
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Site{% endblock title %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link type="text/x-scss" href="{% static 'bootstrap/scss/bootstrap.scss' %}" rel="stylesheet" media="screen">
<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>
<link rel="shortcut icon" type="image/png" href="{% static 'core_images/OH_favicon.png' %}"/>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-VJRXH7YFXZ"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-VJRXH7YFXZ');
</script>
</head>
<body>
<wrapper class="d-flex flex-column">
{% include 'nav.html' %}
<main class="flex-fill">
<div class="row">
<div class="col-12">
<br />
{% block breadcrumbs %}
{% render_breadcrumbs 'view_breadcrumbs/bootstrap4.html' %}
{% endblock breadcrumbs %}
{% block messages %}{% endblock messages %}
</div>
</div>
{% block content %}
<h1>Hello</h1>
{% endblock content %}
</main>
{% include 'footer.html' %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
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.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</wrapper>
</body>
</html>
page
<!-- templates/company_accounts/project_notes.html -->
{% extends 'base.html' %}
{% block content %}
<div class="section-container container">
<div class="general-section-header">
<div class="header-add-new">
<a class="btn btn-success" href="{% url 'company_project:add_project_note' project.pk %}" role="button">Add Note</a>
</div>
<h1>Notes for {{ project }}</h1>
</div>
{% if project.notes.all %}
{% for note in project.notes.all %}
<div class ="projectnotes-entry">
<div class="col-sm-8">
<div class="row-sm-6">
<div class="card mb-2">
<div class="card-body">
<div class="card-title">{{ note.title }}</div>
<div class="card-text">{{ note.body | safe | truncatewords:"20"|linebreaks }}
<div>{{ note.comments.all.count }} comments</div>
read more</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<p>No notes have been have been added yet.</p>
{% endif %}
</div>
{% endblock content %}
There is a demo included with the breadcrumb app the provides some insight. However I have not been able to figure out how to add necessaryt context using code from the demo.
The demo code:
class TestListsView(ListBreadcrumbMixin, ListView):
model = TestModel
template_name = "demo/test-list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
view_paths = []
for instance in self.object_list:
view_paths.append(
(
instance.name,
detail_instance_view_url(instance),
),
)
context["view_paths"] = view_paths
return context

Display multiple views in single page

I have a Django Webapp which has a few forms for adding data to the database.
Once this data has been added, I want to present this on a dashboard. So I have views that were written that add the logic for the data to be presented, but as far as i can work out you only map 1 view to a template otherwise the data won't be displayed on the template.
I think there is a way to pass the data as a context, but I can't get my head around how to write this for my view.
A really simple view i have to display events
def all_events(request):
event_list = Event.objects.all()
return render(request, 'pages/event_list.html',{'event_list': event_list})
I'm passing this to event_list which works fine. But if I % include % on the dashboard I get the HTML but not the data, which I now understand is right.
But being an absolute bigger with Django, I could really do with an example of the above which I can then apply to all my other views.
Thanks
HTML Template
{% extends 'partials/base.html' %}
{% load static %}
{% block head_title%}
<title> Dashboard </title>
{% endblock %}
{% block extra_css %}
<link rel="stylesheet" type="text/css" href="{% static 'libs/toastr/build/toastr.min.css' %}">
<!-- plugin css -->
<link href="{% static 'libs/admin-resources/jquery.vectormap/jquery-jvectormap-1.2.2.css' %}" rel="stylesheet" type="text/css" />
{% endblock %}
{% block content %}
<div class="main-content">
<div class="page-content">
<div class="container-fluid">
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
<h1 class="display-4 mb-0">Dashboard</h1>
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item active">Dashboard</li>
</ol>
</div>
</div>
</div>
</div>
</div>
{% include 'pages/event_list.html' %}
</div>
{% endblock %}
{% block extra_js %}
<script src="{% static 'libs/#ckeditor/ckeditor5-build-classic/build/ckeditor.js' %}"></script>
<!-- init js -->
<script src="{% static 'js/pages/form-editor.init.js' %}"></script>
<!-- pristine js -->
<script src="{% static 'libs/pristinejs/dist/pristine.min.js' %}"></script>
{% endblock %}
I'm not sure if I understand your problem correctly, but just including the pages.html file will not pass the correct context data to the dashboard if it is not in the view connected to the dashboard endpoint. Django directs an endpoint to a view, the view grabs the context data from the models or creates it, and returns a template with the data.
Your url pattern for the dashboard could look something like this
urlpatterns = [
path('dashboard/', dashboard_view, name="dashboard"),
]
and your view could then look like this
def dashboard_view(request):
event_list = Event.objects.all()
return render(request, 'path/to/dashboard.html',{'event_list': event_list})
Assuming the event_list.html file uses a context data variable correctly like the example shown below, it will be displayed on the dashboard as well.
{{ for event in event_list }}
{{ event.attribute }}
{{ endfor }}
What you're passing to the render() function is just a dictionary of context data for the templates to use, so as long as the correct data is in that dictionary and the correct variable names from the dictionary are used in the template being rendered, or any templates included within it, it should be displayed.
Hope this helps answer your question!

why my search bar is not working in Django?

created a simple search in the Django blog but it's not working. why search bar is not working in a blog web app ? its nothing to search in the search bar when searching something in the search box.
- urls.py
urlpatterns = [
path('', views.home, name='home'),
path('about', views.about, name='about'),
path('contact', views.contact, name='contact'),
path('search', views.search, name='search'),
]
- views.py
def search(request):
query = request.GET['query']
allPosts = Post.objects.filter(title__icontains=query)
params = {'allPosts': allPosts}
return render(request,'home/search.html', params)
- search.html
{% extends 'base.html' %}
{% block title %} Search Results {% endblock title %}
{% block blogactive %}active{% endblock blogactive %}
{% block body %}
<div class="container my-3">
<h2>Search Results</h2>
{% for post in allposts %}
<div class="row no-gutters border rounded overflow-hidden flex-md-row my-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">Article by {{post.author}}</strong>
<h3 class="mb-0">{{post.title}}</h3>
<div class="mb-1 text-muted">{{post.datetime}}</div>
<p class="card-text mb-auto">{{post.content | truncatechars:500}}</p>
<div class='my-2'>
Continue reading
</div>
<div class="col-auto d-none d-lg-block">
</div>
</div>
</div>
{% endfor %}
{% endblock body %}
There is a typo in your code. In template you are using allposts(all lower case) where you are passing allPosts from context, ie: params = {'allPosts': allPosts}. So you need to change either one of them, like change in context:
params = {'allposts': allPosts}
And one improvement suggestion, replace href="/blog/{{post.slug}}" in the template with href="{% url 'url_name' %}". More information can be found in url tag documentation.

Model in header doesn't appear in views that use the header

Model defined in the header of my pages appears on page load and refresh on the main page, but when I navigate to another view the model doesn't appear there. The rest of the header is there, just the dynamic data that isn't.
Where am I going wrong? New to both Python and Django, so if anyone can help, please don't be afraid to patronize and Eli5 :)
Model defined in models.py:
from django.db import models
from django.utils import timezone
# Create your models here.
class Propaganda(models.Model):
slogan = models.CharField(max_length=140, blank=True, null=True)
def __str__(self):
return self.slogan
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Christopher's weblog</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Blog site.">
<!-- Let's get the static files where we use them, but this could be before the html tag -->
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- <link rel="stylesheet" href="{% static 'blog/css/cupar.css' %}" type="text/css" /> -->
</head>
<body>
<section class="hero is-success is-bold">
<div class="hero-body">
<div class="container">
{% block slogan %}
{% for propaganda in propagandas %}
<h6>{{ propaganda.slogan }} it's</h6>
{% endfor %}
{% endblock %}
<h1 class="title" style="display: inline-block;">
<span class="icon">
<i class="fa fa-home"></i>
</span>
The Guide
</h1>
{% if user.is_authenticated %}
<div class="field">
<div class="control">
<a href="{% url 'post_new' %}" class="button is-warning is-pulled-right">
<span class="icon">
<i class="fa fa-plus-square"></i>
</span>
<span>New post</span>
</a>
</div>
</div>
{% endif %}
</div><!-- #container -->
</div>
</section>
<!-- content under header in here-> -->
{% block content %}
{% endblock %}
</body>
</html>
views.py
from django.template import RequestContext
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Propaganda
from .forms import PostForm
from django.utils import timezone
# Create your views here.
def post_list(request):
posts = Post.objects.all()
propagandas = Propaganda.objects.all().order_by('?')[:1]
return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})
post_detail.html (where the model does not appear):
{% extends 'blog/header.html' %}
{% block content %}
some html / form that has nothing to do with the header.
{% endblock %}
post_list.html (the 'index' page where the model works fine)
{% extends "blog/header.html" %}
{% block content %}
{% for post in posts %}
<section class="section">
more html
{% endblock %}
need to pass the data from each view function that is required in the header you are extending (re-using) in each template.
def post_detil(request, id):
posts = Post.objects.all()
propagandas = Propaganda.objects.all().order_by('?')[:1]
# ... add in other stuff relevant to post details ...
post = Post.objects.get(pk=id)
return render(request, 'blog/post_detail.html', {'posts': posts, 'propagandas': propagandas, 'post': post})
Stick with it #Rin and Len, you'll get there :)
First: Why are you not showing the view of post_detail. Isn't that the one that does not work?
Second: Even though you are extending a base template you still have to pass the appropriate context in order to generate the desired dynamic data.
I hope it helps.

How to set up a custom template in djangocms

I've successfully installed djangocms on a Ubuntu machine, and now I would like to integrate a custom template bought from Envato.
After I have installed it, djangocms came with its own simple template files which are located in mysite/templates:
base.html
{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}This is my new project home page{% endblock title %}</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.min.css">
{% render_block "css" %}
</head>
<body>
{% cms_toolbar %}
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
{% show_menu 0 1 100 100 "menu.html" %}
</ul>
</div>
</div>
{% block content %}{% endblock content %}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
{% render_block "js" %}
</body>
</html>
feature.html
{% extends "base.html" %}
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
<div class="jumbotron">
{% placeholder "feature" %}
</div>
<div>
{% placeholder "content" %}
</div>
{% endblock content %}
menu.html
{% load i18n menu_tags cache %}
{% for child in children %}
<li class="{% if child.ancestor %}ancestor{% endif %}
{% if child.selected %} active{% endif %}
{% if child.children %} dropdown{% endif %}">
{% if child.children %}
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
{{ child.get_menu_title }} <span class="caret"></span>
</a>
<ul class="dropdown-menu">
{% show_menu from_level to_level extra_inactive extra_active template "" "" child %}
</ul>
{% else %}
<span>{{ child.get_menu_title }}</span>
{% endif %}
</li>
{% if class and forloop.last and not forloop.parentloop %}{% endif %}
{% endfor %}
page.html
{% extends "base.html" %}
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
{% placeholder "content" %}
{% endblock content %}
I have read their documentation but I haven't found anything related to some custom template integration. Could anyone please lead me in the right direction ?
EDIT1:
I have added in CMS_TEMPLATES:
CMS_TEMPLATES = (
## Customize this
('page.html', 'Page'),
('feature.html', 'Page with Feature'),
('index.html', 'oriel.io') # this is what I added
)
but nothing happened.
Add your templates to CMS_TEMPLATES in your settings file.
I recently met the same problem! So let me try to explain
1) You should extend PageAdmin in admin.py
In admin side, when you want to choose template for page ('advanced settings') it will call AdvancedSettingsForm by default. but we must to extend too to give your templates.
class ExtendedPageAdmin(PageAdmin):
def get_form_class(self, request, obj=None, **kwargs):
if 'advanced' in request.path_info:
return ExtendedAdvancedSettingsForm
elif 'permission' in request.path_info:
return PagePermissionForm
elif 'dates' in request.path_info:
return PublicationDatesForm
return self.form
and DO NOT forget unregister and register
admin.site.unregister(Page)
admin.site.register(Page, ExtendedPageAdmin)
2) OK) You have choosen ('advanced settings') and there must be choice among your custom templates.
class ExtendedAdvancedSettingsForm(AdvancedSettingsForm):
def __init__(self, *args, **kwargs):
super(ExtendedAdvancedSettingsForm, self).__init__(*args, **kwargs)
template_choices = [(x, _(y)) for x, y in get_cms_setting('TEMPLATES')]
self.fields['template'] = forms.ChoiceField(choices=template_choices)
3) Ok, wee see custom templates for page, but there will be error if you want to save it. It's because of Page model. It looks like this:
#python_2_unicode_compatible
class Page(six.with_metaclass(PageMetaClass, MP_Node)):
"""
A simple hierarchical page model
"""
...
template_choices = [(x, _(y)) for x, y in get_cms_setting('TEMPLATES')]
...
template = models.CharField(_("template"), max_length=100,
choices=template_choices, default=TEMPLATE_DEFAULT
help_text=_('The template used to render the content.'))
4) So you should change template_choice during init the Page object. Let's use signals
def after_page_init(sender, instance, **kwargs):
instance._meta.get_field_by_name('template')[0]._choices = []
def patch_cms_page():
from cms.models import Page
from django.db.models.signals import post_init
post_init.connect(after_page_init, sender=Page)
and finally call patch_cms_page() in urls.py )