繁体   English   中英

Django IntegrityError电子邮件不是唯一的

[英]Django IntegrityError email is not unique

我正在与普通/来宾用户一起使用Checkout视图,但是却很难解决完整性错误。 想法是让访客用户仅使用电子邮件注册才能结帐,而我需要将用户电子邮件设置为唯一。

models.py

from django.conf import settings
from django.db import models

class UserCheckout(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
    email = models.EmailField(unique=True)

    def __unicode__(self):
        return self.email

表格

from django import forms
from django.contrib.auth import get_user_model

User=get_user_model()
class GuestCheckoutForm(forms.Form):
    email = forms.EmailField()
    email2 = forms.EmailField(label='Verify Email')
    def clean_email2(self):
        email = self.cleaned_data.get("email")
        email2 = self.cleaned_data.get("email2")
        if email == email2:
            user_exists = User.objects.filter(email=email).count()
            if user_exists != 0:
                raise forms.ValidationError("User already exists. Please login instead")
            return email2
        else:
            raise forms.ValidationError("Please confirm emails addresses are the same.")

在我的购物车视图中,这就是渲染表格的方式。

def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            email = form.cleaned_data.get("email")
            user_checkout = UserCheckout.objects.create(email=email)
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

我已经向admin注册了该模型,在admin中,它可以很好地显示重复的错误,但是从前端出现以下错误:

IntegrityError at /checkout/
column email is not unique
Request Method: POST
Request URL:    http://localhost:8000/checkout/
Django Version: 1.8.13
Exception Type: IntegrityError
Exception Value:    
column email is not unique
Exception Location: C:\Users\Ali\ecomm\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 318
Python Executable:  C:\Users\Ali\ecomm\Scripts\python.EXE
Python Version: 2.7.9

每当结帐发生时,您都会创建一个新的UserCheckout 在所有这些条目中,每封电子邮件只能存在一次。

我不认为你想要这个。 因为如果客人订购两次,则不允许这样做,因为他的电子邮件已经在数据库中。 这就是为什么您会收到此错误。

Formclean_<fieldname>方法用于相对于单个字段执行验证。 如果您需要通过访问多个字段进行验证,请使用clean方法。 查看有关表单验证的文档以获取详细说明。

这将给:

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.'))

编辑:我相信我发现了为什么收到IntegrityError :您正在验证数据库中没有给定电子邮件的User ,您还应该验证数据库中没有其他UserCheckout if User.objects.filter(email=email).exists():替换为if User.objects.filter(email=email).exists(): if User.objects.filter(email=email).exists() or UserCheckout.objects.filter(email=email).exists():

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM