Django 在使用 FormSet 时无法将请求传递给 Form。生成"__init__() 得到意外的关键字参数"请求"


#forms.py
class RequestModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(RequestModelForm, self).__init__(*args, **kwargs)
class BusinessForm(RequestModelForm):
class Meta:
model = Business
fields = ('title', 'stitle', 'gstin', 'address')
def clean_gstin(self):
user = self.request.user
gstin = self.cleaned_data['gstin'].upper()
if Business.objects.filter(owner=user, gstin=gstin).exists():
raise  ValidationError("A Business with that GSTIN already exists")
return gstin

#views.py
class BaseFormView(FormView):
def get_form_kwargs(self):
kwargs = super(BaseFormView, self).get_form_kwargs()
kwargs['request'] = self.request
return kwargs
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.save()
return super(BaseFormView, self).form_valid(form)
class Meta:
abstract = True

class BusinessCreateView(BaseFormView):
BusinessFormSet = formset_factory(BusinessForm, extra=3)
form_class = BusinessFormSet
success_url = '/dashboard'
template_name = "business/business_create_form.html"

如果我为formset_factory设置extra=1,一切正常.但是当extra = 2或大于 1 时,会抛出错误:__init__() got an unexpected keyword argument 'request'

我已经在这里确定了问题。由于我在RequestModelForm__init__函数中弹出request(当 extra 设置为 1 以上时会多次调用(。而且没有request,因为它已经被弹出了。

我尝试做self.request = kwargs.get("request")而不是self.request = kwargs.pop("request").但这抛出了另一个错误 'BusinessForm' object has no attribute 'request'.

如何克服这个问题?有什么帮助吗?

您需要将额外的 kwargrequest传递给表单,但BusinessFormSet需要明确包含此信息。在 FormView 中覆盖get_form_kwargs方法不会按照您描述的方式工作,因为它会将所有这些作为 kwarg 传递给您定义为form_class的内容。

见 https://docs.djangoproject.com/en/2.1/topics/forms/formsets/#passing-custom-parameters-to-formset-forms

例如,可能有效的是:

class BaseFormView(FormView):
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['form_kwargs'] = {'request': self.request}
return kwargs
...

相关内容

  • 没有找到相关文章

最新更新