Django IntegrityError email is not unique

前端 未结 2 1506
[愿得一人]
[愿得一人] 2021-01-23 19:03

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

2条回答
  •  臣服心动
    2021-01-23 19:39

    The clean_ 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():

提交回复
热议问题