Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form.MultipleChoiceField . Customize checkboxes in template

Tags:

forms

django

I have this form:

class PasswordForm(forms.Form):

    CHOICES=[('uppercase','Uppercase'),
            ('lowercase','Lowercase'),
            ('numbers','Numbers'),]

    password_length = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)],)
    options = forms.MultipleChoiceField(
                     widget=forms.CheckboxSelectMultiple, choices=CHOICES,)

How can I customize in template my checkbox fields?
I know how I can do it with other fields, like forms.Charfield() or my password_length, just

<form action="" method="post">
    {{form.some_field}}
</form>

but it doent works with my MultipleChoiceField, I tried many things like
{{form.uppercase}}, {{form.options.choices.uppercase}} and tried {% for %} loop.
it just return nothing, and I dont see it in html via browser inspector.

like image 535
Ivan Semochkin Avatar asked Jan 05 '16 08:01

Ivan Semochkin


Video Answer


2 Answers

 <!-- With for-cycle: -->
{% for field in form %}
  {% for choice_id, choice_label in field.field.choices %}
    {{choice_id}}
    {{choice_label}}
  {% endfor %}
{% endfor %}

<!-- And my end version, where I edited only certain field. -->
{% for field in form %}
  {% if field.name == "your-field-name-here"%}
       <p><strong>{{field.name}}: </strong></p>
       {% for choice_id, choice_label in field.field.choices %}
                <input type="checkbox" name="category" value="{{choice_id}}" style="display:inline;">{{choice_label}}
      {% endfor %}
   {% else %}
       <p>{{ field.errors }}<label style="display:table-cell;">{{field.name}}: </label>{{ field }}</p>
   {% endif %}
{% endfor %}

<!-- If you want to edit all fields with options: {% if field.choices %} -->
like image 84
Varje Avatar answered Sep 21 '22 19:09

Varje


You should write these options as fields of the form:

class PasswordForm(forms.Form):
    uppercase = forms.CharField(widget=forms.CheckboxInput())
    lowercase = forms.CharField(widget=forms.CheckboxInput())
    numbers = forms.CharField(widget=forms.CheckboxInput())
    password_length = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)],)

and then render the form to template, and in template:

{{ form.uppercase }}

will show

<input name="uppercase" type="checkbox">
like image 24
doniyor Avatar answered Sep 20 '22 19:09

doniyor