1

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': 'bearclaw@example.com'
        }
    ))

    ...
    # 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?

Ken
  • 859
  • 2
  • 14
  • 33

1 Answers1

2

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': 'bearclaw@example.com'
        }
    ))

    ...
    # 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')
rahul.m
  • 5,572
  • 3
  • 23
  • 50
  • 1
    Thank you. Also found a helpful [comment](https://stackoverflow.com/questions/17873855/manager-isnt-available-user-has-been-swapped-for-pet-person?rq=1#comment107773409_17874111). Seems that the `model` is hard-coded in `contrib.auth.forms.UserCreationForm`'s `Meta`. – Ken Jun 02 '20 at 12:31