如何在Django中呈现单独的choicefield

时间:2016-04-23 01:50:02

标签: python django templates web choicefield

我正在使用Django中的模型,我在模型中有一个选择域,但我不知道在模板中手动渲染,有人可以帮助我吗?

型号:

class Plantonista(models.Model): 
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(max_length=2,
                                      choices=YEAR_IN_SCHOOL_CHOICES,
                                      default=FRESHMAN)

表单:

from django.forms import ModelForm
from plantonista.models import Plantonista

class PlantonistaForm(ModelForm):

    class Meta:
        model = Plantonista
        exclude = ['']

模板:

<div class="mdl-cell mdl-cell--4-col">
    <select class="" name="{{ form.year_in_school.name }}">
        {% for field in form.year_in_school %}
            <option value="{{ field }}"></option>
        {% endfor %}
    </select>
</div>

预览

Preview html

1 个答案:

答案 0 :(得分:0)

只需提供form.field名称

<div class="mdl-cell mdl-cell--4-col">
   <label for = {{ form.year_in_school.name }}>Year In School</label>
   {{ form.year_in_school.name }}
</div>