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

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

duplicate key value violates unique constraint “auth_user_username_key” DETAIL: Key (username)=(None) already exists

我该如何解决这个错误.

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

在urls.py中,我为各个页面创建了url配置.

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)

最佳答案 您需要在表单中包含用户名. Coz用户名是唯一字段,不能在表单中排除.如果你在表单中排除它,你需要通过为每个用户生成唯一的用户名来处理它,这有点单调乏味.

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

    class Meta:
        model = User

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