Django Form之select自动更新

class InitialForm(DForms.Form):
    username = fields.CharField()
    user_type = fields.IntegerField(
        widget=widgets.Select(choices=models.UserType.objects.all().values_list('id','caption'))
    )

UserType的数据表数据更新,不重启django项目的情况下,看到的结果永远是没更新的
解决方式是重写__init__ 方法

class InitialForm(DForms.Form):
    username = fields.CharField()
    # user_type = fields.IntegerField(
    #     widget=widgets.Select(choices=models.UserType.objects.all().values_list('id','caption'))
    # )
    #
    def __init__(self,*args, **kwargs):
        # 执行父类的构造方法
        super(InitialForm,self).__init__(*args, **kwargs)

        self.fields['user_type'].widget.choices = models.UserType.objects.all().values_list('id','caption')

另一种不推荐使用方式

from django.forms import models as form_model
class InitialForm(DForms.Form):
    username = fields.CharField()
    # to_field_name 决定select option 的value取的是什么值,而且为了显示效果,应该定义UserType的__str__
    # 正因为需要定义__str__, 所以耦合度高,不建议使用
    user_type = form_model.ModelMultipleChoiceField(queryset=models.UserType.objects.all(), to_field_name='caption')

原文地址:https://www.cnblogs.com/longyunfeigu/p/9147736.html