Reputation: 27
I am new in Django so this is very confusing. I have this clean method to raise an error when the input data has the same year with existing data:
class FormSetting(forms.ModelForm):
class Meta:
model = model
fields = '__all__'
def clean_date_year(self):
clean_year = self.cleaned_data.get('effective_date')
year = clean_year.strftime("%Y")
check = model.objects.filter(effective_date__year=year).exists()
if check:
raise forms.ValidationError("The Year Input already here")
return clean_year
But I also use the same page and the same form to make an update, how can I not clean it when I update it?
I am using date field so it was a date picker
<fieldset>
<div class="row">
<div class="col-lg-3">
<label >Effective Date</label>
</div>
<div class="col-lg-9">
{{ form.effective_date.errors}}
{{ form.effective_date }}
</div>
</div>
</fieldset>
Upvotes: 2
Views: 875
Reputation: 512
You should exclude the current instance from your queryset.
Try this:
class FormSetting(forms.ModelForm):
class Meta:
model = model
fields = '__all__'
def clean_date_year(self):
clean_year = self.cleaned_data.get('effective_date')
year = clean_year.strftime("%Y")
check = model.objects.filter(effective_date__year=year)
if self.instance:
check = check.exclude(id=self.instance.id)
if check.exists():
raise forms.ValidationError("The Year Input already here")
return clean_year
Upvotes: 3