Я пытаюсь получить Django-Formset из экземпляра класса формы.
В моем классе формы я добавляю некоторые поля в метод init , потому что форма должнапредложить некоторую гибкость. Поэтому я не могу передать класс в качестве параметра функции formset_factory.
- forms.py
class ConfigForm(forms.Form):
def __init__(self, fields, fields_choices, *args, **kwargs):
super(ConfigForm, self).__init__(*args, **kwargs)
for field in fields:
# instanciate Field from field data
exec(
f'self.fields["{field.name}"] ='
f'forms.{field.field_type.field_type}('
f'required = {field.required},'
f'disabled = {field.disabled},'
f'label = "{field.label}",'
f'initial = "{field.value}",'
f'widget = {field.widget},'
f'help_text = "{field.description}"'
f')'
)
# if field is a ChoiceField add choices to the field instance
if 'ChoiceField' in field.field_type.field_type:
self.fields[field.name].choices = [fields_choices[field.name]]
- views.py ...
form = forms.ConfigForm(active_fields, field_choices)
formset = formset_factory(form, extra=1)
...
Но если я пытаюсь вызвать formset_factory с экземпляром ConfigForm, возникает следующая ошибка:
Internal Server Error: /machines/testconfig/mw0-sap-001/
Traceback (most recent call last):
File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "D:\Users\BKU\maximilianwiederer\OneDrive - Deutsche Bahn\Documents\Programmierung\Eclipse\sap4cloud-dev\machines\views.py", line 83, in get
formset = forms.formset_factory(form, extra=1)
File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\formsets.py", line 441, in formset_factory
return type(form.__name__ + 'FormSet', (formset,), attrs)
AttributeError: 'ConfigForm' object has no attribute '__name__'