修改 models.py 添加
class UserType(models.Model):
caption = models.CharField(max_length=32)
执行命令,生成数据库
python manage.py makemigrations
python manage.py migrate
修改 forms.py 添加
from app01 import models
class DBForm(DForms.Form):
host = fields.CharField()
host_type = fields.IntegerField(
widget=widgets.Select(choices=[])
)
def __init__(self, *args, **kwargs):
super(DBForm, self).__init__(*args, **kwargs)
self.fields['host_type'].widget.choices = models.UserType.objects.all().values_list('id', 'caption') # 自定义构造方法,实时从数据库中获取数据

本文介绍如何在Django项目中扩展模型和表单,包括创建新的UserType模型类,通过makemigrations和migrate命令更新数据库,以及在forms.py中自定义DBForm表单类,实现实时从数据库获取数据填充下拉选择框。

被折叠的 条评论
为什么被折叠?



