Django 模型中的下拉菜单 [英] Dropdown in Django Model

查看:47
本文介绍了Django 模型中的下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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.pyForms.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 https://docs.djangoproject.com/en/dev/topics/forms/modelforms/.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆