我有一个只有一个小部件的 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)
所以,我想了一种方法(黑客)来实现我想要的,但没有像我预期的那样工作。如果我想给小部件的名称是“国家”,则会产生以下错误:
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)
)