修改 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 Form 实时从数据库中获取数据

相关文章:

  • 2021-06-24
  • 2021-08-31
  • 2022-01-01
  • 2022-01-16
  • 2021-04-14
  • 2021-09-11
  • 2021-11-11
  • 2021-05-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案