首页 > 解决方案 > 如何将 javascript 函数的返回值保存在 django 模板变量中?

问题描述

有谁能够帮我?

我正在 django 中做评论功能,但我停止了,因为我不知道该怎么做。

comment.id我的想法是在单击“响应”按钮时为每个评论设置一个变量值,并将其保存到 django 模板变量中,以便在发布答案后访问它。

单击按钮时会显示表单,显示 CSS 类和锚链接。

post.html:

{% for comment in comments %}
  <input class="blog__answer__reply" type="button" name="comment_parent_id" onclick="comment_parent_id=set_comment_parent_id({{ comment.id|escapejs }})" value="RESPONDER">
{% endfor %}

视图.py:

def add_comment(request, post_slug):
  try:
    comment_parent_id = int(request.POST.get('comment_parent_id'))
  except:
    comment_parent_id = None

函数.js:

function set_comment_parent_id(comment_id) {
  return comment_id
}

标签: javascriptdjangoonclick

解决方案


解决了

post.html:

{% for comment in comments %}
  <input class="blog__answer__reply" type="button" name="comment_parent_id" onclick="comment_parent_id=set_comment_parent_id({{ comment.id|escapejs }})" value="RESPONDER">
{% endfor %}

视图.py:

def add_comment(request, post_slug):
  try:
    comment_parent_id = int(request.POST.get('comment_parent_id'))
  except:
    comment_parent_id = None

函数.js:

function set_comment_parent_id(comment_id) {
  return comment_id
}

推荐阅读