我正在使用常规/来宾用户处理我的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
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.")
在我的购物车视图中,这是我呈现表单的方式。
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
答案 0 :(得分:2)
每次结帐时都会创建新的UserCheckout
。在所有这些条目中,只允许每封电子邮件只存在一次。
我不认为你想要这个。因为如果客人订购了两次,则不允许,因为他的电子邮件已经在数据库中。这就是你得到这个错误的原因。
答案 1 :(得分:1)
clean_<fieldname>
的{{1}}方法用于执行相对于单个字段的验证。如果您需要访问多个字段的验证,请使用Form
方法。有关详细说明,请查看表单验证documentation。
这会给:
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():