1👍
✅
You can use your existing method, but check first whether self.instance
and self.instance.pk
are not None.
0👍
def clean_tag_number(self):
tag_number = self.cleaned_data['tag_number']
qs = self.Meta.model.objects.filter(tag_number=tag_number)
if self.instance:
qs = qs.exclude(pk=self.instance.id)
if qs.count() > 0:
raise forms.ValidationError('You already have a calculation based on that tag number, please choose another.')
return tag_number
0👍
Thanks for the posts and elaborating on Daniels answer below I have the following working code.
def clean_tag_number(self):
tag_number = self.cleaned_data['tag_number']
if self.instance and self.instance.pk == None:
try:
Calc.objects.get(tag_number = tag_number)
except Calc.DoesNotExist:
return tag_number
except Calc.MultipleObjectsReturned:
raise forms.ValidationError("You already have a calculation based on that tag number, please choose another.")
raise forms.ValidationError("You already have a calculation based on that tag number, please choose another.")
else:
return tag_number
This is the first time Ive written any validation so please feel free to point out any issues.
👤Karl
- [Answer]-Django QuerySet to return unique objects in ManyToMany fields
- [Answer]-Converting time string to TimeField
- [Answer]-Django admin reverse TabularInline
Source:stackexchange.com