【问题标题】:Django-Ajax giving error "Method Not Allowed (POST): /post/like/"Django-Ajax 给出错误“不允许的方法(POST):/post/like/”
【发布时间】:2019-10-22 20:59:54
【问题描述】:

我是 django 新手,我是第一次使用 ajax 和 django。我已经尽力在这里和那里搜索,但我无法找到解决方案

这个答案也没有帮助

Django and ajax request Method Not Allowed (POST)

我得到的错误是

Method Not Allowed (POST): /post/like/
[07/Jun/2019 16:06:16] "POST /post/like/ HTTP/1.1" 405 0

下面是代码

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

阿贾克斯

$(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})

任何帮助将不胜感激!

提前致谢

【问题讨论】:

    标签: python ajax django python-3.x


    【解决方案1】:

    您的“/post/like” URL 与 CategoryListView 的 URL 模式匹配,因为它是“post”加上一个字符串。

    正如您对帖子详细信息视图所做的那样,将类似视图的模式放在 URL 列表的前面,以便它首先匹配。

    【讨论】:

    • 非常感谢它的帮助!但我很困惑,我在 ajax 中使用了 {% url 'like_post' %} 直到现在我认为会在 url.py 中查找名称“like_post”,即 path('post/like/', views.like_post,name ="like_post"),但它怎么会匹配其他一些 url 模式和一些其他名称。
    • 它生成了正确的 URL,但是当您实际访问该 URL 时出现了问题。
    猜你喜欢
    • 1970-01-01
    • 2019-07-05
    • 2019-05-31
    • 2021-12-23
    • 2015-09-19
    • 2017-12-09
    • 2018-03-07
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多