Question

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!

Was it helpful?

Solution

You can access the initial data of the form field using

{{field.value}}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top