我不知道如何对我的表单集进行自定义验证。我试图防止用户在同一年选择超过12次,但是在我打印时,cleaned_data作为每种形式的不同字典出现。
我想将所有表格归为一本字典,以检查一年是否出现超过12次,或以更好的方式编写。
我的代码:
表格
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)
最佳答案
设法使其正常工作,完整的工作代码如下:
表格
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 }}
。关于python - Django中表单集的自定义验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46787810/