随机渲染表单字段

时间:2013-10-18 09:20:56

标签: python django forms

我对表单中的字段呈现有疑问。我有这段代码:

class RTForm(forms.ModelForm):

    type_options = {
        'error': {
            'label': _('Error'),
        },
        'warning': {
            'label': _('Warning'),
        },
        'off': {
            'label': _('Disable'),
        }
    }

    choice_type = forms.ChoiceField(
        choices=[(k, v['label']) for k, v in type_options.items()],
        required=True, widget=forms.RadioSelect(
            attrs={
                class="choices"
            }
        )
    )

    class Meta:
        model = RT

    def __init__(self, *args, **kwargs):
        self.rt = kwargs.pop('instance', None)

        errors = create_error_list(rt.type)
        warnings = create_warning_list(rt.type)

        super(RTV, self).__init__(*args, **kwargs)

我想做的是在我的模板上有尽可能多的choice_type字段,作为init内列表中返回的错误/警告的数量(每次不同的数字)。那可能吗?我无法找到可能的解决方案。

1 个答案:

答案 0 :(得分:1)

借助您使用typehttp://docs.python.org/2/library/functions.html#type)创建的动态课程,您可以提出的要求

我不确定我是否正确理解了您的问题的业务需求,但是为了创建自定义表单,我会做这样的事情:

choice_type = forms.ChoiceField( # this is your class
   choices=[(k, v['label']) for k, v in type_options.items()],
   required=True, widget=forms.RadioSelect(attrs={
           class="choices"
       })
)

# let's say that I want my custom form to have two choice fields:
formfields = {}
formfields['choice_field1']= choice_type 
formfields['choice_field2']= choice_type 

# Now I can create my custom class
form_class = type('CustomForm', (django.forms.Form,), formfields )

# Finally I will create an instance of my custom class
form = form_class()

# Ok ! form can be used in my view as any normal django form !!