Skip to content
Advertisement

NoReverseMatch Reverse for ‘save-post’ with arguments ‘(”,)’ not found. 1 pattern(s) tried: [‘save/(?P[0-9]+)$’]

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

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement