Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

I want to register a user using a custom register model but I keep getting the following error :

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

How do I fix this error.

This is the code I have created thus far:

In urls.py I create url configurations for the various pages.

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'),
]

In forms.py I create the custom registration form.

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

In views.py I created the register view function.

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)
like image 583
Waltham WECAN Avatar asked Oct 29 '22 01:10

Waltham WECAN


2 Answers

You need to include username in your form. Coz username being a unique field can't be excluded in form. And if you are excluding it in form then, you need to handle it by generating the unique username for every user which is bit tedious.

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

    class Meta:
        model = User

        fields = (
             'username'
             'first_name',
             'last_name',
             'email',
             'password1',
             'password2'
        )
   . . . . . .
   . . . . . .
like image 187
Astik Anand Avatar answered Nov 15 '22 07:11

Astik Anand


You should really try something like below. Here, I have included username to your form fields. Since username is unique, it should be included in form fields. In the save method, self.cleaned_data.get("username", None) takes None to username field if nothing posted in the request. Your db expects None if no value given, but if you don't specify it in the save method, it receives empty strings, which causes duplicate key error. Note that Django does not store empty values as None, but uses empty string instead.

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 = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )

        def save(self, commit = True):
            user = super(CreateAccountForm, self).save(commit = False)
            user.username = self.cleaned_data.get("username", None)
            user.first_name = self.cleaned_data.get("first_name", None)
            user.last_name = self.cleaned_data.get("last_name", None)
            user.email = self.cleaned_data.get("email", None)

            if commit:

                user.save()

            return user
like image 37
Jamolkhon Akhmedov Avatar answered Nov 15 '22 05:11

Jamolkhon Akhmedov