【问题标题】:Django blog.models.Post.DoesNotExist: Post matching query does not existDjango blog.models.Post.DoesNotExist:帖子匹配查询不存在
【发布时间】:2021-02-26 10:32:51
【问题描述】:

我目前正在尝试将 Ajax 添加到我的点赞按钮以防止刷新,我不是 JS 专家。我正在尝试从错误和像这样的小型训练练习中学习,但我收到以下错误:

blog.models.Post.DoesNotExist: Post matching query does not exist.

我不知道这个错误的来源和原因。

这里是views.py

def like_post(request):
    user = request.user

    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        post_obj = Post.objects.get(id=post_id)
        if user in post_obj.liked.all():
            post_obj.liked.remove(user)
        else:
            post_obj.liked.add(user)

        like, created = Like.objects.get_or_create(user=user, post_id=post_id)
        if not created:
            if like.value == 'Like':
                like.value = 'Unlike'
            else:
                like.value = 'Like'
        like.save()
        context = {
            'post_id': post_id,
        }
        if request.is_ajax:
            html = render_to_string('blog/like_section.html',context, request=request)
            return JsonResponse({'form': html})
    return redirect('blog:post-detail', slug=post_obj.slug)

这里是类似section.html的模板

          <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}">
            {% csrf_token %}
            <input type="hidden" name="post_id" value='{{post.id}}'>
            {% if user not in post.liked.all %}
              <button id="like" class="bwhite sm-button" style="color: grey; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;">
                <i class="far fa-thumbs-up" type="submit"></i>
              </button>
            {% else %}
              <button id="like" class="bwhite sm-button" style="color: blue;background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;" >
                <i class="far fa-thumbs-up" type="submit"></i>
              </button>
            {% endif %}
            <div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div>
          </form>

这是脚本

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
        $(document).on('click', '#like', function(event){
          event.preventDefault();
          var pk = $(this).attr('value');
          $.ajax({
            type: 'POST',
            url: '{% url "blog:like-post" %}',
            data: {'post_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>

这里是 post-details.html

        <!-- Like -->
        <div id="like-section">
        {% include 'blog/like_section.html' %}
        </div>
        <!-- Like -->

【问题讨论】:

  • 究竟是在哪一行出现错误?
  • 只是想指出所有的答案都太不一样了,这是怎么回事哈哈
  • 您应该添加调试语句以便下次诊断问题。堆栈跟踪会说明错误发生在哪一行,您可以添加 print() 语句以查看 post_id 不包含您需要的值。然后,您可以在 JavaScript 中添加 console.log() 语句,以查看您是否检索到正确的值以在 POST 中传递。

标签: javascript python jquery django


【解决方案1】:

我来宾 post_obj = Post.objects.get(id=post_id) 导致您的代码异常 (https://docs.djangoproject.com/en/3.1/ref/exceptions/#objectdoesnotexist)。对于建议,有两种解决方案:

# solution 1
try:
    post_obj = Post.objects.get(id=post_id)
except Post.DoesNotExist:
    # do something

# solution 2
post_obj = Post.objects.filter(id=post_id).first()
if not post_obj:
    # do something

对我来说,我更喜欢solution 2,因为它更符合 Pythonic :) 使用 EAFP 原则 (What is the EAFP principle in Python?)

【讨论】:

  • 方案一使用EAFP原则,不是方案二。
  • 这也需要完成,但是关于在 JavaScript 中实际获得正确的 pk 值的另一个答案是使任何事情都正常工作所需要的。
【解决方案2】:

在您的 ajax 函数中,$(this).attr('value') 行引用了 like 按钮不是隐藏的输入。相反,您应该使用 attribute selector:

$(document).on('click', '#like', function(event){
  event.preventDefault();
  const pk = $("input[name=post_id]").val();

  ...

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 2021-06-21
    • 2015-01-28
    • 2022-01-05
    • 2020-10-15
    • 2016-05-11
    • 1970-01-01
    相关资源
    最近更新 更多