zoukankan      html  css  js  c++  java
  • 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')
    
    
  • 相关阅读:
    HDU
    HDU
    CodeForces
    HDU——2955 Robberies (0-1背包)
    南京区域赛之后
    算法作业三-哈夫曼编码
    HDU
    POJ 1220 NUMBER BASE CONVERSION(进制转换,大数)
    HDU 1535 Invitation Cards(最短路)
    HDU 3572 Task Schedule(网络流+当前弧优化)
  • 原文地址:https://www.cnblogs.com/longyunfeigu/p/9147736.html
Copyright © 2011-2022 走看看