Django - Template does not show DetailView - python

I am encountering the following error when trying to set DetailView for each of the post in my postlist:
NoReverseMatch at /blog/post-list/ Reverse for 'postdetail' with
keyword arguments '{'id': ''}' not found. 1 pattern(s) tried:
['blog\/post-list/(?P\d+)/$']
Here the code:
views.py
def PostList(request):
postlist = Post.objects.all()
context = {
"postlist":postlist
}
template_name = "postlist.html"
return render(request,template_name,context)
def PostDetail(request,id):
post = get_object_or_404(Post,id=id)
context = {
'post':post
}
template_name = "postdetail.html"
return render(request,template_name,context)
postlist.html
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="col">
{% for item in postlist %}
<ul>
<li><h3>Title:</h3> {{ item.title }} <smal>{{ item.timestamp }}</smal></li>
<li><h3>description:</h3>{{ item.description }}</li>
<li><h3>Updated:</h3>{{ item.updated }}</li>
<li><h>Author: {{ item.Author }}</h></li>
{{ item.id }}
</ul>
{{ item }}
{% endfor %}
</div>
</div>
</div>
{% endblock %}
urls.py
urlpatterns = [
re_path(r'^post-list/$',views.PostList,name ='postlist'),
re_path(r'^post-list/(?P<id>\d+)/$',views.PostDetail,name="postdetail"),
path ('post-create',views.CreatPost, name='post-create'),
re_path (r'^post-list/update/(?P<id>\d+)/$',views.PostUpdateis,name='update-post'),
# re_path(r'^(?P<slug_post>[-\w])+/$',views.PostDetail,name="postdetail"),
]
Does anybody know how to solve this?

Related

I am stuck when accessing the DetailView template in Django

urls.py
urlpatterns = [
path('',CourseList.as_view(),name='course_list'),
path('create/',CourseCreate.as_view(),name='course_create'),
path('<int:cid>/',CourseView.as_view(),name='course_view'),
]
views.py
COURSE_PERM_GUEST = 0
COURSE_PERM_STUDENT = 1
COURSE_PERM_TEACHER = 2
COURSE_PERM_MEMBER = 3
class CourseAccessMixin(AccessMixin):
permission = None
extra_context = {}
def dispatch(self,request,*args,**kwargs):
if not request.user.is_authenticated:
return super().handle_no_permission()
self.course = get_object_or_404(Course,id=kwargs['cid'])
user_perm = COURSE_PERM_GUEST
if self.course.teacher == request.user:
user_perm = COURSE_PERM_TEACHER
elif self.course.enroll_set.filter(student=request.user).exists():
user_perm = COURSE_PERM_STUDENT
if not request.user.is_superuser and self.permission is not None:
is_accessible = False
if self.permission == COURSE_PERM_GUEST and \
user_perm == COURSE_PERM_GUEST:
is_accessible = True
elif (self.permission & user_perm) != 0:
is_accessible = True
if not is_accessible:
return super().handle_no_permission()
self.extra_context.update({'course':self.course})
return super().dispatch(request,*args,**kwargs)
class CourseView(CourseAccessMixin,DetailView):
extra_context = {'title':'檢視課程'}
model = Course
pk_url_kwarg = 'cid'
models.py
class Course(models.Model):
name = models.CharField('課程名稱',max_length=50)
enroll_password = models.CharField('選課密碼',max_length=50)
teacher = models.ForeignKey(User,models.CASCADE)
def __str__(self):
return '{}#{} ({})'.format(
self.id,
self.name,
self.teacher.first_name)
course_list.html
{% extends "base.html" %}
{% load user_tags %}
{% block content %}
{% if user|is_teacher %}
<div class="mb-2">
建立課程
</div>
{% endif %}
<div id="course_list">
{% for course in course_list %}
<div class="list-group">
<div class="list-group-item d-flex">
{% if user.is_authenticated %}
{{ course.name }}
{% else %}
{{ course.name }}
{% endif %}
<small class="ml-auto">{{ course.teacher.first_name }} 老師</small>
</div>
</div>
{% endfor %}
</div>
{% include 'pagination.html' %}
{% endblock %}
course_detail.html
{% extends 'base.html' %}
{% load user_tags %}
{% block content %}
<div id="course_view" class="card">
{% with b1 = "btn btn-sm btn-primary" b2 = "btn btn-sm btn-secondary" %}
<div class="card-header d-flex">
<div>
{{ course.name }}
<small>{{ course.teacher.first_name }} 老師</small>
</div>
{% if user.is_superuser or course.teacher == user %}
<div class="ml-auto">
<span class="badge badge-light">
選課密碼: {{ course.enroll_password }}
</span>
<a href="{% url 'course_edit' course.id %}" class="{{ b1 }}">
<i class="fas fa-edit"></i>編輯
</a>
</div>
{% endif %}
</div>
<div class="card-body">
{% block course_detail_body %}
<div id="student_op" class="btn-group">
{% if not course|has_member:user and not user.is_superuser %}
<a href="{% url 'course_enroll' course.id %}" class="{{ b1 }}">
<i class="fas fa-id-badge"></i>選修
</a>
{% else %}
<a href="{% url 'course_users' course.id %}" class="{{ b1 }}">
<i class="fas fa-users"></i>修課名單
</a>
{% if course|has_student:user %}
<a href="{% url 'course_seat' course.id %}" class="{{ b1 }}">
<i class="fas fa-chair"></i>更改座號
</a>
{% endif %}
{% endif %}
</div>
{% endblock %}
</div>
{% endwith %}
</div>
{% endblock %}
Error:
ValueError at /course/1/
The view course.views.CourseView didn't return an HttpResponse object. It returned None instead.
I had a view CourseView and when I try to access the detail of the corresponding course by clicking the hyperlink {{ course.name }} from the template course_list.html, I received the error message showing that it didn't return an HttpResponse object. I do not know what is missing in order to have the details accessible even though I had set the pk_url_kwarg?
You forget to add return super().dispatch(request,*args,**kwargs) and the end of dispatch function (you add it, only in if condition)
change this
self.extra_context.update({'course':self.course})
return super().dispatch(request,*args,**kwargs)
To this:
self.extra_context.update({'course':self.course})
return super().dispatch(request,*args,**kwargs)
return super().dispatch(request,*args,**kwargs)

How to create a Class Based Views search bar on Django

I'm making a search bar in Django using Class-Based Views on my Views.py. When I try to get the value submitted in the input it's not showing the query name and if I don't submit anything is NOT giving me an error. Also what is the way to get the post showed by the world searched? Thanks for all. My code is:
Models.py:
class Post(models.Model): # Post core
title = models.CharField(max_length=299)
author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE)
category = models.CharField(max_length=50)
image = models.ImageField(blank=True)
desc = models.TextField()
text = RichTextField(blank = True, null = True )
date = models.DateTimeField(auto_now=False, auto_now_add=True)
slug = models.SlugField(null = True, blank = True, unique=True)
class Meta: # Order post by date
ordering = ['-date',]
def __str__(self): # Display title
return self.title
def get_absolute_url(self): # #TODO da cambiare
return reverse("listpost")
Views.py:
class SearchView(TemplateView):
model = Post
template_name = "admin/search.html"
def get(self, request, *args, **kwargs):
q = request.GET.get('q', '')
self.results = Post.objects.filter(text__icontains=q, desc__icontains = q, title__icontains = q)
return super().get(request, *args, **kwargs)
Urls.py:
path('dashboard/listpost/search/', SearchView.as_view(), name="search")
ListPost.html:
{% extends "admin/layout.html" %}
{% block title %}
<title>Post List</title>
{% endblock title %}
{% block content %}
<form action="{% url 'search' %}" method="GET">
<input type="text" placeholder="Cerca" name="search"> <button>Cerca</button>
</form>
<div class="postlist">
<div class="cards"> <!-- Card Container -->
{% for post in object_list %}
<div class="card"> <!-- Single Card -->
{% if post.image %}
<img src="{{post.image.url}}" alt="">
{% endif %}
<h3>{{ post.title }}</h3>
<p>
{{ post.category }}
{{ post.author }}
<data class="data"> {{ post.date|date:'d-m-Y' }} </data>
</p>
<p class="desc-list">{{ post.desc|truncatewords:10 }}</p>
edit
delate
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
Search.html
{% extends "admin/layout.html" %}
{% block title %}
<title>Search</title>
{% endblock title %}
{% block content %}
{% if query %}
{{Query}}
{% else %}
<p>Nope</p>
{% endif %}
{% endblock content %}
Your are trying to display the variable query, Query (two different variables since the template language is case sensitive).
Your do not pass any of those two variables in the template context.
I don't see any query nor Query variable in your view.
It seems that your want to show the results variable, so I will assume this.
Your need to send the results from your queryset in the template results.
The get_context_data method ContextMixin (one of the TemplateView derived classes) is useful for this.
class SearchView(TemplateView):
model = Post
template_name = "admin/search.html"
def get(self, request, *args, **kwargs):
q = request.GET.get('q', '')
self.results = Post.objects.filter(text__icontains=q, desc__icontains = q, title__icontains = q)
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""Add context to the template"""
return super().get_context_data(results=results, **kwargs)
And in your template:
{% extends "admin/layout.html" %}
{% block title %}
<title>Search</title>
{% endblock title %}
{% block content %}
{% if results.exists %}
{% for result in results %}
{{ result }}
{% endfor %}
{% else %}
<p>Nope</p>
{% endif %}
{% endblock content %}

Calculation in your template with values passed in as context to display content

Im having trouble displaying some divs using the context passed in through my view. In my views.py, i'm passing a value "total_used"" and "total".
views.py:
def home(request):
context = {
"reward": [
{
"total": 5,
"total_used": 2
}
]
}
return render(request, "web/index.html", context)
Template:
{% with ''|center:reward.total_used as range %}
{% for _ in range %}
<div class="red"></div>
{% endfor %}
{% endwith %}
<div class="blue"></div>
<div id="reward-count">
<h5>{{ reward.total_used }}/{{ reward.total }}</h5>
</div>
So for example, I want 2 divs with class red, and 3 divs (reward.total- reward.total_used) with the class blue.
I have tried this but it didn't work:
{% with ''|center:reward.total_used as range %}
{% for _ in range %}
<div class="red"></div>
{% endfor %}
{% endwith %}
{% with ''|center:reward.total-reward.total_used as range %}
{% for _ in range %}
<div class="blue"></div>
{% endfor %}
{% endwith %}
<div id="reward-count">
<h5>{{ reward.total_used }}/{{ reward.total }}</h5>
</div>
Remove the square brackets [] from context definition. Your views.py should look like this:
def home(request):
context = {
"reward": {"total": 5, "total_used": 2}
}
return render(request, "web/index.html", context)
I ended up calculating total-total_used in my views, then adding it to my context:
views.py:
def home(request):
context = {
"rewards": [
{
"total": 5,
"total_used": 2
},
{
"total": 7,
"total_used": 1
}
]
}
for reward in context['rewards']:
reward['total_not_used'] = reward['total'] - reward['total_used']
return render(request, "web/index.html", context)
Template:
{% with ''|center:reward.total_used as range %}
{% for _ in range %}
<div class="reward reward-shaded"></div>
{% endfor %}
{% endwith %}
{% with ''|center:reward.total_not_used as range %}
{% for _ in range %}
<div class="reward"></div>
{% endfor %}
{% endwith %}
<div id="reward-count">
<h5>{{ reward.total_used }}/{{ reward.total }}</h5>
</div>

Reverse for ' write' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I was updating from django 1.7 to django 1.9 and i am getting this error message.
"NoReverseMatch at /gaestebuch/"
"Reverse for ' write' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []"
here is my code:
urls.py:
from django.conf.urls import url
from . import views
app_name = 'gaestebuch'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<id>[0-9]+)/$', views.result, name='result'),
url(r'^comment/$', views.comment, name='comment'),
url(r'^write/', 'gaestebuch.views.write', name='write'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^(?P<pk>[0-9]+)/delete$', views.delete_eintrag,
name='delete_eintrag'),
url(r'^(?P<pk>[0-9]+)/comment/$', views.write_comment_eintrag,
name='write_comment_eintrag'),
]
index.html
<div id = "content_main">
<div id = "header_main">
<div id = "logo_main">
{% if user.is_authenticated %}
<p>Hallo {{ user.username }}! :))</p>
{% else %}
<p>Hallo ihr Lieben!</p>
{% endif %}
</div>
<div id= "write_main">
{% if user.is_authenticated %}
<p>Logout</p>
<p>Eintrag Verfassen</p>
{% else %}
<p>Hier Registrieren</p>
<p>Hier Einloggen</p><br />
{% endif %}
</div>
</div>
<div id = "list_main">
{% if latest_eintrage_list %}
<ul>
<br>
{% for e in latest_eintrage_list %}
<li>
<div id="comment_main">
{{ e.author }}
<br>
</div>
{{ e.title }}
<br>
<div id="comment_main">
Kommentare: {{ e.comments.count }} | {{ e.created_date }} | {{ e.get_typ_display }}
</div>
<hr>
</li>
{% endfor %}
<br>
</ul>
{% else %}
<p>Keine Eintraege verfuegbar!</p>
{% endif %} </div>
<div id = "footer_main">
Impressum
</div>
</div>
It is refering to this line:
<p>Eintrag Verfassen</p>
This:
<p>Eintrag Verfassen</p>
does not work too.
Can someone tell me what the problem is?
Remove the space between gaestebuch and write:
<p>Eintrag Verfassen</p>

Pass 2 or more variables to django template

i want to pass 2 lists to django template but only first is rendered
this is index.html:
enter code here
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
{% if menu_items_list %}
<table id="menu_items_list">
<tr>
{% for item_url, item_name in menu_items_list %}
<td>item_name
{% endfor %}
</tr>
</table>
{% endif %}
<h3>{{ index_name }}</h3>
and this is urlconf:
urlpatterns = patterns('zzz.polls.views',
url(r'^$',
ListView.as_view(
queryset=Poll.objects.order_by('pub_date')[:5],
context_object_name='latest_poll_list',
template_name='index.html')),
and views:
def index(request):
latest_poll_list = Poll.objects.all().order_by('pub_date')[:5]
index_name = 'INDEX PAGE'
menu_items_list = ['somesite.com', 'Googy') for x in xrange(5)]
return render_to_response('index.html', {'latest_poll_list': latest_poll_list,
'menu_items_list' : menu_items_list,
'index_name': index_name})
where i make mistake??
The syntax of the LC is wrong.
>>> ['somesite.com', 'Googy' for x in xrange(5)]
File "<stdin>", line 1
['somesite.com', 'Googy' for x in xrange(5)]
^
SyntaxError: invalid syntax
>>> [('somesite.com', 'Googy') for x in xrange(5)]
[('somesite.com', 'Googy'), ('somesite.com', 'Googy'), ('somesite.com', 'Googy'), ('somesite.com', 'Googy'), ('somesite.com', 'Googy')]

Categories