In my django powered app there is only one obvious case where \"IntegrityError\" can arise.
So, how can I catch that error and display a message using templates?
I would validate it with ModelForm. For example:
You got model:
class Manufacturer(models.Model):
name = models.CharField(default='', max_length=40, unique=True)
And ModelForm:
class ManufacturerForm(forms.ModelForm):
def clean(self):
cleaned_data = super(ManufacturerForm, self).clean()
name = cleaned_data.get('name')
if Manufacturer.objects.filter(name=name).exists():
raise forms.ValidationError('Category already exists')
class Meta:
model = Manufacturer
In this case when you submit name that is unique. You'll get validation error before IntegrityError. 'Category already exists' message will be shown in your form in template