重复键值违反唯一约束“auth_user_username_key”DETAIL:键(用户名)=(无)已存在

时间:2017-09-29 23:42:36

标签: python django

我想使用自定义寄存器模型注册用户,但我不断收到以下错误:

  

重复键值违反唯一约束“auth_user_username_key”DETAIL:键(用户名)=(无)已存在

如何解决此错误。

这是我到目前为止创建的代码:

urls.py 中,我为各个页面创建了网址配置。

from django.conf.urls import url
from django.contrib.auth.views import login


from . import views

urlpatterns = [

    url(r'^$', views.nest, name = 'nest'),

    url(r'^login/$', login, {'template_name' : 'Identities/login.html'}, name = 'login'),

    url(r'^register/$', views.register, name = 'register'),
]

forms.py 中,我创建了自定义注册表单。

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

# Create custom user registration


class CreateAccountForm(UserCreationForm):

    email = forms.EmailField(required = True)


    class Meta:

        model = User

        fields = (

            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )

        def save(self, commit = True):
            user = super(CreateAccountForm, 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

views.py 中,我创建了注册视图功能。

from django.shortcuts import render, redirect
from Identities.forms import CreateAccountForm

# Create your views here.

def nest(request):
    return render(request, 'Identities/nest.html')


def register(request):

    if request.method == 'POST':

        form = CreateAccountForm(request.POST)

        if form.is_valid():
            form.save()

        else:
            return redirect(reverse('Identities:logout'))

    else:

        form = CreateAccountForm()
        var = {'form' : form}
        return render(request, 'Identities/create_account.html', var)

1 个答案:

答案 0 :(得分:1)

您需要在表单中加入username。作为唯一字段的Coz 用户名不能在表单中排除。如果您在表单中将其排除,则需要通过为每个用户生成唯一用户名来处理它,这有点单调乏味。

class CreateAccountForm(UserCreationForm):
    email = forms.EmailField(required = True)

    class Meta:
        model = User

        fields = (
             'username'
             'first_name',
             'last_name',
             'email',
             'password1',
             'password2'
        )
   . . . . . .
   . . . . . .