Python 渲染形式场随机时间
我有一个关于表单中的字段渲染的问题。我有以下代码:Python 渲染形式场随机时间,python,django,forms,Python,Django,Forms,我有一个关于表单中的字段渲染的问题。我有以下代码: class RTForm(forms.ModelForm): type_options = { 'error': { 'label': _('Error'), }, 'warning': { 'label': _('Warning'), }, 'off': { 'label': _('
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_类型字段,就像init中列表中返回的错误/警告的数量一样(每次都有不同的数量)。可能吗?我想不出一个可能的解决方案。在您自己创建的动态类的帮助下,您所要求的将成为可能 我不确定我是否正确理解了您的问题的业务需求,但是为了创建自定义表单,我会这样做:
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 !!
你考虑过使用吗?