render_to_string 似乎删除了变量的值

render_to_string seems to remove value of an variable

我正在 Django 中创建一个不像按钮,然后我 运行 撞到了墙上。我正在使用 ajax 抓取 ID 和 post 来渲染字符串。第一次点击按钮时一切正常,但 render_to_string 不 return 值 attr。我不知道为什么?

def 我的观点:

def like_post(request):

# post = get_object_or_404(Post, id=request.POST['post_id'])
id = request.POST.get('id')

post = get_object_or_404(Post, id=id)
# check if this user already  
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 = {
    'is_liked': is_liked,
    'value': id,
}

if request.is_ajax():
    html = render_to_string('post/like_section.html', context, request=request)
    return JsonResponse({'form': html})

正在呈现的部分:

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

我的jquery

 $(document).on('click', '#like', function(e) {
    e.preventDefault();
    var id = $(this).attr("value");
    var url = '{% url "like_post" %}';

    $.ajax({
        type: 'POST',
        url: url,
        data: {
            id: id,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        dataType: 'json',
        success: function(response) {

            $('#like-section').html(response['form'])

        },
        error: function(rs, e) {
            console.log(rs.responseText)
        }
    });

});

正在呈现的部分

  <form action='{% url "like_post" %}' method="post">

    {% csrf_token %} {% if is_liked %}

     <button name="post_id" class="likes" id="like" type="submit" value="{{ Post.id }}" like-count="{{ Post.likes.count }}">click 1</button> {% else %}
     <button name="post_id" class="likes" id="like" type="submit" value="{{ Post.id }}" like-count="{{ Post.likes.count }}">click 2</button> {% endif %}

  </form>

{{Post.id}} 未通过 render_to_string 呈现 我得到的结果是:

<form action='/like/' method="post">

    <input type="hidden" name="csrfmiddlewaretoken" value="0isfVRqNKFrDpFjCBi8jdFUgYzaw13YsEdPZV0dwi3SyExUmfOKLZUgFxaDAWhQ1"> 
    <button name="post_id" class="likes" id="like" type="submit" value="" like-count="">click 2</button> 

</form>

似乎变量没有被拾取,如果我硬编码任何数字而不是从数据库中提取,因为 {{ Post.id }} 一切似乎都工作正常。知道我错过了什么吗?

提前致谢

您没有将 Post 传递给上下文,因此模板引擎确实无法呈现它。你应该传递这个,例如:

def like_post(request):
    id = request.POST.get('id')
    post = get_object_or_404(Post, id=id)
    # check if this user already  
    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 = {
        'is_liked': is_liked,
        'value': id,
        <b>'Post': post</b>  # ←  add post to the context
     }
    if request.is_ajax():
        html = render_to_string('post/like_section.html', context, request=request)
    return JsonResponse({'form': html})