【问题标题】:render_to_string seems to remove value of an variablerender_to_string 似乎删除了变量的值
【发布时间】:2021-01-25 12:23:19
【问题描述】:

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

提前致谢

【问题讨论】:

    标签: python django django-views django-templates render-to-string


    【解决方案1】:

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

    【讨论】:

    • 即使我这样做了看起来我得到了同样的错误。它传递了值,但是在 render_to_string 之后它不起作用
    • @Dula:你是把它传递为Post还是post,注意变量是区分大小写的。所以如果你用{{ Post.id }}渲染它,你应该把它传递为'Post' : post
    • @Williem Van Onsem:我这样做: context = { 'is_liked': is_liked, 'value': id, 'Post': post } 我的构建是这样的:post = get_object_or_404(PostJoke, id=id)
    • 我明白了。就是这样,非常感谢。我的变量名在上下文中是错误的
    • @Williem Van Onsem:好的,所以我现在的问题是,如果我在 lis(for 循环)上的任何帖子上点击一个赞,它会更新所有帖子。我猜是我的 jquery 目标 ...hm...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 2022-01-04
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多