我无法弄清楚如何为我的formset进行自定义验证。我试图阻止用户在同一年选择超过12次,但是当我打印它时,cleaning_data作为每个表单的不同字典进入。
我希望将所有表格分成1个字典,以检查一年是否出现超过12次,或以更好的方式写出来。
我的代码:
forms.py
class SellerResultForm(forms.ModelForm):
class Meta:
model = SellerResult
fields = ('month', 'year', 'result',)
widgets = {
'month': forms.Select(attrs={'class': 'form-control',}),
'year': forms.Select(attrs={'class': 'form-control',}),
'result': forms.TextInput(attrs={'class': 'form-control',}),
}
def has_changed(self): #used for saving data from initial
changed_data = super(SellerResultForm, self).has_changed()
return bool(self.initial or changed_data)
def clean(self):
cleaned_data = super(SellerResultForm, self).clean()
print(cleaned_data)
# prints a set of dictionaries
# {'month': 4, 'year': 2017, 'id': 1, 'result': 1000}
# {'month': 5, 'year': 2017, 'id': 1, 'result': 1000}
# {'month': 6, 'year': 2017, 'id': 1, 'result': 1000}
views.py
def seller_result(request, user_id):
SellerResultFormSet = modelformset_factory(SellerResult, form=SellerResultForm, extra=1, max_num=1)
queryset = SellerResult.objects.filter(seller=user_id,).order_by('year', 'month')
formset = SellerResultFormSet(request.POST or None,
queryset=queryset,
initial=[
{'month': datetime.now().month,
'year': datetime.now().year,
'result': 1000,}])
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.seller_id = user_id
instance.save()
context = {
'formset': formset,
}
return render(request, 'app/seller_result.html', context)
答案 0 :(得分:1)
管理以使其工作,下面的完整工作代码:
forms.py
class SellerResultForm(forms.ModelForm):
class Meta:
model = SellerResult
fields = ('month', 'year', 'result',)
widgets = {
'month': forms.Select(attrs={'class': 'form-control',}),
'year': forms.Select(attrs={'class': 'form-control',}),
'result': forms.TextInput(attrs={'class': 'form-control',}),
}
def has_changed(self): #used for saving data from initial
changed_data = super(SellerResultForm, self).has_changed()
return bool(self.initial or changed_data)
#no clean method here anymore
class BaseSellerResultFormSet(BaseModelFormSet):
def clean(self):
super(BaseSellerResultFormSet, self).clean()
years = []
for form in self.forms:
year = form.cleaned_data['year']
years.append(year)
if years.count(2017) > 12:
raise forms.ValidationError('You selected more than 12 months for 2017')
然后我很难在我的模板中渲染此ValidationError,错误可以在{{ formset.non_form_errors }}
而不是{{ formset.errors }}
中提供,正如我最初预期的那样。
答案 1 :(得分:0)
覆盖formset的clean方法。 self.forms将包含所有表单。