Django模板中的渲染ChoiceField选项 [英] Render ChoiceField options in Django template
问题描述
在Django中给出 ChoiceField
Given a ChoiceField
in Django
fruits = ChoiceField(label="Fruits", choices=(('A', 'Apple'),
('B', 'Banana'), ('C', 'Cherry')
)
如何在1.9的Django模板中显示表单选项?例如,我尝试了以下操作,但无法显示表单数据:
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>
推荐答案
默认情况下,Django为我们提供了一个简单的下拉列表t作为选择字段的直观表示。只需在您的视图中创建一个表单实例,然后在上下文中传递它即可。这是一个示例,
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,
我们的示例模型为
gender = (
('x', 'Male'),
('y', 'Female'),
)
class User(models.Model):
gender = models.CharField(max_length=60, blank=True, default='',choices=gender,verbose_name="gender")
和我们的模型表单,
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})
,然后使用{{form.my_choice_field}}将其显示在模板中。
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>
这篇关于Django模板中的渲染ChoiceField选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!