Django Form 实时从数据库中获取数据

匿名 (未验证) 提交于 2019-12-02 22:51:30

修改 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')  # 自定义构造方法,实时从数据库中获取数据 

文章来源: https://www.cnblogs.com/klvchen/p/11239872.html
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!