Search code examples
pythondjangoemailuser-registration

Create a user with email which has been processed from the previous page with UserCreationForm Django


I am trying to create a user with email as username and the email is first screened, i.e., the email is not registered then create a user. How can I pass or set the email in forms.py as it is already processed in the previous page?

Models.py

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

class CUserManager(models.Manager):
    def _create_user(self, email, password, **extra_fields):

        now = timezone.now();

        if not email:
            raise ValueError(_('Email is required'))

        user = self.model(
            email = email,
            date_joined = now, **extra_fields
        )

        user.set_password(password)  
        user.save(using = self._db)

        return account

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

    def get_by_natural_key(self, email):
        return self.get(email=email)

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password,**extra_fields)

class CUser(AbstractBaseUser):

    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=255)
    last_name = models.CharField(_('last name'), max_length=255)
    date_joined = models.DateTimeField(_('date created'), auto_now_add=True)
    is_active = models.BooleanField(default=True)    

    objects = CUserManager()

    USERNAME_FIELD = 'email'
...

Forms.py

from django.contrib.auth.forms import UserCreationForm

class RegistrationForm(UserCreationForm):

    class Meta: 
        model = CUser
        fields = ('first_name', 'last_name', 'password1', 'password2')

in HTML

 <form action=""  method="post" role="form">
    {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Submit" />
</form>

The email comes from session['email'] which is saved in the previous page.

How can I pass this session['email'] to forms.py?


Solution

  • You can try like this:

     # Form
    
     class RegistrationForm(UserCreationForm):
    
        class Meta: 
            model = CUser
            fields = ('first_name', 'last_name', 'password1', 'password2')
    
        def save(self, **kwargs):
           email = kwargs.pop('email')
           user = super(RegistrationForm, self).save(commit=False)
           user.set_password(self.cleaned_data['password1'])
           user.email = email
           user.save()
           return user
    
    # View
    
    # your form codes...
    
    if form.is_valid():
        form.save(email=request.session.get('email'))
        # rest of the codes
    

    What I am doing here is that, first I have override that save method to catch email value from keyword arguments. Then I am passing the email value to the ModelForm's save method. Hope it helps!!