首页 > 解决方案 > render_to_string 似乎删除了变量的值

问题描述

我在 Django 中创建了一个不同的按钮,我撞到了墙上。我正在使用 ajax 抓取 id 并发布以呈现到字符串。当第一次单击按钮时,一切都很好,但 render_to_string 不返回值 attr。我不知道为什么?

在我的观点中定义:

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 }}一切似乎都工作正常。知道我缺少什么吗?

提前致谢

标签: pythondjangodjango-viewsdjango-templatesrender-to-string

解决方案


您没有传递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,
        'Post': post  # ←  add post to the context
     }
    if request.is_ajax():
        html = render_to_string('post/like_section.html', context, request=request)
    return JsonResponse({'form': html})

推荐阅读