akg
akg

Reputation: 670

Unable to render Email field in the registration form in an Django app

I am using Django 1.8.After following tutorials of how to customize user model I decided to make an app using customized user model. My CustomUser model looks like -

class CustomUser(AbstractBaseUser):

first_name = models.CharField(max_length=100,blank=True)
last_name = models.CharField(max_length=100,blank=True)
college = models.CharField(max_length=200,blank=True)
email = models.EmailField(unique=True,blank=False)
date_joined = models.DateTimeField(_('date joined'), default=datetime.now())
is_active   = models.BooleanField(default=True)
is_superuser    = models.BooleanField(default=False)
is_staff    = models.BooleanField(default=False)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name']

objects = CustomUserManager()

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')

def get_absolute_url(self):
    return "/users/%s/" % urlquote(self.email)

def get_full_name(self):
    """
    Returns the first name plus the last name , with a space in between
    """
    full_name = '%s %s' % (self.first_name,self.last_name)
    return full_name.strip()

My CustomUserManager class is this (though not important to mention here) -

class CustomUserManager(BaseUserManager):
def _create_user(self,email,password,is_staff,is_superuser,**extra_fields):
    """
    Creates and saves a User with the given email and password
    """

    t = datetime.now()

    if not email:
        raise ValueError('The given email must be set')

    email = self.normalize_email(email)
    user = self.model(email=email,is_staff=is_staff,is_active=True,is_superuser=is_superuser,
            last_login=t,date_joined=t,**extra_fields)
    user.set_password(password)
    user.save(using=self._db)

    return user

def create_user(self,email,password=None,**extra_fields):
    return self._create_user(email,password,False,False,**extra_fields)

def create_superuser(self,email,password=None,**extra_fields):
    print "Inside Superuser"
    return self._create_user(email,password,True,True,**extra_fields)

I have added the relevant settings - AUTH_USER_MODEL and AUTHENTICATION_BACKENDS to the settings.py file.

Most importantly my custom registration form looks like this -

class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and password
"""

def __init__(self,*args,**kargs):
    super(CustomUserCreationForm,self).__init__(*args,**kargs)
    #print self.fields
    del self.fields['username']

    class Meta:
        model = CustomUser
        fields = ('email',)

I have mentioned here that my model will be CustomUser.As you can see that my custom form inherits from in-built UserCreation form. For the convenience I am also posting here UserCreationFrom class -

class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
    'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(label=_("Password"),
    widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
    widget=forms.PasswordInput,
    help_text=_("Enter the same password as above, for verification."))

class Meta:
    model = User
    fields = ("username",)

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'],
            code='password_mismatch',
        )
    return password2

def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

I have some doubts here.UserCreationForm has model set to User which is default User model(from django.contrib.auth.models import User);

but in my CustomForm's meta class I have mentioned model equal to my CustomUser.

When I print the fields returned by UserCreationForm it gives - username,password1,password2.Presence of 'username' field is the proof that UserCreationForm used 'User' model and added 'username' field which subsequently I deleted in my custom form.

I have also added 'email' to the fields in my custom form but Email option is not rendering in my registration page.Is what I am doing the right way to create Custom Registration forms? If not then what should be done to render email field in my custom registration form.

enter image description here

Upvotes: 0

Views: 224

Answers (1)

chandu
chandu

Reputation: 1063

from .models import CustomUser

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput)

    class Meta:
        model = CustomUserModel
        # Note - include all *required* CustomUser fields here,
        # but don't need to include password1 and password2 as they are
        # already included since they are defined above.
        fields = ("email",)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            msg = "Passwords don't match"
            raise forms.ValidationError("Password mismatch")
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

Source: Django 1.5: UserCreationForm & Custom Auth Model

Upvotes: 1

Related Questions