[Solved]-Render ChoiceField options in Django template

20👍

By default, Django provides us with a simple drop-down list as a visual representation of the choice field. Just create and an instance of the form in your view, pass it in the context. Here is an example,

let’s say our example model is,

gender = (
    ('x', 'Male'),
    ('y', 'Female'),
    )

class User(models.Model):
      gender = models.CharField(max_length=60, blank=True, default='',choices=gender,verbose_name="gender")

and our model form,

class UserForm(forms.ModelForm):

    def __init__(self, *args, **kargs):
        super(UserForm, self).__init__(*args, **kargs)

    class Meta:
         model = User
         fields = '__all__'

Just create an instance of the form in your view, pass it in the context:

def my_view(request):
    form = UserForm()
    return render_response('template.html',{'form': form})

and then display it in the template using {{ form.my_choice_field }}.

<div class="col-md-4">
    <div class="form-group">
    <label>Gender</label>
    <select name="gender" class="selectpicker" data-title="Select Gender" data-style="btn-default btn-block" data-menu-style="dropdown-blue">
    {% for x,y in form.fields.gender.choices %}
       <option value="{{ x }}"{% if form.fields.gender.value == x %} selected{% endif %}>{{ y }}</option>
    {% endfor %}
    </select>
  </div>  
</div>

Leave a comment