Django:为什么POST网址在Django AJAX中不起作用?

时间:2018-12-27 09:06:29

标签: jquery ajax django url

我正在使用AJAX调用在我的主页(其中有用户可以喜欢的帖子列表)中在Django中创建一个“喜欢”按钮,为了测试“喜欢”按钮的逻辑,我使用了普通的方法(带有页面刷新)来提交表单,并且在我将URL设置为action='{% url "like_post" %}'的地方也可以正常使用。但是,当我使用基于AJAX的表单提交时,我遇到了POST http://127.0.0.1:8000/like/ 404 (Not Found)错误。

template.py:

{% for post in all_posts %}
      <div class="posts" id="post-{{ post.id }}">
        <h2 class="thought-title">{{ post.title }}</h2>
        <p class="content" id="{{ post.id }}" onclick="showWholeContent({{ post.id }})">
          {{ post.content }}
        </p>
        <div class="post-footer">
          <form id="like-form{{ post.id }}">
            {% csrf_token %}
            <button type="submit" id="{{ post.id }}btn" name="like" value="{{ post.id }}" class="btn upvote">Like</button>
            <script type="text/javascript">
              {% for like in post.likes.all %}
                {% if like != user %}

                {% else %}
                  likingPost("{{ post.id }}btn");
                {% endif %}
              {% endfor %}

  // Adding AJAX for Like button
              $(document).ready(function(event){
                $(document).on('click', '#{{ post.id }}btn', function(event){
                  event.preventDefault();
                  $.ajax({
                    type: 'POST',
                    url: '{% url "like_post" %}',
                    data: {
                      csrfmiddlewaretoken: '{{ csrf_token }}'
                    },

                    success:function(response){

                    }
                  });
                });
              });

            </script>
          </form>
                      </div>
      </div>
    {% endfor %}

urls.py:

urlpatterns = [
    path('like/', views.like_post, name="like_post")
    .
    .
    .
]

views.py:

def like_post(request):
print("Insisde Like Post")
post = get_object_or_404(Posts, id=request.POST.get('like'))
if post.likes.filter(id=request.user.id).exists():
    post.likes.remove(request.user)                 # Liking The Post
    print("DisLiking the post")
else:
    post.likes.add(request.user)
    print("Liking the post")
return HttpResponseRedirect('/')

注意:我是AJAX的新手。这是我的第一个项目,其中包括AJAX调用

1 个答案:

答案 0 :(得分:0)

I figured out Solution after some time. And also Thanks to @Chiefir , In views.py I was looking for like, post = get_object_or_404(Posts, id=request.POST.get('like')) Whereas, ajax call does not post any data JSON key like... So In data variable of template.py we just have make following changes...

data = {
    'like' : '{{ post.id }}'
    csrfmiddlewaretoken: '{{ csrf_token }}'
}