Django自定义用户表单:错误:唯一约束失败:auth_user.username

时间:2018-07-25 16:06:10

标签: python django django-forms django-users

我正在将Django(2.0.7)UserCreationForm与三个额外的字段一起使用-first_name,last_name和email。当我注册新用户时(虽然已创建用户),在终端窗口中出现以下错误。

return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: auth_user.username


return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username

我的forms.py是

class SignupForm(UserCreationForm):
    alphabetic = RegexValidator(r'^[a-zA-Z]+$')
    email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput(attrs={'placeholder': 'Email Address', }))
    first_name = forms.CharField(max_length=254, required=True, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'style': 'text-transform:capitalize'}),
                                 validators=[alphabetic])
    last_name = forms.CharField(max_length=254, required=True, widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'style': 'text-transform:capitalize'}),
                                validators=[alphabetic])

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
        widgets = {'username': forms.TextInput(attrs={'placeholder': 'Username'})}

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['password1'].widget = forms.PasswordInput(
            attrs={'class': 'form-control', 'placeholder': 'Choose a Password'})
        self.fields['password2'].widget = forms.PasswordInput(
            attrs={'class': 'form-control', 'placeholder': 'Confirm the Password'})

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

我也尝试覆盖表单中的默认保存方法,但这也不起作用。我已多次删除数据库并创建了新的数据库,但到目前为止没有任何帮助。

我在引导程序中使用登录模式。所以我的views.py是这样的:-

def register_view(request):
    data = dict()

    if request.method == 'POST':
        form = SignupForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
    else:
        form = SignupForm()

    context = {'form': form}
    data['html_form'] = render_to_string('signup.html',
                                         context,
                                         request=request
                                         )
    return JsonResponse(data)

我还尝试在我的settings.py中添加以下行:-

ACCOUNT_FORMS = {'signup':'accounts.forms.SignupForm',}

1 个答案:

答案 0 :(得分:0)

也许这会发生

form.save(commit=False)