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












0















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?










share|improve this question



























    0















    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?










    share|improve this question

























      0












      0








      0








      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?










      share|improve this question














      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?







      python django email user-registration






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 5:06









      Gene9yGene9y

      2131214




      2131214
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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!!






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424205%2fcreate-a-user-with-email-which-has-been-processed-from-the-previous-page-with-us%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            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!!






            share|improve this answer




























              0














              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!!






              share|improve this answer


























                0












                0








                0







                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!!






                share|improve this answer













                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!!







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 '18 at 6:48









                ruddraruddra

                12.5k32648




                12.5k32648






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424205%2fcreate-a-user-with-email-which-has-been-processed-from-the-previous-page-with-us%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python