문제

There is a BooleanField in my Django form that I would like to have an initial value of True, so I defined it as:

my_checkbox = forms.BooleanField(label='My Checkbox', help_text='Some help text here', initial=True)

In my helper, I have:

helper.layout = Layout(
    Field('my_checkbox', template="custom.html")

Custom.html looks like:

<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>

I tried outputting the value of field.initial, but nothing shows up. I know that if I were coding this manually, I would just put <input ... checked>, and the box would be checked.

Is there some way to access the "initial" part of the field and set it in my custom template? Thanks!

도움이 되었습니까?

해결책

You can access the initial data of the form field using

{{field.value}}

다른 팁

It really is {{ field.initial }} on unbound forms. To manually render the form's initial value on a radio button, for example:

{% for value, descr in field.choices %}
  <input type="radio" name="{{ field.html_hame }}" value="{{ value }}"{% if field.initial == value %} checked{% endif %}>{{ descr }}<br>
{% endfor %}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top