Reputation: 48402
I have a EmailField(primary_key=True)
. I'm using a ModelForm
to render a form to a user and on the post back I am calling form.is_valid()
.
I am seeing two types of errors on this field. One is a unique value constraint on the primary key (this email address already exists). The other is an invalid email address error.
I would like to respond differently to each error. Is there an easy way to identify that validation failure was due to an actual input format error vs a unique constraint?
Upvotes: 2
Views: 1479
Reputation: 48402
I figured out how to achieve what I wanted. My goal was to avoid the unique constraint so that I could silently ignore the form submission and succeed (from the user perspective, since their submission was a noop) in the case of a duplicate email address being submitted.
First override the validate_unique
method on my ModelForm
definition.
from django.forms import ModelForm
from apps.announcer.models import Subscriber
class SubscribeForm(ModelForm):
class Meta:
model = Subscriber
exclude = ('created',)
def validate_unique(self):
pass
Because the validate_unique
method has been converted to a noop the view will have to perform whatever validation it needs. So instead of calling form.save()
call entity = form.save(commit=False)
. Perform the needed validation on entity and if needed call entity.save()
.
Upvotes: 5
Reputation: 42805
Could you check for a pre-existing key first, then call is_valid()
?
Upvotes: 1