Render ChoiceField options in Django template

寵の児 提交于 2020-03-17 11:02:21

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/36724255/render-choicefield-options-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!