使用自定义模板时Django表单字段的初始值

use*_*467 4 django django-forms django-crispy-forms

我的Django表单中有一个BooleanField,我希望初始值为True,所以我将其定义为:

my_checkbox = forms.BooleanField(label='My Checkbox', help_text='Some help text here', initial=True)
Run Code Online (Sandbox Code Playgroud)

在我的帮手中,我有:

helper.layout = Layout(
    Field('my_checkbox', template="custom.html")
Run Code Online (Sandbox Code Playgroud)

Custom.html看起来像:

<input class="checkboxinput" id="id_{{ field.name }}" name="{{ field.name }}" type="checkbox">
<span id="hint_id_{{ field.name }}" class="help-inline">{{ field.help_text }}</span>
Run Code Online (Sandbox Code Playgroud)

我尝试输出field.initial的值,但没有显示任何内容.我知道如果我手动编码,我会放<input ... checked>,并检查框.

有没有办法访问该字段的"初始"部分并将其设置在我的自定义模板中?谢谢!

Aks*_*aaj 8

您可以使用以下方式访问表单字段的初始数据

{{field.value}}
Run Code Online (Sandbox Code Playgroud)

  • 如果用户尚未选择值(表单未绑定),这似乎不起作用. (3认同)
  • 实际上它有效。如果像我一样,您将表单对象传递给模板,则需要使用“{{ form.field.value}}”,而不是“{{ form.data.field.value }}”或“{{ form.value”。 clean_data.field.value }}`。 (2认同)