Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render ChoiceField options in Django template

Given a ChoiceField in Django

fruits = ChoiceField(label="Fruits", choices=(('A', 'Apple'),
    ('B', 'Banana'), ('C', 'Cherry')
)

How do I display the form options in Django Templates in 1.9? For example, I tried the following but cannot display the form data:

    <table class="table table-bordered table-condensed">
      <tr>
      <th>
        <label for="{{form.fruits.id_label}}">  
          {{form.fruits.label}}
        </label>
      </th>
      <td>{% for value, displayable in form.fruits.choices %}
            <option value="{{value}}">{{displayable}}</option>
          {% endfor %}
      </td>
      </tr>
    </table>
like image 699
bryan.blackbee Avatar asked Apr 19 '16 16:04

bryan.blackbee


People also ask

What is ChoiceField in Django?

ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.

What is render to string in Django?

render_to_string is a callable within the django. template. loader module of the Django project. get_template and select_template are a couple of other callables within the django. template.

What does {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


1 Answers

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>
like image 136
Emil George James Avatar answered Oct 08 '22 00:10

Emil George James