2

我对表单中的字段渲染有疑问。我有这个代码:

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)

我想做的是在我的模板上拥有与 init 内列表中返回的错误/警告数量一样多的 choice_type 字段(每次不同的数字)。那可能吗?我想不出一个可能的解决方案。

4

1 回答 1

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 !!
于 2013-10-18T10:28:41.777 回答