我的 View.py
class AccountCreate(RequestPassingFormViewMixin, MyCreateView):
template_name = 'dashboard/account_form.html'
form_class = AccountForm
model = Account
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(AccountCreate, self).get_form_kwargs(*args, **kwargs)
common = get_object_or_404(Common, pk=self.kwargs['common_pk'])
combination_price = Account(common=common)
kwargs['instance'] = combination_price
return kwargs
def get_success_url(self):
return reverse('dashboard_account_list', kwargs={'chain_pk': self.object.chain.id})
def form_valid(self, form):
self.object = form.save(commit=False)
discount = form.cleaned_data['discount']
account_list = form.cleaned_data['account_list']
self.object.common = get_object_or_404(Common, pk=self.kwargs['common_pk'])
code = Account.get_code(self.object.common, account_list, discount)
self.object.code = code
self.object.save()
form.save_m2m()
return redirect(self.get_success_url())
这是我的form.py文件
class AccountForm(autocomplete_light.ModelForm):
class Meta:
model = Account
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(AccountForm, self).__init__(*args, **kwargs)
common = Common.objects.get(pk=self.request.session.get('common_pk'))
products = Account.objects.filter(chain=chain)
form.fields['discount'].queryset = Discount.objects.filter(product__in=products)
form.fields['account_list'].queryset = AccountList.objects.filter(common=common)
def clean(self):
cleaned_data = super(AccountForm, self).clean()
discount = cleaned_data['discount']
if len(discount) <= 1:
self._errors["discount"] = self.error_class(['Choose at least two discount'])
return cleaned_data
account_list = cleaned_data['account_list']
common = Common.objects.get(pk=self.request.session.get('common_pk'))
code =Account.get_code(common, account_list, discount)
if not self.instance or (self.instance.code != code or self.instance.account_list != account_list):
if Account.objects.filter(code=code, account_list=account_list).exists():
msg1 = 'Already exists'
self._errors["discount"] = self.error_class([msg1])
return cleaned_data
我尝试在我的m2m字段中添加自动建议选项。我在form.py文件中添加了自动完成功能。
但问题是,在表单中添加自动填充后,我面临错误。
答案 0 :(得分:0)
我找到了解决方案,在我的表单中,__init__
方法没有&#39; param&#39;关键字参数,所以我重写了我的form.py之类的东西,添加self.param = kwargs.pop("param")
并且它有效。
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
self.param = kwargs.pop("param")
super(CombinationPriceForm, self).__init__(*args, **kwargs)
chain = Chain.objects.get(pk=self.request.session.get('chain_pk'))
products = Product.objects.filter(chain=chain)
self.fields['variants'].queryset = Variant.objects.filter(product__in=products)
self.fields['price_list'].queryset = PriceList.objects.filter(chain=chain)