zoukankan      html  css  js  c++  java
  • 动态修改modelform Meta

    需求:模型对象某些字段是自己生成而非前台传过来,因此新建的时候modelform需要验证这些字段必填,但是编辑的时候不需要

    本来想直接修改Meta中exclude,像这样:

    class AuthorForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(AuthorForm, self).__init__(*args, **kwargs)
            if kwargs.get('instance'):
                if not hasattr(self.__class__.Meta, 'exclude'):
                    self.__class__.Meta.exclude = []
                self.__class__.Meta.exclude.append('name')
    

     但是并不生效,应该是创建类的时候使用元类将exclude中的字段在fields中排除了,最后使用如下方法

    def add_exclude_field(*ex_field):
        def outer(class_obj):
            def __init__(self, *args, **kwargs):
                super(class_obj, self).__init__(*args, **kwargs)
                if kwargs.get('instance'):
                    for field in ex_field:
                        del self.fields[field]
            class_obj.__init__ = __init__
            return class_obj
        return outer
    
    
    @add_exclude_field('name')
    class AuthorForm(forms.ModelForm):
        ......
    

      

  • 相关阅读:
    获取comboBox里面的item使用的方法
    QT格式化代码
    按键槽的写法
    int to String
    sprintf在51单片机中的使用
    学习使用MarkDown
    分享9款超酷的jQuery/CSS3插件
    2014年展望
    操作系统面试
    web一点小结
  • 原文地址:https://www.cnblogs.com/songbird/p/8109729.html
Copyright © 2011-2022 走看看