user2406467
user2406467

Reputation: 1047

Initial value for Django form field when using custom template

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!

Upvotes: 8

Views: 9437

Answers (2)

Russ McFatter
Russ McFatter

Reputation: 492

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

Upvotes: -1

Akshar Raaj
Akshar Raaj

Reputation: 15211

You can access the initial data of the form field using

{{field.value}}

Upvotes: 12

Related Questions