NoReverseMatch 反向“保存后”;带参数 '('',)'未找到。尝试了 1 个模式:['save/(?P[0-9]+)$']
我不明白为什么我总是收到这个“NoReverseMatch at /
”。我正在尝试将 AJAX 添加到表单中以保存帖子。这似乎是 Javascript 中 URL 的问题,但我无法弄清楚它到底是什么。谁能告诉我这里出了什么问题吗?先感谢您。
urls.py
path('', PopularPostListView.as_view(), name='popular'),
path('save/<int:pk>', views.AjaxSave, name='save-post'),
views.py
def AjaxSave(request, pk):
id = int(request.POST.get('postid'))
post = get_object_or_404(Post, id=id)
if request.POST.get('action') == 'post':
result = post.saves.count()
if post.saves.filter(id=request.user.id).exists():
post.saves.remove(request.user)
post.save()
else:
post.saves.add(request.user)
post.save()
return JsonResponse({'result': result, })
#This is the view for the popular page
class PopularPostListView(ListView):
model = Post
template_name = 'blog/popular.html'
context_object_name = 'posts'
ordering = ['-pinned', '-date_posted']
paginate_by = 25
queryset = Post.objects.all().filter(approved=True).order_by('-date_posted', '-pinned')
popular.html
{% extends "blog/base.html" %}
{% block content %}
<h1>Popular Posts</h1>
<div style="margin-left: 10%;">
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="date-text">{{ post.date_posted|date:"F d, Y P" }}</small>
</div>
<h3><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h3>
<p class="article-content-listview">{{ post.content|urlize }}</p>
<!--Display image-->
{% if post.image %}
<img style="max-width: 100%; max-height: 100%;" src="{{ post.image.url }}">
{% else %}
{{ NONE }}
{% endif %}
<!--Display video-->
{% if post.video %}
<video style="max-width: 100%; max-height: 100%;" src="{{ post.video.url }}" controls></video>
{% endif %}
<hr>
<!--Dropdown for post options-->
<div class="post_dropdown_home">
<button class="dropbtn"><i class="fa fa-caret-down fa-2x"></i></button>
<div class="post_dropdown_content">
<div>
<!--Displaying save form-->
<form action="{% url 'save-post' post.id %}" id="save" method="post">
{% csrf_token %}
<button class="savebutton" type="submit" name="post_id" title="Save Post" id="save" value="{{ post.id }}">
<i class="fas fa-bookmark"></i> Save Post
</button>
</form>
</div>
<div>
<!--Displaying report button-->
<form action="{% url 'report_post' post.id %}" method="post">
{% csrf_token %}
{% if user != post.author %}
<button class="reportbutton" type="submit" name="post_id" title="Report Post" value="{{ post.id }}" onclick="reportThank();">
<i class="fas fa-exclamation-circle"></i> Report Post
</button>
{% endif %}
</form>
</div>
</div>
</div>
<div>
<!--Showing report count to staff-->
{% if user.is_staff %}
<small style="margin-left: 0%;">Reports:</small> {{ post.total_reports }}
{% endif %}
</div>
</article>
{% endfor %}
</div>
Javascript
<script>
$(document).on('click', '#save', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: "{% url 'save-post' post.id %}",
data: {
postid: $('#save').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
alert('Post saved!')
},
error: function () {
alert('Error!')
}
});
})
</script>
修复了views.py
I cannot figure out why I keep getting this "NoReverseMatch at /
". I am trying to add AJAX to a form to save posts. It seems to be a problem with the URL in the Javascript, but I cannot figure out exactly what it is. Can anyone tell me what is wrong here? Thank you in advance.
urls.py
path('', PopularPostListView.as_view(), name='popular'),
path('save/<int:pk>', views.AjaxSave, name='save-post'),
views.py
def AjaxSave(request, pk):
id = int(request.POST.get('postid'))
post = get_object_or_404(Post, id=id)
if request.POST.get('action') == 'post':
result = post.saves.count()
if post.saves.filter(id=request.user.id).exists():
post.saves.remove(request.user)
post.save()
else:
post.saves.add(request.user)
post.save()
return JsonResponse({'result': result, })
#This is the view for the popular page
class PopularPostListView(ListView):
model = Post
template_name = 'blog/popular.html'
context_object_name = 'posts'
ordering = ['-pinned', '-date_posted']
paginate_by = 25
queryset = Post.objects.all().filter(approved=True).order_by('-date_posted', '-pinned')
popular.html
{% extends "blog/base.html" %}
{% block content %}
<h1>Popular Posts</h1>
<div style="margin-left: 10%;">
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="date-text">{{ post.date_posted|date:"F d, Y P" }}</small>
</div>
<h3><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h3>
<p class="article-content-listview">{{ post.content|urlize }}</p>
<!--Display image-->
{% if post.image %}
<img style="max-width: 100%; max-height: 100%;" src="{{ post.image.url }}">
{% else %}
{{ NONE }}
{% endif %}
<!--Display video-->
{% if post.video %}
<video style="max-width: 100%; max-height: 100%;" src="{{ post.video.url }}" controls></video>
{% endif %}
<hr>
<!--Dropdown for post options-->
<div class="post_dropdown_home">
<button class="dropbtn"><i class="fa fa-caret-down fa-2x"></i></button>
<div class="post_dropdown_content">
<div>
<!--Displaying save form-->
<form action="{% url 'save-post' post.id %}" id="save" method="post">
{% csrf_token %}
<button class="savebutton" type="submit" name="post_id" title="Save Post" id="save" value="{{ post.id }}">
<i class="fas fa-bookmark"></i> Save Post
</button>
</form>
</div>
<div>
<!--Displaying report button-->
<form action="{% url 'report_post' post.id %}" method="post">
{% csrf_token %}
{% if user != post.author %}
<button class="reportbutton" type="submit" name="post_id" title="Report Post" value="{{ post.id }}" onclick="reportThank();">
<i class="fas fa-exclamation-circle"></i> Report Post
</button>
{% endif %}
</form>
</div>
</div>
</div>
<div>
<!--Showing report count to staff-->
{% if user.is_staff %}
<small style="margin-left: 0%;">Reports:</small> {{ post.total_reports }}
{% endif %}
</div>
</article>
{% endfor %}
</div>
Javascript
<script>
$(document).on('click', '#save', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: "{% url 'save-post' post.id %}",
data: {
postid: $('#save').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
alert('Post saved!')
},
error: function () {
alert('Error!')
}
});
})
</script>
Fixed the views.py
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
错误来自此行
url: "{% url 'save-post' post.id %}",
此处您无权访问您的post
对象,因为它不是内部循环,你可以像这样解决你的问题,如果你使用ajax请求,你没有创建表单并设置要提交的按钮类型,像这样更改你的代码,你的ajax调用将如下所示
Error is comming from this line
url: "{% url 'save-post' post.id %}",
here you don't have access to yourpost
object because it's not inside loop you can solve your problem like this you don't have create form and set your button type to submit if you're using ajax request change your code like thisand you ajax call will look like this
在 Ajaxsave 函数中,您没有指定 pk,您应该将其链接到其中一个对象,然后开始发布帖子,这样视图就无法返回您尝试加载的反向查询,使用 AJAX 请求的最佳实践是使用Django-Rest-Framework 因此它处理所有请求。
in the Ajaxsave function you didnt specifiy the pk you should link it to one of the objects then start making the post so the view couldn't return back the reverse query you are trying to load , the best practices for using AJAX request is by using Django-Rest-Framework so it handle all the requests.