简体   繁体   English

Django错误:UNIQUE约束失败:auth_user.username

[英]Django error: UNIQUE constraint failed: auth_user.username

I need to register a user by sending an activation token to her Email address. 我需要通过向用户的电子邮件地址发送激活令牌来注册用户。 I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register her using custom built-in functions register and activate . 尝试使用自定义内置函数registeractivate进行注册时,出现此错误(UNIQUE约束失败:auth_user.username)。

My code is as follows: 我的代码如下:

forms.py 表格

class UserRegisterForm(forms.Form, UserCreationForm):

username = forms.CharField(max_length=20)
date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField()

def clean_username(self):
    username = self.cleaned_data.get('username')
    if User.objects.filter(username__iexact=username).exists():
        raise forms.ValidationError('Username already exists')
    return username

def clean_date_of_birth(self):
    '''
    Only accept users aged 13 and above
    '''
    userAge = 13
    dob = self.cleaned_data.get('date_of_birth')
    today = date.today()
    if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
        raise forms.ValidationError('Users must be aged {} years old and above.'.format(userAge))
    return dob

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError('A user has already registered using this email')
    return email

def clean_password2(self):
    '''
    we must ensure that both passwords are identical
    '''
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError('Passwords must match')
    return password2

views.py views.py

def register(request):
if request.method == 'POST':
    form = UserRegisterForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password1')
        new_user = User.objects.create(username=username, email=email, password=password)
        new_user = form.save(commit=False)
        #new_user.set_password(password) # hashes the password
        new_user.is_active = False
        new_user.save()
        current_site = get_current_site(request)
        message = render_to_string('email_activation_link.html', {
            'new_user':new_user,
            'domain':current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
            'token': account_activation_token.make_token(new_user),
        })
        mail_subject = 'Activate your Frac account.'
        #to_email = form.cleaned_data.get('email')
        email = form.cleaned_data.get('email')
        to_email = EmailMessage(mail_subject, message, to=[email])#[to_email])
        to_email.send()
        return render(request, 'register_confirm.html', {'form': form})
else:
    form = UserRegisterForm()

return render(request, 'register.html', {'form': form})

spec_backend = 'django.contrib.auth.backends.ModelBackend'


def activate(request, uidb64, token):
try:
    uid = force_text(urlsafe_base64_decode(uidb64))
    new_user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
    new_user = None
if new_user is not None and account_activation_token.check_token(new_user, token):
    new_user.is_active = True
    new_user.save()
    return render(request, 'register_complete.html', {})
else:
    return render(request, 'registration_incomplete.html', {})

What is causing such an error? 是什么引起这样的错误? I researched similar posts on this platform but each case is unique. 我在此平台上研究了类似的帖子,但每个案例都是唯一的。

You are getting the unique constraint error because you are trying to create the same user twice: 由于尝试两次创建同一用户,因此您获得了唯一约束错误:

new_user = User.objects.create(username=username, email=email, password=password)
new_user = form.save(commit=False)
...
new_user.save()

Since you are using a model form, you don't need to call User.objects.create() manually. 由于您使用的是模型表单,因此无需手动调用User.objects.create() Remove that line. 删除该行。 You can also remove the three lines above that fetch username, email and password from the cleaned data. 您还可以删除从清除的数据中获取用户名,电子邮件和密码的三行内容。

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

相关问题 UNIQUE约束失败:auth_user.username - UNIQUE constraint failed: auth_user.username 如何捕获UNIQUE约束失败:auth_user.username错误? - How to catch UNIQUE constraint failed: auth_user.username error? 如何修复错误 UNIQUE constraint failed: auth_user.username - how to fix error UNIQUE constraint failed: auth_user.username /signup UNIQUE 约束的 IntegrityError 失败:auth_user.username - IntegrityError at /signup UNIQUE constraint failed: auth_user.username Django tests.py django.db.utils.IntegrityError:唯一约束失败:auth_user.username - Django tests.py django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username UNIQUE 约束失败:auth_user.username 尝试在 django 中注册用户时 - UNIQUE constraint failed: auth_user.username while trying to register the user in django django.db.utils.IntegrityError:唯一约束失败:auth_user.username - django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username Django:异常类型:IntegrityError 唯一约束失败:auth_user.username - Django: Exception Type: IntegrityError UNIQUE constraint failed: auth_user.username 唯一约束失败:创建 django 注册表单时的 auth_user.username - UNIQUE constraint failed: auth_user.username when creatin a django sign up form Django自定义用户 - 不使用用户名 - 用户名唯一约束失败 - Django Custom User - Not using username - Username unique constraint failed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM