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

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([ ...
]

Related

Django - jinja syntax help - how do i pass the value of {{ title }} into the href url args?

so i have this html :
{% extends "encyclopedia/layout.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block body %}
<h1>{{ title }}</h1>
{% autoescape off %}
<p>{{ entry|safe }}</p>
{% endautoescape%}
<br>
<button type="button" name="button">Edit</button>
{% endblock %}
i want the url 'edit' to also get the value of the {{ title}} - instead of 'cat' ..i just used this value to test the rest of the code, but i don`t want to hard code it like that ...
here are my urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("<str:title>", views.title, name="title"),
path("edit/<str:title>", views.edit, name="edit"),
path("error/", views.error, name="error"),
path("new/", views.new, name="new"),
]
this is the code in views.py :
def title(request, title):
entry = util.get_entry(title)
if entry == None:
return redirect("error")
entry_html = md.convert(entry)
return render(request, "encyclopedia/title.html", {
"entry": entry_html
})
def edit(request, title):
if request.method == "POST":
# get the changes from the user
form = EditEntryForm(request.POST)
if form.is_valid():
content = form.cleaned_data["content"]
# save the entry and redirect to the updated page
util.save_entry(title, content)
return redirect("title", title=title)
else:
redirect("edit", title=title)
entry = util.get_entry(title)
form = EditEntryForm(initial={'content': entry})
return render(request, "encyclopedia/edit.html", {
"form": form
})
as i said the code works as intended if i hard code the value of the title ....how do i get {{ title }} in the href url ?
You should just be able to pass it in as:
{% url 'edit' title %}
…or you may need to specify the argument name:
{% url 'edit' title=title %}
See this link in the documentation for more information.

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-Ajax giving error "Method Not Allowed (POST): /post/like/"

I am new to django i am using ajax and django for very first time. I have tried by best to search here and there but i couldn't get to solution
this answer didn't help as well
Django and ajax request Method Not Allowed (POST)
the error i am getting is
Method Not Allowed (POST): /post/like/
[07/Jun/2019 16:06:16] "POST /post/like/ HTTP/1.1" 405 0
below are the codes
likes_section.html
{% if request.user.is_authenticated %}
<form action="{% url 'like_post' %}" method="post">
{% csrf_token %}
{% if is_liked %}
<span class="mr-2" style="color:black;">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}">DisLike</button></span>
{% else %}
<span class="mr-2" style="color:black;">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}">Like</button></span>
{% endif %}
</form>
{% else %}
<span class="mr-2">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}" disabled>Like</button>Please Login to enable Like button</span>
{% endif %}
Ajax
$(document).ready(function(event){
$(document).on('click',"#like_the_post_by_user", function(event){
event.preventDefault();
console.log($("#like_the_post_by_user").val())
console.log("from jquery section")
var pk = $(this).attr('value');
$.ajax({
type : "POST",
url : "{% url 'like_post' %}",
data : {'id': pk , "csrfmiddlewaretoken": '{{ csrf_token }}' },
dataType : 'json',
success : function(response){
$('#like-section_user').html(response['form'])
console.log($('#like-section_user').html(response['form']));
},
error : function(rs, e){
console.log(rs.responseText);
}
});
});
});
urls.py
urlpatterns = [
path('', PostListView.as_view(),name="blog-home"),
path('post/<int:pk>/', PostDetailView.as_view(),name="post-detail"),
path('post/new/', PostCreateView.as_view(),name="post-create"),
path('post/<int:pk>/update/', PostUpdateView.as_view(),name="post-update"),
path('post/<int:pk>/delete/', PostDeleteView.as_view(),name="post-delete"),
path('user/<str:username>/', UserPostListView.as_view(),name="user-posts"),
path('post/<str:category>/', CategoryListView.as_view(),name="category-posts"),
path('about/', AboutListView.as_view(),name="about"),
#path('users/myposts/', ActiveUserPostDetailView.as_view(),name="my-blogs"),
path('feedback-email/', views.feedback_email,name="feedback-email"),
path('post/like/', views.like_post,name="like_post"),
]
views.py
def like_post(request):
#post = get_object_or_404(Post,id=request.POST.get("post_id"))
if request.method == 'POST':
print('method is {}'(request.method))
print("\ninside like view\n")
print("\n in {} \n".format(request.POST.get('id')))
post = get_object_or_404(Post,id=request.POST.get("id"))
is_liked = False
if post.likes.filter(id=request.user.id).exists():
print("\ninside like\n")
post.likes.remove(request.user)
is_liked = False
else:
print("\ninside dislike\n")
post.likes.add(request.user)
is_liked = True
comments = Comment.objects.filter(post=post,reply=None).order_by("-id")
context = {
"post":post,
"is_liked":is_liked,
"comment": comments
}
#return redirect("post-detail",pk=request.POST.get("post_id"))
print("\ngetting in ajax\n")
if request.is_ajax():
print("\ninside ajax\n")
html = render_to_string('blog/likes_section.html', context, request=request)
return JsonResponse({"form":html})
any help will be greatly appreciated !
Thanks in advance
Your "/post/like" URL is matching the URL pattern for CategoryListView, since it is "post" plus a string.
As you have done with the post detail view, bring the pattern for the like view earlier in the list of URLs so that it matches first.

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?

Django NoReverseMatch error

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.

Categories