Django: Catching Integrity Error and showing a customized message using template

前端 未结 6 2121
梦谈多话
梦谈多话 2020-12-13 03:24

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?

6条回答
  •  Happy的楠姐
    2020-12-13 04:01

    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

提交回复
热议问题