Django NoReverseMatch error - python

I'm trying to build a little django "board" app for my classmates.
But I'm getting this error which I can't find a way around.
I presume it has to be something to do with template rendering, but I don't know what the problems is. It was working fine until I made some modifications to the views & template below. Even after when I undid all the changes I made, it stopped working and returned the same error.
Error
NoReverseMatch at /board/2/
Reverse for 'read_article' with arguments '('', 10)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['board/(?P<board_id>\\d+)/(?P<article_id>\\d+)/$']
Request Method: GET
Request URL: http://192.168.56.101:8000/board/2/
Django Version: 1.7.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'read_article' with arguments '('', 10)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['board/(?P<board_id>\\d+)/(?P<article_id>\\d+)/$']
Exception Location: /home/web/venv/lib/python3.4/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 468
Python Executable: /home/web/venv/bin/python
Python Version: 3.4.2
Views.py
def index(request):
boards = Board.objects.order_by("title")
dashboards = []
try:
if request.session["error"]:
error_message = request.session["error"]
del request.session["error"]
except KeyError:
error_message = None
for board in boards:
articles = board.article_set.order_by("-written_date")[:5]
dashboard_item = {
"board" : board,
"articles" : articles,
}
dashboards.append(dashboard_item)
context = {
"boards" : Board.objects.all(),
"dashboards" : dashboards,
"error_message" : error_message,
}
return render(request, "index.html", context)
def read_board(request, board_id):
board = get_object_or_404(Board, id=board_id)
article_list = board.article_set.order_by("-written_date")
paginator = Paginator(article_list, 5)
page = request.GET.get("page")
try:
articles = paginator.page(page)
except PageNotAnInteger:
articles = paginator.page(1)
except EmptyPage:
articles = paginator.page(paginator.num_pages)
context = {
"articles" : articles,
"pages" : paginator.page_range
}
return render(request, "board.html", context)
def read_article(request, board_id, article_id):
article = get_object_or_404(Article, id=article_id)
reply_list = article.reply_set.order_by("written_date")
try:
if request.session["error"]:
error_message = request.session["error"]
del request.session["error"]
except KeyError:
error_message = None
context = {
"boards" : Board.objects.all(),
"board_id" : board_id,
"article" : article,
"replies" : reply_list,
"error_message" : error_message,
}
return render(request, "article.html", context)
Urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'board.views.index', name = 'index'),
url(r'^board/(?P<board_id>\d+)/$', 'board.views.read_board', name = 'board'),
url(r'^board/(?P<board_id>\d+)/(?P<article_id>\d+)/$', 'board.views.read_article', name = 'read_article'),
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='login'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template
{% include "header.html" %}
{% include "navbar.html" %}
<div class="container">
<div class="page-header">
<h3>{{ board.title }}</h3>
</div>
<div class="list-group">
<div class="list-group-item list-group-item-info text-center">
<div class="row text-center">
<div class="col-xs-2 col-md-2">글번호</div>
<div class="col-xs-4 col-md-5">글제목</div>
<div class="col-xs-3 col-md-2">작성자</div>
<div class="col-xs-3 col-md-3">작성시간</div>
</div>
</div>
{% if articles %}
{% for article in articles %}
<a href="{% url 'read_article' board.id article.id %}" class="list-group-item">
<div class="row text-center">
<div class="col-xs-2 col-md-2">{{ article.id }}</div>
<div class="col-xs-4 col-md-5">{{ article.title }}</div>
<div class="col-xs-3 col-md-2">{{ article.user.first_name }} {{ article.user.last_name }}</div>
<div class="col-xs-3 col-md-3">{{ article.written_date }}</div>
</div>
</a>
{% endfor %}
{% else %}
<div class="list-group-item text-center">작성된 글이 없습니다</div>
{% endif %}
</div>
새글쓰기
{% include "paginator.html" %}
</div>
{% include "footer.html" %}

From the traceback I find that the board.id you provide in url tag in the template is empty, and in fact, you haven't specified it in your context.

Related

"POST /......... / ......... / HTTP/1.1" 405 0 - Django

I have a problem, in my work I need to insert a system of likes to published posts but by clicking on the button that should give the post a like, nothing happens and this error comes out..."POST /posts/like/ HTTP/ 1.1" 405 0
views.py
#ajax_required
#require_POST
#login_required
def post_like(request):
post_id = request.POST.get('id')
action = request.POST.get('action')
if post_id and action:
try:
post = Post.objects.get(id=post_id)
if action == 'like':
post.users_likes.add(request.user)
else:
post.users_likes.remove(request.user)
return JsonResponse({'status': 'ok'})
except:
pass
return JsonResponse({'status': 'error'})
urls.py
from django.urls import path, include
from . import views
app_name = 'posts'
urlpatterns = [
path('like/', views.post_like, name='like'),
]
index.html
{% with total_likes=post.users_likes.count users_likes=post.users_likes.all %}
<div class="post-info">
<div>
<span class="count">
<span class="total">{{ total_likes }}</span>
like{{ total_likes|pluralize }}
</span>
<a href="#" data-id="{{ post.id }}" data-action="{% if request.user in users_likes %}un{% endif %}like" class="like">
{% if request.user not in users_likes %}
Like
{% else %}
Unlike
{% endif %}
</a>
</div>
</div>
<div class="post-likes">
{% for user in users_likes %}
<div>
<p>{{ user.first_name }}</p>
</div>
{% empty %}
<p>No body likes this post yet</p>
{% endfor %}
</div>
{% endwith %}
<p>{{ post.id }}</p>
<a class="normal-text" href="{{ post.get_absolute_url }}">Discover more...</a>
</div>
</div>
ajax code
<script>
{% block domready %}
$('a.like').click(function(e){
e.preventDefault();
$.post("{% url 'posts:like' %}",
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok')
{
var previous_action = $('a.like').data('action');
// toggle data-action
$('a.like').data('action',
previous_action == 'like' ? 'unlike' : 'like');
// toggle link-text
$('a.like').text(
previous_action == 'like' ? 'Unlike' : 'Like');
// update total likes
var previous_likes = parseInt(
$('span.count .total').text());
$('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes -1);
}
}
);
});
{% endblock %}
</script>
I don't understand where the problem is... I thought in the url but I don't think so
From the documentation, it appears that your urls.py is at fault - you define a "like/" pattern, but there's nothing to tell the router that you mean for it to have a "posts/" prefix.
The examples given there explicitly use an include directive to do that, and you do no such thing. Try:
from django.urls import include, path
from . import views
urlpatterns = [
path('posts/', include([
path('like/', views.post_like, name='like'),
# Other posts/... endpoints
])),
# path('users/', include([ ...
]

ValueError at /post/politics Field 'id' expected a number but got 'politics'

I have a template posts.html
{% extends 'base2.html' %}
{% block posts %}
<div class="row">
<div class="leftcolumn">
<div class="cardpost">
<h1>{{posts.title}}</h1>
<h5>{{posts.created_at}}</h5>
<div class="fs-4">{{posts.body | safe}}</div>
</div>
</div>
</div>
{% endblock %}
posts.html extends base2.html, because I want the posts.html to have nav bar functionality
<nav id="navbar" class="navbar">
<ul>
<li>About</li>
<li>Guest Posting</li>
<li class="dropdown"><span>Categories</span> <i class="bi bi-chevron-down dropdown-indicator"></i>
<ul>
<li>Tech</li>
<li>Bizconomics</li>
<li>Politics</li>
<li>Religion</li>
<li>Sports</li>
</ul>
</li>
<li>Contact</li>
</ul>
above is a section of the nav bar which is on base2.html, and also on the index.html. It works perfectly in the index.html. But when the user is on the posts.html-> path('post/str:pk', views.post, name='post') and they click politics category for instance, I get this error:
ValueError at /post/politics
Field 'id' expected a number but got 'politics'.
Here are my url routes
path('', views.index, name='index'),
path('post/<str:pk>', views.post, name='post'),
path('politicalpost/<str:pk>', views.politicalpost, name='politicalpost'),
path('bizconomicspost/<str:pk>', views.bizconomicspost, name='bizconomicspost'),
path('techpost/<str:pk>', views.techpost, name='techpost'),
path('sportspost/<str:pk>', views.sportspost, name='sportspost'),
path('religionpost/<str:pk>', views.religionpost, name='religionpost'),
path('subscribe', views.subscribe, name ='subscribe'),
path('contactform', views.contactform, name='contactform'),
path('about', views.about, name='about'),
path('guestposting', views.guestposting, name='guestposting'),
path('bizconomics', views.bizconomics, name='bizconomics'),
#These are the caregory urls
path('tech', views.tech, name='tech'),
path('sports', views.sports, name='sports'),
path('politics', views.politics, name='politics'),
path('religion', views.religion, name='religion'),
path('culture', views.culture, name='culture'),
path('culturepost/<str:pk>', views.culturepost, name='culturepost'),
So how can I make it possible such that when a user clicks on the politics category, they are redirected from the posts.html to the politics page->path('politics', views.politics, name='politics'),
My views.py
def index(request):
politics = Politics.objects.all().order_by('-created_at')
posts = Post.objects.all().order_by('-created_at')
trendingposts = Trending.objects.all().order_by('-created_at')
religions = Religion.objects.all().order_by('-created_at')
sliders = Heroslider.objects.all()
return render(request,
'index.html',
{'politics':politics, 'posts':posts,'trendingposts':trendingposts,'religions':religions, 'sliders':sliders})
def politics(request):
politics = Politics.objects.all()
return render(request, 'Politics/politics.html', {'politics':politics})
def post(request, pk):
posts = Post.objects.get(id=pk)
return render(request, 'posts.html', {'posts':posts})
Please try changing it:
<li>Politics</li>
With:
<li>Politics</li>

Getting NoReverseMatch even though url patterns are correct?

I've been learning Django for like a month so apologies if I'm doing something stupid, but, I'm getting a NoReverseMatch Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<use>[^/]+)$'] error when trying to render a "profile" page under the url '/profile/[a user's name]', and I'm pretty sure all my paths/patterns are correct?? Here's my code, could someone help me with this? All my other url patterns work fine. This path also worked fine before, I just renamed the "user" variable into "use" and this happened.
urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("profile/<str:use>", views.profile, name="profile"),
path("following", views.following, name="following"),
#api
path('', include(router.urls)),
]
views.py:
def profile(request, use):
currentuser = str(request.user)
followers = []
following = []
for follow in Follow.objects.filter(following=use):
followers.append(follow.person)
for item in Follow.objects.filter(person=use):
following.append(item.following)
follower_count = len(followers)
following_count = len(following)
try:
Follow.objects.get(person=currentuser, following=use)
followed = True
except:
followed = False
post_list = Post.objects.filter(user=use)
dates = []
for post in post_list:
dates.append(post.timestamp)
dates.sort(key = lambda date: datetime.strptime(date, '%B %d, %Y, %I:%M %p'), reverse=True)
formattedlist = []
for date in dates:
postobject = Post.objects.get(timestamp=date)
formattedlist.append(postobject)
paginatorlist = Paginator(formattedlist, 10)
now_page_content = paginatorlist.page(1)
nowpage = 1
if request.method == "POST":
# Update the database
followbutton = request.POST.get("button")
button = request.POST.get("nav-button")
pagenum = request.POST.get("pg")
if followbutton:
if followbutton == "Follow":
followid = Follow.objects.all().count() + 1
person = currentuser
following = use
newfollow = Follow(followid, person, following)
newfollow.save()
return HttpResponseRedirect(f"/profile/{use}")
else:
deletefollow = Follow.objects.get(person=currentuser, following=use)
deletefollow.delete()
return HttpResponseRedirect(f"/profile/{use}")
else:
currentpage = paginatorlist.page(pagenum)
if button == 'Previous':
if pagenum == '1':
return render(request, "network/profile.html", {
"formattedlist": now_page_content, "currentnumber": nowpage, "message":'No previous page', "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
})
else:
nowpage = int(pagenum)-1
now_page_content = paginatorlist.page(nowpage)
return render(request, "network/profile.html", {
"formattedlist": now_page_content, "currentnumber": nowpage, "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
})
else:
if currentpage.has_next() == False:
return render(request, "network/profile.html", {
"formattedlist": currentpage, "currentnumber": pagenum, "message":'No next page', "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "list": formattedlist, "followed": followed,
})
else:
nowpage = int(pagenum)+1
now_page_content = paginatorlist.page(nowpage)
return render(request, "network/profile.html", {
"formattedlist": now_page_content, "currentnumber": nowpage, "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
})
return render(request, "network/profile.html", {
"use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed, "formattedlist": now_page_content, "currentnumber": nowpage,
})
network/profile.html
{% extends "network/layout.html" %}
{% block body %}
<script src="http://127.0.0.1:8000/static/network/network.js"></script>
<div>
<h2 class="profiletext">{{use}}'s profile page</h2>
{{use}}
{% if message %}
<h6 style="color: red; margin-left: 10px">{{message}}</h6>
{% endif %}
<h5 class="profiletext">Follows: {{follower_count}} // Following: {{following_count}}</h5>
{% if use != currentuser %}
<form method="POST" class="profiletext" action="{% url 'profile' use %}">
{% csrf_token %}
{% if followed == False %}
<input type="submit" value="Follow" name="button">
{% else %}
<input type="submit" value="Unfollow" name="button">
{% endif %}
</form>
{% endif %}
</div>
{% for post in formattedlist %}
<div class="post">
<h5>{{post.use}}</h5>
<h6 style="font-weight: 60" class="edit"><a>Edit</a></h6>
<h4 class="content" style="font-size: 16px;">{{post.content}}</h4>
<h6 style="color: #d3d3d3; font-weight: 50">{{post.timestamp}}</h6>
<h1 class="hidden">{{post.id}}</h1>
{% if user.is_authenticated %}
<img src="https://cdn.shopify.com/s/files/1/0649/0603/products/bigo-0002-GH-8-bit-heart_grande.jpeg?v=1410449344">
<h2 class="likes">TODO</h2>
{% endif %}
</div>
{% endfor %}
<div>
<form class="pagination" method="POST" action="{% url 'profile' use %}">
{% csrf_token %}
<input type="submit" value="Previous" class="page-link" name="nav-button">
<input type="submit" value="Next" class="page-link" name="nav-button" >
<input type="text" value={{currentnumber}} class="pagenumber" name="pg">
</form>
</div>
{% endblock %}
I assume you have not changed user foreignkey from Post model. So, I guess your error is from this line:
<h5>{{post.use}}</h5>
So, it should be like:
<h5>{{ post.user }}</h5>

Django - Template does not show DetailView

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?

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>

Categories