Python 如何为模板中的django表单字段赋值?

Python 如何为模板中的django表单字段赋值?,python,html,django,Python,Html,Django,我想知道如何为模板中的django表单字段赋值 我知道在django中还有其他方法可以指定初始值,但我需要在模板中指定该值,因为变量只存在于模板中 使用普通html表单执行此操作的方法如下: {% for thing in things %} <p> {{ thing.content }} </p> <!-- Reply form --> <form> <input type="hidden" name="replying

我想知道如何为模板中的django表单字段赋值

我知道在django中还有其他方法可以指定初始值,但我需要在模板中指定该值,因为变量只存在于模板中

使用普通html表单执行此操作的方法如下:

{% for thing in things %}
  <p> {{ thing.content }} </p>
  <!-- Reply form -->
  <form>
    <input type="hidden" name="replyingto" value="{{ thing.number }}">
    <input type="text" label="Reply"></input>
  </form>
{% endfor %}
{%for things in things%}
{{thing.content}

{%endfor%}
但是,我需要使用django表单

我还知道有一种方法可以将标签指定给模板中的字段,如下所示:

{{ form.non_field_errors }}
{{ form.field.errors }}
   <label for="{{ form.field.id_for_label }}"> field </label>
{{ form.field }}
{{form.non_field_errors}
{{form.field.errors}}
领域
{{form.field}
所以我的问题基本上是你将如何进行上面的例子,但不是分配一个标签,而是分配一个值


我找到了解决办法

我所做的是按照建议手动键入html并以这种方式分配值


对于任何想知道我是如何做到这一点的人,这里有一个。

您可以用Python来完成,然后可以在HTML表单或生成器中使用它

forms.py
中,可以设置
initial
属性来定义字段的默认值

例如:
name=forms.CharField(initial='class')

或者在
views.py中动态地使用
dict

例如:
f=CommentForm(首字母={'name':'instance'})

一旦在
表单
实例中可用,就可以使用
{{{form.field.value}
在HTML中或使用生成器自动创建


扩展参考:

您可以逐个字段手动渲染表单,但随后使用Django模板插值渲染所有其他字段,但您可以手动渲染隐藏字段。e、 g

{% for thing in things %}
  <p> {{ thing.content }} </p>
  <!-- Reply form -->
  <form FORM_PARAMS_HERE >
    <div class="form-row">
        {{ form.other_form_field.errors }}
        {{ form.other_form_field.label_tag }} {{ form.other_form_field }}
    </div>
    ... (more form rows)
    <div class="form-row">
        <input type="hidden" name="replyingto" id="replyingto_id" value="{{ thing.number }}">
        <input type="text" label="Reply"></input>
    </div>
  </form>
{% endfor %}
{%for things in things%}
{{thing.content}

{{form.other_form_field.errors} {{form.other_form_field.label_tag}{{form.other_form_field} ... (更多表格行) {%endfor%}

我遇到了这个确切的问题,在找到它之后,我终于能够按照我认为您想要的方式解决它。

我不明白您的代码有什么问题。手动创建HTML不会阻止您在视图中使用Django表单。抱歉,我不明白。我可以使用html表单而不是django表单来解析视图中的值吗?如果你愿意,但你说你想使用django表单。如果有办法解析普通html表单中的值,我真的不需要django表单。如果有办法的话,我的问题是你会怎么做。你能为这个页面添加views.py和forms.py代码吗?我相信在代码中有更好的方法来实现这一点。