I have a simple model:
class InvitationRequest(models.Model):
email = models.EmailField(max_length=255, unique=True)
<
I agree with Tomasz Zielinski that common practice is to not worry about this. For most use cases it's just not worth the trouble.
If it is important, the best way is probably with optimistic concurrency. In this case it might look like (untested):
from django.forms.util import ErrorList
def handle_form(request)
form = InvitationRequestForm(request.POST)
try:
if form.is_valid():
form.save()
return HttpResponseRedirect(...) # redirect to success url
except IntegrityError:
form._errors['email'] = ErrorList()
form._errors['email'].append('Error msg')
return render(...) # re-render the form with errors
SERIALIZABLE
won't really help here. As the PostgreSQL documentation makes clear, you have to be prepared to handle serialization failures, which means that the code would look pretty much the same as above. (It would help, though, if you didn't have the unique
constraint forcing the database to throw an exception.)