Django 模型中的下拉菜单 [英] Dropdown in Django Model
问题描述
我想在 Django models.py
中创建一个字段,它将呈现为一个下拉列表,用户可以从那里选择选项.
I want to create a field in Django models.py
which will render as a dropdown and user can select the options from there.
如果我有 5 个选择:
If I have 5 choices:
- 绿色
- 蓝色
- 红色
- 橙色
- 黑色
我应该如何在 models.py
和 Forms.py
中编写我的代码,以便模板将其呈现为下拉元素?
How should I write my code in models.py
and Forms.py
so that the template renders it like a dropdown element?
推荐答案
在模型中使用 choices
选项指定 CharField 或 IntegerField https://docs.djangoproject.com/en/dev/ref/models/fields/#choices 并使用 ModelForm
Specify CharField or IntegerField with choices
option in your model https://docs.djangoproject.com/en/dev/ref/models/fields/#choices and use ModelForm https://docs.djangoproject.com/en/dev/topics/forms/modelforms/.
这篇关于Django 模型中的下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!