Customize select widget in template

15 views
Skip to first unread message

Vrooom

unread,
Feb 22, 2014, 6:01:19 AM2/22/14
to django...@googlegroups.com
Hey people,

I need help customizing a "select" widget within the template.

I have a ModelForm and I am building a custom within the template. Looking at the documentation (https://docs.djangoproject.com/en/1.6/topics/forms/) I figured it out pretty quickly. One example:

<div class="form-group">                                                          
    <label for="{{ form.summary.id_for_label }}"                                  
           class="control-label">{{ form.summary.label }}</label>                 
    <input id="{{ form.summary.id_for_label }}" name="{{ form.summary.html_name }}"
           type="text"                                                            
           value="{{ form.summary.value|default_if_none:"" }}"                    
           class="form-control">                                                  
</div>

The next thing really annoys me. There is no documentation on how to customize a select widget.  It took me hours of trial and error to arrive at the point where I have all the necessary information to create this:

<div class="form-group">
    <label for="id_fruit"
           class="control-label">Fruit</label>
    <select class="form-control">
            <option value="">---------</option>
            <option value="1">Apple</option>
            <option value="2">Pear</option>
    </select>
</div>

Now I am stuck at including the "selected" attribute, because somehow "choice.0" is not the same as "form.fruit.value" even though the output is the same.

<pre>                                                 
    {% for choice in form.fruit.field.choices %}       
        {{ choice.0 }} {{ form.fruit.value }}          
        {% if choice.0 == form.fruit.value %}          
            equals                                    
        {% endif %}                                   
    {% endfor %}                                      
</pre>

Output:
2
2 1
2 2

I know that I rather should create a custom Widget, but now that I started this way, I really like to know how to finish it this way.
Reply all
Reply to author
Forward
0 new messages