How do I extend UserCreationForm to include email field

前端 未结 3 1841
借酒劲吻你
借酒劲吻你 2021-01-12 01:26

I managed to get the stock standard User Creation Form to work. Which included just the username, password1 and password2 field. However, when I try to include the email fie

相关标签:
3条回答
  • 2021-01-12 02:07

    I'm new with django and I tried what you posted and I had to changed to work ... Here's what I did.

    forms.py

    from django import forms
    from django.contrib.auth.forms import UserCreationForm
    from django.contrib.auth.models import User
    
    
    class UserCreationForm(UserCreationForm):
        email = forms.EmailField(required=True, label='Email')
    
        class Meta:
            model = User
            fields = ("username", "email", "password1", "password2")
    
        def save(self, commit=True):
            user = super(UserCreationForm, self).save(commit=False)
            user.email = self.cleaned_data["email"]
            if commit:
                user.save()
            return user
    

    views.py

    from .forms import UserCreationForm
    from django.urls import reverse_lazy
    from django.views import generic
    
    
    class SignUp(generic.CreateView):
        form_class = UserCreationForm
        success_url = reverse_lazy('login')
        template_name = 'accounts/signup.html'
    

    signup.html

    {% extends 'polls/base.html' %}
    {% load bootstrap4 %}
    {% load static %}
    {% block content %}
    <body class="body_login">
      <form method="post" class="form-signup">
        {% csrf_token %}
        {% bootstrap_form form  %}
        <button type="submit" class="save btn btn-dark">Sign up</button>
      </form>
    </body>
    {% endblock %}
    
    0 讨论(0)
  • 2021-01-12 02:08

    forms.py

    from django.contrib.auth.forms import UserCreationForm
    from django.contrib.auth.models import User
    
    class SignupForm(UserCreationForm):
        class Meta:
            model = User
            fields = ("username", "email",)
    

    views.py

    from django.urls import reverse_lazy
    from django.views import generic
    from accounts.forms import SignupForm
    
    class SignUpView(generic.CreateView):
        form_class = SignupForm
        success_url = reverse_lazy('login')
        template_name = 'stories/register.html'
    
    0 讨论(0)
  • You are importing the wrong UserCreationForm in views.py. You should import your own form not the Django's one:

    stories/views.py

    from stories.forms import UserCreationForm
    ...
    

    Besides that, you don't have to wrap all your fields with <p></p> individually as there exists form.as_p() for this job.

    register.html

    <form action = "/register/" method = "POST">{% csrf_token %}
        {{ form.as_p }}
    </form>
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题