young_minds1
young_minds1

Reputation: 1471

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

Upvotes: 0

Views: 390

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

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.

Upvotes: 1

Related Questions