问题描述
我正在使用常规/访客用户的Google Checkout视图进行工作,但是遇到完整性错误时需要花费很多时间。想法是让访客使用电子邮件注册才能结帐,我需要设置用户邮箱的唯一性。
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 checkout and I need to set the user email unique.
models.py
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
forms.py
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.")
在我的购物车视图中,我是如何呈现我的表单。
In my cart views this is how I've rendered my form.
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)
我已经注册了管理员和管理员显示重复的错误非常好,但从前端我得到以下错误:
I've registered the model with admin and in admin it shows the error for duplication perfectly fine but from frontend I am getting error below:
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
。在所有这些条目中,只允许每个电子邮件只存在一次。
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.
这篇关于Django IntegrityError电子邮件不是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!