NoReverseMatch 反向“保存后”;带参数 '('',)'未找到。尝试了 1 个模式:['save/(?P[0-9]+)$']

发布于 2025-01-15 05:35:54 字数 4146 浏览 0 评论 0原文

我不明白为什么我总是收到这个“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤千羽 2025-01-22 05:35:54

错误来自此行 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>

Error is comming from this line url: "{% url 'save-post' post.id %}", here you don't have access to your post 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 this

<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>

and you ajax call will look like this

<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>
绳情 2025-01-22 05:35:54

在 Ajaxsave 函数中,您没有指定 pk,您应该将其链接到其中一个对象,然后开始发布帖子,这样视图就无法返回您尝试加载的反向查询,使用 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, })

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.

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, })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文