我想创建一个AbstractEditForm
(继承自ModelForm)表单,从中可以有多个表单从中继承。但是我收到了这个错误:
这是我的forms.py
# This is the abstract form that I want to inherit other forms from
class AbstractEditForms(forms.ModelForm):
def __init__(self, id_fields=None, ref_field=None,
model=None, *args, **kwargs):
self.id_fields = id_fields
self.changed_fields = {}
self.ref_field = ref_field
self.model_ = model
self.ref_id_changed = False
self.check_ref_id()
try:
if 'id_fields' in kwargs.keys():
del kwargs['id_fields']
if 'ref_fields' in kwargs.keys():
del kwargs['ref_fields']
except KeyError as e:
print('Error in AbstractionEditForms :', str(e))
super(AbstractEditForms, self).__init__(*args, **kwargs)
# This is the form that I want to use
class SchemeEditForm(AbstractEditForms):
class Meta:
model = SchemeModel
exclude = ['created_on', 'financial_year']
widgets = {
'as_ref_id': forms.TextInput(attrs={'readonly': 'readonly',
'placeholder': 'Auto Generated '
}),
'admin_sanction_amount': forms.HiddenInput(),
'updated_on': forms.HiddenInput(),
}
views.py
:
def edit_scheme_form_view(request, pk=None):
assert pk is not None, 'pk cannot be None, scheme edit form'
instance = get_object_or_404(SchemeModel, pk=pk)
id_fields = ['technical_authority', 'dept_name', ]
model = SchemeModel
ref_field = "as_ref_id"
if request.method == 'GET':
scheme_form = SchemeEditForm(None, id_fields=id_fields, ref_field="as_ref_id",
model=model, instance=instance)
context = {
'form': scheme_form
}
return render(request, 'Forms/forms/SchemeForm.html', context=context)
if request.method == 'POST':
scheme_form = SchemeEditForm(request.POST, id_fields=id_fields, ref_field="as_ref_id",
model=SchemeModel, instance=instance)
if scheme_form.is_valid():
instance = scheme_form.save()
return generate_success_page(request, instance,"Scheme Edit Success",
"Scheme Details - Edited", nav_dict=None,
util_dict=None)
else:
return render(request, 'Forms/forms/SchemeForm.html', {'form': scheme_form})
错误traceback
:
Internal Server Error: /edit/admin-sanction-form/1/
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\karth\PycharmProjects\phc\edit_forms\views.py", line 17, in edit_scheme_form_view
model=model, instance=instance
TypeError: __init__() got multiple values for argument 'id_fields'
[04/Sep/2016 20:41:08] "GET /edit/admin-sanction-form/1/ HTTP/1.1" 500 63681
我知道这是初始化形式的问题,无论是AbstractEditForm还是SchemeEditForm。
非常感谢任何帮助。
答案 0 :(得分:1)
SchemeEditForm
正在将您传递的第一个位置参数解释为id_fields
参数。当您稍后尝试按名称传递id_fields
时,它认为它正在获得该参数的副本并且您收到错误。
尝试更改__init__()
方法,以便在关键字参数之前接受任意位置参数:
def __init__(self, *args, id_fields=None, ref_field=None, model=None, **kwargs):
我不确定这是否会在您的表单功能方面为您提供所需的结果,但它会消除您所看到的错误。 请注意,此方法不在Python 2.X 中工作,只有Python 3。