利用type快速生成类

方式一

 MyTestForm = type("MyTestForm",(Form,),{
       'tp1': fields.ChoiceField(label='路宁傻不傻?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect),
       'tp2': fields.ChoiceField(label='路宁傻不傻?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect),
        'tp3': fields.CharField(label='对路宁的建议?',widget=widgets.Textarea),
       'tp4': fields.ChoiceField(label='路宁帽子颜色?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect),
    })

利用type

    question_list = models.Question.objects.filter(naire_id=qn_id)
    field_dict = {}
    for que in question_list:
        if que.tp == 1:
            field_dict['val_%s' % que.id] = fields.ChoiceField(
                label=que.caption,
                error_messages={'required':'必填'},
                widget=widgets.RadioSelect,
                choices=[(i, i) for i in range(1, 11)]
            )
        elif que.tp == 2:
            field_dict['option_id_%s' % que.id] = fields.ChoiceField(
                label=que.caption,
                widget=widgets.RadioSelect,
                choices=models.Option.objects.filter(
                    qs_id=que.id).values_list('id', 'name'))
        else:
            from django.core.exceptions import ValidationError
            from django.core.validators import RegexValidator
            # field_dict['x_%s' % que.id] = fields.CharField(
            #     label=que.caption, widget=widgets.Textarea,validators=[RegexValidator(regex=""),])
            field_dict['content_%s' % que.id] = fields.CharField(
                label=que.caption, widget=widgets.Textarea, validators=[func, ])
    # 类:方式二
    MyTestForm = type("MyTestForm",(Form,), field_dict)
 def __init__(cls, what, bases=None, dict=None): 

typ参数 what 类名,bases继承类,dict类中的字段一可以定义方法

你可能感兴趣的:(利用type快速生成类)