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')
    
    
  • 相关阅读:
    异常处理、网络编程
    内置函数、反射、__str__、__del__、元类
    tomcat 拒绝服务
    html标签
    google 与服务器搭建
    liunx centox ssh 配置
    java 泛型
    Windows Mysql安装
    java 空对象
    java 动态代理(类型信息)
  • 原文地址:https://www.cnblogs.com/longyunfeigu/p/9147736.html
Copyright © 2011-2022 走看看