Saturday, February 22, 2014

Customize select widget in template

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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8f9cd469-6077-4382-95ee-b73b4036fdd3%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment