Django Form acquire real-time data from the database

Add modify models.py

class UserType(models.Model):
    caption = models.CharField(max_length=32)

Execute commands, generate a database

python manage.py makemigrations
python manage.py migrate

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

Guess you like

Origin www.cnblogs.com/klvchen/p/11239872.html