Ken
Ken

Reputation: 902

AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'

I have a custom signup form SignupForm that checks for existing email for the custom user object CustomUser and raises a ValidationError if exists. But when I try to raise the error, I get AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'.

Here are my codes.

forms.py

from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.exceptions import ValidationError

from django.contrib.auth import get_user_model


class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': '[email protected]'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data

views.py

from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import SignupForm
from .models import CustomUser

...
# other views and imports
...

class CustomSignup(CreateView):
    form_class = SignupForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.username

settings.py

AUTH_USER_MODEL = "accounts.CustomUser"

What am I missing?

Upvotes: 1

Views: 226

Answers (1)

rahul.m
rahul.m

Reputation: 5854

Basically you are missing ModelForm Meta

try this

class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': '[email protected]'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data

   class Meta:
       model = get_user_model()
       fields = ('username', 'email')

Upvotes: 2

Related Questions