Django auth.user具有独特的电子邮件 [英] Django auth.user with unique email
本文介绍了Django auth.user具有独特的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用django.auth系统,我这样做:
I use the django.auth system and I've this:
class RegisterForm(UserCreationForm):
username = forms.RegexField(label= "Username" , max_length = 30, regex = r'^[\w]+$', error_messages = {'invalid': "This value may contain only letters, numbers and _ characters."})
email = forms.EmailField(label = "Email")
first_name = forms.CharField(label = "First name", required = False)
last_name = forms.CharField(label = "Last name", required = False)
class Meta:
model = User
fields = ("username", "first_name", "last_name", "email", )
def save(self, commit = True):
user = super(RegisterForm, self).save(commit = False)
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
我想将电子邮件设置为独家,并检查此验证的表单。我该怎么做?
I want to set emails as uniques and check the form for this validation. How can I do it?
推荐答案
将此添加到您的表单中。但这不是完美的方式。竞争条件只能使用这种形式。我建议您在db级别添加唯一的约束。
add this to your form. But this isn't perfect way. race condition is available by only using this form. I recommend you to add unique constraint at db level.
def clean_email(self):
data = self.cleaned_data['email']
if User.objects.filter(email=data).exists():
raise forms.ValidationError("This email already used")
return data
SQL添加唯一约束:
SQL to add unique constraint:
ALTER TABLE auth_user ADD UNIQUE (email)
这篇关于Django auth.user具有独特的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文