NoReverseMatch 对 'save-post' 的反向匹配,未找到参数“(”,)“。尝试了 1 种模式:['save/(?P<pk>[0-9]+)$']
NoReverseMatch Reverse for 'save-post' with arguments '('',)' not found. 1 pattern(s) tried: ['save/(?P<pk>[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
在 Ajaxsave 函数中你没有指定 pk 你应该 link 它到一个对象然后开始制作 post 所以视图不能 return 反向您尝试加载的查询,使用 AJAX 请求的最佳做法是使用 Django-Rest-Framework 以便它处理所有请求。
def AjaxSave(request, pk):
pk = module.objects.get(pk=pk)
if request.method == "POST":
# or you can get the pk here if you want without parsing to int
id = int(request.POST.get('postid'))
result = post.saves.count()
post = get_object_or_404(Post, id=id)
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, })
错误来自这一行 url: "{% url 'save-post' post.id %}",
这里您无权访问您的 post
对象,因为它不在循环内 您可以像这样解决您的问题,您没有创建表单如果您正在使用 ajax 请求,请将您的按钮类型设置为提交 像这样更改您的代码
<button class="savebutton" type="button" name="post_id" title="Save Post" id="save" onclick="savePost(event)" value="{{ post.id }}" data-url="{% url 'save-post' post.id %}">
<i class="fas fa-bookmark"></i> Save Post
</button>
你 ajax 通话将如下所示
<script>
function savePost(event){
var url = event.target.getAttribute("data-url");
$.ajax({
type: 'POST',
url: url,
data: {
postid: event.target.getAttribute('value'),
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
alert('Post saved!')
},
error: function () {
alert('Error!')
}
});
}
</script>
我不明白为什么我总是收到这个“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
在 Ajaxsave 函数中你没有指定 pk 你应该 link 它到一个对象然后开始制作 post 所以视图不能 return 反向您尝试加载的查询,使用 AJAX 请求的最佳做法是使用 Django-Rest-Framework 以便它处理所有请求。
def AjaxSave(request, pk):
pk = module.objects.get(pk=pk)
if request.method == "POST":
# or you can get the pk here if you want without parsing to int
id = int(request.POST.get('postid'))
result = post.saves.count()
post = get_object_or_404(Post, id=id)
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, })
错误来自这一行 url: "{% url 'save-post' post.id %}",
这里您无权访问您的 post
对象,因为它不在循环内 您可以像这样解决您的问题,您没有创建表单如果您正在使用 ajax 请求,请将您的按钮类型设置为提交 像这样更改您的代码
<button class="savebutton" type="button" name="post_id" title="Save Post" id="save" onclick="savePost(event)" value="{{ post.id }}" data-url="{% url 'save-post' post.id %}">
<i class="fas fa-bookmark"></i> Save Post
</button>
你 ajax 通话将如下所示
<script>
function savePost(event){
var url = event.target.getAttribute("data-url");
$.ajax({
type: 'POST',
url: url,
data: {
postid: event.target.getAttribute('value'),
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
alert('Post saved!')
},
error: function () {
alert('Error!')
}
});
}
</script>