这是我的模特表格
class CategoryCreateForm(forms.ModelForm):
class Meta:
model = Category
fields = [
'nature',
'name',
'description',
]
字段nature
是一对多的外国字段(可能有许多相同性质的类别)。我知道我可以使用{{ form.nature }}
在模板中呈现此字段,但是我想在没有Django或脆皮表单的帮助下手动呈现表单。我设法对其他字段执行了此操作,但是不知道如何对模型表单的select
字段执行此操作。我正在寻找与以下类似的解决方案
<select class="custom-select custom-select-sm{% if form.nature.errors %} is-invalid{% endif %}" id="{{ form.nature.id_for_label }}" name="{{ form.nature.html_name }}">
{% for nature in form.nature.objects %}
<option value="{{ nature.id }}">{{ nature.name }}</option>
{% endfor %}
</select>
答案 0 :(得分:0)
这是有效的
<select class="custom-select custom-select-sm{% if form.nature.errors %} is-invalid{% endif %}" id="{{ form.nature.id_for_label }}" name="{{ form.nature.html_name }}">
{% for id, name in form.fields.nature.choices %}
<option value="{{ id }}">{{ name }}</option>
{% endfor %}
</select>