Given a view that creates an object from a model that has a 'unique_together' for two fields using the following code:
    def form_valid(self, form):
        field1 = form.cleaned_data['field1']
        field2 = form.cleaned_data['field2']
        try:
            TheModel.objects.create(org=self.request.org, field1=field1, field2=field2)
        except IntegrityError as e:
            if 'UNIQUE constraint' in e.message:
                messages.error(self.request, _('field1 already exists.'))
            return super(ModelFormMixin, self).form_valid(form)
        messages.success(self.request, _('Fields have been successfully updated.'))
        return super(ModelFormMixin, self).form_valid(form)
How might I unit test that the error message gets displayed when the 'unique_together' throws an error?
My current test throws a TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
Here is the current test:
    @patch.object(messages, 'error')
    def test_error_handling(self, error_mock):
        TheModel.objects.create(org=self.org, field1='somepath', field2='anotherpath2')
        with transaction.atomic():
            response = self.client.post(reverse('configurations.create_amodel', args=(self.org.slug,)),
                {'field1': 'somepath', 'field2': 'anotherpath'}, follow=True)
            self.assertTrue(error_mock.called)
I cannot figure out how to make the test work (testing the code that is run when the exception is caught)
Here's my form class:
class RedirectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    super(RedirectForm, self).__init__(*args, **kwargs)
field1 = forms.CharField(label='field1', required=True)
field2 = forms.CharField(label='field2', required=True)
class Meta:
    model = TheModel
    fields = ('field1', 'field2')
 
    