我無法弄清楚如何爲我的formset進行自定義驗證。我試圖阻止用戶選擇同一年的12次以上,但是當我打印它時,clean_data作爲每種表單的不同字典進來。在Django中爲formset定製驗證
我想將所有的表格分組到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)
請您詳細說明一下嗎?這是我一直試圖做幾個小時沒有運氣 – robtus88