gpt4 book ai didi

python - render_to_string 似乎删除了变量的值

转载 作者:行者123 更新时间:2023-12-04 03:52:06 26 4
gpt4 key购买 nike

我在 Django 中创建了一个不像按钮,但我撞到了墙上。我正在使用 ajax 抓取 id 并发布以呈现为字符串。第一次单击按钮时一切正常,但 render_to_string 不返回值 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})

关于python - render_to_string 似乎删除了变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64296665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com