【问题标题】:How to render Django model form drop down manually in the template?如何在模板中手动渲染 Django 模型表单下拉菜单?
【发布时间】:2020-03-19 04:45:41
【问题描述】:

这是我的模型表格

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>

【问题讨论】:

  • 如果你能说出nature是什么类型的外键就更好了。 OneToMany、ManyToMany 还是什么?在这种情况下,我看到您正在尝试访问 nature 作为查询集。所以试试这个:form.nature.all
  • @ToanQuocHo 我已经更新了这个问题。试过form.nature.all。没用。
  • 自然字段值是固定的吗?
  • @ShateelAhmed,那只是一个假设。如果您可以提供模型或与数据架构或模型与nature 字段之间的关系更相关的内容,则可能更容易找到答案

标签: django django-forms


【解决方案1】:

这是有效的

<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>

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 2013-02-25
    • 2015-09-16
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多