Creating a IntegrityError for testing purposes

For testing purposes and building my own understanding, I'd like to create a simple Django model and form that can result in a django.db.utils.IntegrityError when saved. Ideally, the error would be null value in column "foo" of relation "bar" violates not-null constraint or similar.

I've tried creating a test model like the following:

class ATestModel(models.Model):
    field = models.BooleanField(null=False)

    def __str__(self):
        return f'<ATestModel(field={self.field})>'

and a test admin form like this:

class ATestForm(forms.ModelForm):
    field = forms.NullBooleanField(label='field')

    def clean(self):
        return
    

@admin.register(ATestModel)
class ATestAdminWithErrors(admin.ModelAdmin):
    form = ATestForm

But the form still validates the model and will give an error on the page:

Please correct the error below.


“None” value must be either True or False.

How can I modify my example to generate a django.db.utils.IntegrityError when saved?

Вернуться на верх