0

I've a custom template to render my form in my Django website. This code renders the ChoiceFields:

<select id="{{ "id_"|add:field.html_name }}"
        class="form-control"
        name="{{ field.html_name }}">
    {% for id, name in field.field.choices %}
        <option value="{{ id }}"
            {% if field.value|default_if_none:"" == id %}
                selected="selected"
            {% endif %}
            >{{ name }}</option>
    {% endfor %}
</select>

This code works perfectly, when the ChoiceField does not have an initial value. If I sumbit the form, but there's an error in the form (sp I get back to my form, and all the data is in there as I submitted it), the correct choice get the selected="selected" attribute, so it works perfectly fine.

But when I set the default value for the form in my Django view (correctly in the form's init() function, like this: self.fields['card_type'].initial = self.card.card_type_id), this stops working.

If I put manually somewhere in my template the form.value variable it displays the correct integer. In the id, name for-loop there's the same id value. These do not have any whitespace ot something else there. But the code does not works, does not equals to true the self.fields['card_type'].initial = self.card.card_type_id condition.

If I modify the previous code, to print the id, and the field.value instead of the {{name}}, like this: ({{id}}-{{ field.value }}), the following HTML code'll be generated:

<select id="id_card_type" class="form-control" name="card_type">
    <option value="3">(3-2)</option>
    <option value="2">(2-2)</option>
    <option value="1">(1-2)</option>
</select>

There's the id, which is 1, 2, and 3! There's the form.value, which is 2! But there isn't any selected="selected"... Why not working?

Thanks!

Nagy Vilmos
  • 1,878
  • 22
  • 46
  • Why are you doing this at all, instead of just using `{{ form.my_field_name }}` which would do it all for you? – Daniel Roseman Jul 18 '14 at 17:52
  • I'd like to add the `class` tag for the ` – Nagy Vilmos Jul 19 '14 at 20:13

0 Answers0