I am working on my Checkout view with regular/guest user but getting hard time to come around the integrity error. Idea is to let guest users register with email only to checkou
The clean_<fieldname>
methods of a Form
are used to perform validation relative to single field. If you need validation with access to multiple fields, use the clean
method. Check the documentation on form validation for a thorough explanation.
That would give:
class GuestCheckoutForm(forms.Form):
email = forms.EmailField()
email2 = forms.EmailField(label='Verify Email')
def clean_email(self):
email = self.cleaned_data["email"]
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Please confirm emails addresses are the same.")
return email
def clean(self):
cleaned_data = super(GuestCheckoutForm, self).clean()
email = cleaned_data.get('email')
email2 = cleaned_data.get('email2')
if email and email2 and email != email2:
self.add_error('email2', forms.ValidationError('Please confirm emails addresses are the same.'))
EDIT: I believe I found out why you got an IntegrityError
:
You are validation that no User
with the given email is in the database, you should also be validating that no other UserCheckout
with the given email is in the database. Replace if User.objects.filter(email=email).exists():
by if User.objects.filter(email=email).exists() or UserCheckout.objects.filter(email=email).exists():
You create every time when a checkout occurs an new UserCheckout
. And in all these entries it is only allowed that every email exists only once.
I don't think you want this. Because if a guest orders two times it isn't allowed because his email is already in the DB. And that's why you get this error.