我有一个只有一个小部件的django表单类。我想给这个小部件命名,如<select name="custom_name"></select>
,但Django获取变量的名称,并将其作为小部件的名称。例如:
class MultiSelectForm(forms.Form):
here_is_the_name_of_the_widget = forms.MultipleChoiceField()
因此上面的代码将创建一个名为:
的小部件 <select name="here_is_the_name_of_the_widget">...</select>
因为我需要对表单进行原型设计,所以我需要在初始化时创建此名称。 直到这一刻,这个表格工作正常,但标准的预先给定名称:
class MultiSelectForm(forms.Form):
multiple_select = forms.MultipleChoiceField()
def __init__(self, attrs=None, choices=(), *args, **kwargs):
self.base_fields['multiple_select'].choices = choices
self.base_fields['multiple_select'].empty_permitted = False
self.base_fields['multiple_select'].required = kwargs.get('required', False)
self.base_fields['multiple_select'].widget = MultiSelect(attrs=attrs, choices=choices)
forms.Form.__init__(self, *args, **kwargs)
所以,我想了一个方法(一个黑客)来实现我想要的但是没有像我预期的那样工作。如果我想要给小部件的名称是“countries”,则会产生以下错误:
KeyError at <project_name>
'countries'
产生该错误的代码是:
class MultiSelectForm(forms.Form):
multiple_select = forms.MultipleChoiceField()
def __init__(self, attrs=None, choices=(), *args, **kwargs):
default_name = 'multiple_select'
name = attrs.get('name', default_name)
if name != default_name:
setattr(self, name, forms.MultipleChoiceField())
del attrs['name']
'''
The error is produced in the following line...
'''
self.base_fields[str(name)].choices = choices
self.base_fields[str(name)].empty_permitted = False
self.base_fields[str(name)].required = kwargs.get('required', False)
self.base_fields[str(name)].widget = MultiSelect(attrs=attrs, choices=choices)
forms.Form.__init__(self, *args, **kwargs)
有没有办法实现这一点,或更好的东西?
谢谢!
感谢@Daniel Roseman
class MultiSelectForm(forms.Form):
def __init__(self, attrs=None, choices=(), *args, **kwargs):
#empty_permitted is a Form's attribute
kwargs['empty_permitted'] = False
forms.Form.__init__(self, *args, **kwargs)
name = attrs.get('name', 'multiple_select')
self.fields[name] = forms.MultipleChoiceField(
choices=choices,
required=kwargs.get('required', False),
widget=MultiSelect(attrs=attrs, choices=choices)
)
答案 0 :(得分:2)
我不确定你为什么要这么做,但你肯定是过于复杂的事情。您可以在实例化时将该字段动态添加到表单中:
class MultiSelectForm(forms.Form):
def __init__(self, *args, **kwargs):
dynamic_field = kwargs.pop('dynamic_field')
super(MultiSelectForm, self).__init__(*args, **kwargs)
self.fields[dynamic_field['name']] = forms.MultipleChoiceField(
choices=dynamic_field['choices'],
empty_permitted=False
required=dynamic_field['required'],
widget=MultiSelect(attrs=dynamic_field['attrs']))
然后在实例化上传递字典:
my_form = MultiSelectForm(
dynamic_field={'name': 'countries', 'choices': (mychoices), 'required': True})