I'm extremely new to Python and Django. I tried to make a code from exercise work, and it was fine for a while, but since I tried to implement templates inheritance I've got this error on my homepage. Rest are working fine...for now. I tried to find solution in similar topics and django docs.,but it didn't help me. Please give me a hand on this one, cause having error at line 0 when I have only 1,2,3.. is really frustrating. Due to my lack of knowledge it's hard to understand even which file is responsible for this error.
Error:
NoReverseMatch at /bboard/
Reverse for 'by_rubric' with arguments '('',)' not found. 1 pattern(s) tried: ['bboard/(?P<rubric_id>[0-9]+)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/bboard/
Django Version: 3.1.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'by_rubric' with arguments '('',)' not found. 1 pattern(s) tried: ['bboard/(?P<rubric_id>[0-9]+)/$']
Exception Location: D:\django\venv_1\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix
Python Executable: D:\django\venv_1\Scripts\python.exe
Python Version: 3.8.5
My views.py:
from django.shortcuts import render
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Rubric
from .models import Bb
from .forms import BbForm
def index(request):
bbs = Bb.objects.all()
rubrics = Rubric.objects.all()
context = {'bbs': bbs, 'rubrics': rubrics}
return render(request, 'bboard/index.html', context)
def by_rubric(request, rubric_id):
bbs = Bb.objects.filter(rubric=rubric_id)
rubrics = Rubric.objects.all()
current_rubric = Rubric.objects.get(pk=rubric_id)
context = {'bbs': bbs, 'rubrics': rubrics, 'current_rubric': current_rubric}
return render(request, 'bboard/by_rubric.html', context)
class BbCreateView(CreateView):
template_name = 'bboard/create.html'
form_class = BbForm
success_url = reverse_lazy('index')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['rubrics'] = Rubric.objects.all()
return context
my urls.py
from django.urls import path
from .views import BbCreateView
from .views import index, by_rubric
urlpatterns = [
path('add', BbCreateView.as_view(), name='add'),
path('<int:rubric_id>/', by_rubric, name='by_rubric'),
path('', index, name='index'),
]
layout/basic.html template
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>{% block title %}Home{% endblock %} - Bill Board</title>
</head>
<body>
<header>
<h1>Advertisements</h1>
</header>
<nav>
Home
Add New
{% for rubric in rubrics %}
{{ rubric.name }}
{% endfor %}
</nav>
<section>
{% block content %}
{% endblock %}
</section>
</body>
</html>
index.html
{% extends 'layout/basic.html' %}
{% block content %}
{% for bb in bbs %}
<div class="b">
<h2>{{ bb.title }}</h2>
<p>{{ bb.content }}</p>
<p>{{ rubric.name }}</p>
<p>{{ bb.published|date:'d.m.Y H:i:s' }}</p>
</div>
{% endfor %}
{% endblock %}
by_rubric.html
{% extends 'layout/basic.html' %}
{% block title %}{{ current_rubric.name }}{% endblock %}
{% block content %}
<h2>Rubric: {{ current_rubric.name }}</h2>
{% for bb in bbs %}
<div>
<h2>{{ bb.title }}</h2>
<p>{{ bb.content }}</p>
<p>{{ bb.published|date:'d.m.Y H:i:s' }}</p>
</div>
{% endfor %}
{% endblock %}
The reason that this raises an error is the line:
<p>{{ rubric.name }}</p>
in the index.html template. You do not pass a rubric object ot the index.html template, so rubric.pk does not exists, and is resolved to the empty string, and this does does not match with the <int:pk> path converter.
You can replace this with:
{% for rubric in rubrics %}
<p>{{ rubric.name }}</p>
{% endfor %}
{% extends 'layout/basic.html' %}
{% block content %}
{% for bb in bbs %}
<div class="b">
<h2>{{ bb.title }}</h2>
<p>{{ bb.content }}</p>
<p>{{ rubric.name }}</p>
<p>{{ bb.published|date:'d.m.Y H:i:s' }}</p>
</div>
{% endfor %}
{% endblock %}
in index.html
Related
I am a beginner in HTML templates and Django.
basic_app_base.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Base</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-default navbar-static-top">
<ul class="nav navbar-nav">
<li><a class="navbar-brand" href="{% url 'basic_app:list' %}">School</a></li>
<li><a class="navbar-link" href="{% url 'admin:index' %}"></a></li>
<li></li>
</ul>
</nav>
<div class="container">
{% block body_block %}
{% endblock %}
</div>
</body>
</html>
school_list.html
{% extends "basic_app/basic_app_base.html" %}
<!-- {% load static %} -->
{% block body_block %}
<h1>Here are the list of all the schools!</h1>
<ol>
{% for school in schools %}
<h2><li>{{school.name}}</li></h2>
{% endfor % }
</ol>
{% endblock %}
**Error:**TemplateSyntaxError at /basic_app/
Invalid block tag on line 10: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Views.py
from django.shortcuts import render
from django.views.generic import (View,TemplateView,
ListView,DetailView)
from . import models
# from django.http import HttpResponse
# Template views with CBV
class IndexView(TemplateView):
template_name='index.html'
# List View
class SchoolListView(ListView):
context_object_name='schools'
model=models.School
template_name='basic_app/school_list.html'
# Detail View
class SchoolDetailView(DetailView):
context_object_name='school_detail'
model=models.School
template_name='basic_app/school_detail.html'
models.py
from django.db import models
from django.urls import reverse
# Create your models here.
class School(models.Model):
name=models.CharField(max_length=256)
principal=models.CharField(max_length=256)
location=models.CharField(max_length=256)
def __str__(self):
return self.name
class Student(models.Model):
name=models.CharField(max_length=256)
age=models.PositiveIntegerField()
school=models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)
def __str__(self):
return self.name
urls.py
from django.urls import include, re_path
# from django.conf.urls import url
from basic_app import views
app_name='basic_app'
urlpatterns = [
re_path(r'^$',views.SchoolListView.as_view(),name='list'),
re_path(r'^(?P<pk>\d+)/$',views.SchoolListView.as_view(),name='detail')
]
I need output like the following image, when clicking on school page :
I found the error, and I was giving too much space after the % when closing the endfor tag.
error on school_list.html file
in line 8 :{% endfor % }
too much space after the % when closing the endfor tag.
solution: {% endfor %}
"After correcting this error on the line 8, it worked for me."
Need remove extra space afrer % in {% endfor % }
after correction
{% extends "basic_app/basic_app_base.html" %}
<!-- {% load static %} -->
{% block body_block %}
<h1>Here are the list of all the schools!</h1>
<ol>
{% for school in schools %}
<h2><li>{{school.name}}</li></h2>
{% endfor %} <---------------------- in this line need correction, put {% endfor %} insted of {% endfor % }
</ol>
{% endblock %}
Thank you for reading my question, and for your help.
I wrote a simple CRUD app, and used django-tables2 module to make my tables look pretty and more robust. I am using django 3.2, python 3.8.5, django_tables2 2.3.4.
I can enter a query in the search bar on the home.html page and lists the returned results from a postgresql on the search_results.html page. On the search_results page, I have buttons next to each returned row with edit and delete options, when I hover over update buttons it points to url for localhost:8955/update/7887 or localhost:8955/delete/7887 for the delete button, of course the last four digits are unique to the returned rows, however when I click on the update or delete button I get a NoReverseMatch error. I am at my wits end what is causing the edit and delete buttons not to work, your help and assistance is very much appreciated it.
Image with the returned results with the update and delete button
tables.py
from .models import EsgDatabase
from django.urls import reverse_lazy
from django.contrib.auth.models import User as user
class EsgListViewTable(tables.Table):
class Meta:
model = EsgDatabase
template_name = "django_tables2/bootstrap-responsive.html"
fields = ('id','role', 'hq','system','market','state','zone','arrisseachangezone','xgsystem','xgzonecode','fto','xocnoc','snowticketassignment',)
if user.is_authenticated:
edit = TemplateColumn(template_name='update.html')
delete = TemplateColumn(template_name='delete.html')
app urls.py
from django.urls import path, include
from .views import HomePageView, SearchResultsView, EsgCreateView, EsgUpdateView, EsgDeleteView, EsgDetailView
urlpatterns = [
path('search/', SearchResultsView.as_view(),name='search_results',),
path('', HomePageView.as_view(), name='home'),
path('createform/', EsgCreateView.as_view(), name='createform'),
path('update/<int:pk>', EsgUpdateView.as_view(), name='update'),
path('delete/<int:pk>', EsgDeleteView.as_view(), name='delete' ),
path('details/<int:pk>', EsgDetailView.as_view(), name='details'),
]
views.py
from .models import EsgDatabase
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView, DetailView
from django_tables2 import SingleTableView
from esgsheet.tables import EsgListViewTable
class EsgDetailView(DetailView):
template_name = 'details.html'
model = EsgDatabase
table_class = EsgListViewTable
context_object_name = 'esgdetail'
def get_success_url(self):
return reverse_lazy('details',kwargs={'pk':self.object.id})
class HomePageView(TemplateView):
template_name = 'home.html'
context_object_name = 'esghome'
#method_decorator(login_required, name='dispatch')
class EsgDeleteView(DeleteView):
template_name = 'delete.html'
model = EsgDatabase
table_class = EsgListViewTable
# success_url = reverse_lazy('home')
context_object_name = 'deleteview'
def get_success_url(self):
return reverse_lazy('home',kwargs={'pk':self.object.id})
#method_decorator(login_required, name='dispatch')
class EsgUpdateView(UpdateView):
model = EsgDatabase
fields = '__all__'
table_class = EsgListViewTable
template_name = 'update.html'
context_object_name = 'esgupdate'
strong textdef get_success_url(self):
return reverse_lazy('details', kwargs={'pk':self.object.id})
#method_decorator(login_required, name='dispatch')
class EsgCreateView(CreateView):
model = EsgDatabase
fields = '__all__'
template_name = 'forms.html'
def get_success_url(self):
return reverse_lazy('details', kwargs={'pk':self.object.id})
class SearchResultsView(SingleTableView):
model = EsgDatabase
table_class = EsgListViewTable
template_name = 'search_results.html'
SingleTableView.table_pagination = False
def get_queryset(self):
query = self.request.GET.get('q')
if query:
object_list = EsgDatabase.objects.filter(
Q(role__icontains=query) | Q(hq__icontains=query) |
Q(system__icontains=query) | Q(market__icontains=query) |Q(state__icontains=query) |
Q(zone__icontains=query) |Q(arrisseachangezone__icontains=query) |Q(xgsystem__icontains=query) |
Q(xgzonecode__icontains=query) | Q(syscode__icontains=query) |Q(fto__icontains=query) |
Q(xocnoc__icontains=query) |Q(snowticketassignment__icontains=query)
)
else:
object_list = self.model.objects.none()
return object_list
base.html
{% load django_tables2 %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<center>
{% block title %}
{% endblock title %}
</center>
</head>
<body>
<!-- {% url 'home' as home %}
{% if request.path != home %}
<center> <br>
<form action="{% url 'search_results' %}" method="GET">
<input name='q' type="text" placeholder="Search ESG Database">
</form> <br>
</center>
{% endif %} -->
{% block content %}
{% endblock content %}
</body>
</html>
home.html
{% extends 'base.html' %}
{% block title %}
<h1>ESG Database</h1>
{% endblock title %}
{% block content %}
<center>
<form action="{% url 'search_results' %}" method="GET">
<input name='q' type="text" placeholder="Search ESG Database">
</form>
</center>
{% endblock content %}
delete.html
{% block title %}
{% endblock title %}
{% block content %}
<form method="POST">{% csrf_token %}
</form>
{% if user.is_authenticated %}
<a type="submit" class="btn btn-danger btn-sm" href="{% url 'delete' record.id %}" >Delete.html</a>
{% endif %}
{% endblock content %}
update.html
{% extends 'base.html' %}
{% block title %}
{% endblock title %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{form.as_p}}
{% if user.is_authenticated %}
<a type="submit" class="btn btn-info btn-sm" href="{% url 'update' record.id %}" >Update.html</a>
{% endif %}
</form>
{% endblock content %}
search_results.html
{% extends 'base.html' %}
{% load render_table from django_tables2 %}
{% block title %}
<h1>ESG Database Results</h1>
{% endblock title %}
{% block content %}
{% render_table table %}
{% endblock content %}
forms.html
{% extends 'base.html' %}
{% block title %}
<h1>Create ESG Entry</h1>
{% endblock title %}
{% block content %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
{% if user.is_authenticated %}
<input type="submit" value="Submit">
{% endif %}
</form>
{% endblock content %}
details.html
{% extends 'base.html' %}
{% block title %}
<h1>Updated Detail View</h1>
{% endblock title %}
{% block content %}
<table class="table table-hover">
<thead>
<th>Role</th>
<th>HQ</th>
<th>System</th>
<th>Market</th>
<th>State</th>
<th>Zone</th>
<th>Arris/SeaChange Zone</th>
<th>xG System</th>
<th>xG Zone Code</th>
<th>Syscode</th>
<th>FTO</th>
<th>XOC/NOC</th>
<th>SNOW Ticket Assignment</th>
</thead>
<tbody>
<tr>
<td>{{esgdetail.role}}</td>
<td>{{esgdetail.hq}} </td>
<td>{{esgdetail.system}} </td>
<td>{{esgdetail.market}} </td>
<td>{{esgdetail.state}} </td>
<td>{{esgdetail.zone}} </td>
<td>{{esgdetail.arrisseachangezone}} </td>
<td>{{esgdetail.xgsystem}} </td>
<td>{{esgdetail.xgzonecode}} </td>
<td> {{esgdetail.syscode}} </td>
<td> {{esgdetail.fto}} </td>
<td>{{esgdetail.xocnoc}} </td>
<td> {{esgdetail.snowticketassignment}} </td>
<!-- <td>
edit
delete
</td> -->
</tr>
</tbody>
</table>
{% endblock content %}
Thanks to #funkybob at #django irc room. First I had to delete comments from my code because it was being parsed throwing NoReverseMatch errors. Second, I had to remove context_object_name from update and delete views.
Trying to use a paginator in a view. Getting none from page = request.GET.get('page'). As is, the call to paginator limits posts on a page properly, but any call to page sequence henceforth fails. Pages will display, but there will be nothing form pagination.html displayed. For clarity, Base.html is the base template from which all others inherit. list.html is the page where I expect to see pagination.html displayed.
This code is based off of the django manual. Is there something else that needs to be setup to give the requests querydict a key of 'page' or a better way to paginate?
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def post_list(request):
object_list = Post.published.all() #a list of the posts
paginator = Paginator(object_list, 4) # 4 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request,'blog/post/list.html',{'page': page,'posts': posts})
pagination.html
<div class="pagination">
<span class="step-links">
{% if page.has_previous %}
Previous
{% endif %}
<span class="current">
Page {{ page.number }} of {{ page.paginator.num_pages }}.
</span>
{% if page.has_next %}
Next
{% endif %}
</span>
</div>
base.html
#...
<div id="content">
{% block content %}
{% include "pagination.html" with page=posts %}
{% endblock %}
</div>
#...
list.html
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
When you fill a block in a child template it replaces the super template's block's content (not literally the block named content here). If you want to keep the parent's block along with some extra content, you should use {{ block.super }}, i.e. list.html should be:
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{{ block.super }}
{% endblock %}
I have problem with accessing by the link. I am using easy-thumbnail framework, and I created simple view for user list to list all existing users.
Error message:
django.template.exceptions.TemplateSyntaxError: Variable
'user.profile.photo' is an invalid source.
Django Traceback throws me to this view.
views.py file:
#login_required
def user_list(request):
users = User.objects.filter(is_active=True)
return render(request,
'account/user/list.html',
{'section': 'people',
'users': users})
urls.py file:
path('users/', views.user_list, name='user_list'),
template list.html:
{% extends "base.html" %}
{% load thumbnail %}
{% block title %}People{% endblock %}
{% block content %}
<h1>People</h1>
<div id="people-list">
{% for user in users %}
<div class="user">
<a href="{{ user.get_absolute_url }}">
<img src="{% thumbnail user.profile.photo 180x180 %}">
</a>
<div class="info">
<a href="{{ user.get_absolute_url }}" class="title">
{{ user.get_full_name }}
</a>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
sample code from base.html:
<li {% if section == "people" %}class="selected"{% endif %}>
People
</li>
models.py:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d/',
blank=True)
def __str__(self):
return f'Profile for user {self.user.username}'
Thank you for the helping in advance.
Reviewed the documentation https://easy-thumbnails.readthedocs.io/en/latest/usage/#templates. Creates a thumbnail from an object (usually a file field). I tried it and it helped solve my problem:
<img src="{{ user.profile.photo.url }}">
I had this problem too. You can solve the problem with the following solution:
Instead of users = User.objects.filter(is_active=True), use profiles = Profile.objects.all()
Change as follows: return render(request,'account/user/list.html',{'section': 'people', 'profiles': profiles}).
In the list.html file, change as follows:
{% extends 'base.html' %}
{% load thumbnail %}
{% block title %}People{% endblock %}
{% block content %}
<h1>People</h1>
<div id="people-list">
{% for profile in profiles %}
<div class="user">
<a href="{{ profile.user.get_absolute_url }}">
<img src="{% thumbnail profile.photo 180x180 %}" alt="{{ profile.user.last_name }}">
</a>
<div class="info">
<a href="{{ profile.user.get_absolute_url }}" class="title">
{{ profile.user.get_full_name }}
</a>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
I am trying to learn django and while making a viewport view, I came up with this error saying Reverse for 'viewpost' with arguments '(1,)' not found. 1 pattern(s) tried: ['int:post\\.id$'] I don't understand what is the mistake I am doing
Views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def main(request):
return render(request, "blog/index.html", {"Posts":Post.objects.all()})
def viewpost(request):
return render(request, "blog/viewpost.html")
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('',views.main, name = 'main'),
path('viewpost/int:pk/', views.viewpost, name = 'viewpost')
]
index.html
{% extends 'blog/layout.html' %}
{% block body %}
<h1>Physics Blog</h1>
{% for post in Posts %}
<fieldset>
<h2>{{ post.Title }}</h2>
<h4>{{ post.Description }}</h4>
<h6>{{ post.Author }}</h6>
</fieldset>
<br>
{% endfor %}
{% endblock %}
viewpost.html
{% extends 'blog/layout.html' %}
{% block body %}
<h1>{{ post.Title }}</h1>
<h1>{{ post.Description }}</h1>
<h1>{{ post.Author }}</h1>
{% endblock %}
The problem is this line:
path('viewpost/int:pk/', views.viewpost, name = 'viewpost')
int:pk is missing the angular brackets. Change it to
path('viewpost/<int:pk>/', views.viewpost, name='viewpost')
The path() in your question doesn't seem to match 'int:post\\.id$ in the error message. So make sure you have saved the file and restarted runserver.
You'll also have to change viewpost so that it accepts the pk.
def viewpost(request, pk):