Django Allauth: Duplicate Key Value Violates Unique Constraint: Key (username)=() already exists
I have been troubleshooting an issue with my custom allauth Django user model for some time. I only want to use email, first name, last name, and password as part of my user signup form, and I can get it to work once, but when a second user signs up, it says that the username already exists. I have seen others with a similar issue, but unfortunately their solutions do not work. If I remove the custom account form, then it does, but I need to include first name and last name in my signup form, so not sure how to work around that. Any help is appreciated!
settings.py
AUTH_USER_MODEL = 'accounts.CustomUser'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
# I have also tried ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' and ACCOUNT_USER_MODEL_USERNAME_FIELD = 'email' per the solution linked above, but that did not work for my use case
ACCOUNT_FORMS = {
'signup': 'accounts.forms.CustomUserCreationForm'
}
models.py
class CustomUser(AbstractUser):
email = models.EmailField(max_length=256)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']
forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('email', 'first_name', 'last_name')
Figured out an answer after playing around with it a bit and using Ankit's response as a template.
forms.py
from django import forms
from allauth.account.forms import SignupForm
class CustomUserCreationForm(SignupForm):
email = forms.EmailField(max_length = 256)
first_name = forms.CharField(max_length = 128)
last_name = forms.CharField(max_length = 128)
def save(self, request):
user = super(CustomUserCreationForm, self).save(request)
user.save()
return user
settings.py
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_FORMS = {
'signup': 'accounts.forms.CustomUserCreationForm'
}