【问题标题】:Not Found url in django class based view with ajax使用 ajax 在基于 django 类的视图中未找到 url
【发布时间】:2019-06-13 09:54:21
【问题描述】:

我对“喜欢”功能有疑问。我想让喜欢这篇文章成为可能,而不会使整个页面超载。所以我用 CBV django 连接到 ajax。

我的问题是它收到:Not Found: /like/ 按“赞”按钮。

我的看法:

class PostLikeView(generic.View):
    def post(self, request):

        post = get_object_or_404(Post, id=request.POST.get('id'))
        is_liked = False
        if post.likes.filter(id=request.user.id).exists():
            post.likes.remove(request.user)
            is_liked = False
        else:
            post.likes.add(request.user)
            is_liked = True
        context = {
            'post': post,
            'is_liked': is_liked,
            'total_likes': post.total_likes(),
            }
        if request.is_ajax():
            html = render_to_string('post/like_section.html', context, request=request)
            return JsonResponse({'form': html})

下面是jquery代码:

        <script type="text/javascript">
            $(document).ready(function(event){
                $(document).on('click', '#like', function(event){
                    event.preventDefault;
                    var pk = $(this).attr('value');
                    $.ajax({
                        type: 'POST',
                        url: "{% url 'post:post_like' %}",
                        data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                        dataType: 'json',
                        success: function(response){
                            $('#like-section').html(response['form'])
                            console.log($('#like-section').html(response['form']))
                        },
                        error: function(rs, e){
                            console.log(rs.responseText);
                        },
                    });
                });
            });
        </script>

查看网址:

url(r'^like/$', login_required(PostLikeView.as_view()), name='post_like'),

html 中的代码:

<form action="{% url 'post:post_like' %}" method="post">
    {% csrf_token %}
    {% if is_liked %}
        <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button>
    {% else %}
        <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button>
    {% endif %}
</form>

我希望按钮按照不重新加载整个页面的原则工作。

【问题讨论】:

    标签: python jquery json ajax django


    【解决方案1】:

    我认为的问题是您实际上没有在单击事件处理程序中调用 event.preventDefault(您缺少括号)。这意味着提交按钮提交表单,但表单不包含名为 id 的参数,因此 get_object_or_404(Post, id=request.POST.get('id')) 引发 404。

    将缺少的括号添加到event.preventDefault,同时注意HTML元素上id=属性的值应该是unique within the page。更改&lt;button&gt; 元素上id= 属性的值,使它们是唯一的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 2014-02-16
      相关资源
      最近更新 更多