You are going to need this in case you want to allow users creating an account to input more than just their username and password.
Import everything you need: forms.py
from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User
And your class that uses the UserCreationForm class (still in forms.py)
class RegisterForm(UserCreationForm):
# declare the fields you will show
username = forms.CharField(label="Your Username")
# first password field
password1 = forms.CharField(label="Your Password")
# confirm password field
password2 = forms.CharField(label="Repeat Your Password")
email = forms.EmailField(label = "Email Address")
first_name = forms.CharField(label = "Name")
last_name = forms.CharField(label = "Surname")
# this sets the order of the fields
class Meta:
model = User
fields = ("first_name", "last_name", "email", "username", "password1", "password2", )
# this redefines the save function to include the fields you added
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
Can you give an example of how to use it in views.py?
To display the registration form you should have this in your views.py:
def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("./") else: form = RegisterForm() return render(request, 'template/register.html', { 'form': form })Hope it helps!
Why don’t you put the field passwords in the ‘save’ function?
Because username, password1 and password 2 are sent by default by the form. I only add the fields that are missing.
Thanks for the example. . .One question, since you’re inheriting from UserCreationForm, do you really need to add in the password fields explicitly? They’re already in your subclassed form since you’re inheriting from the base class (UserCreationForm).
When I’ve subclassed UserCreationForm, I just add in the new parts I need such as an email, then override the save method, making sure to include the email in this. The password stuff is already done for you. . .Or am I missing something?
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = (‘username’, ’email’, ‘password1’, ‘password2’)
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data[“email”]
if commit:
user.save()
return user
i’m sorry i am trying to access the custom fields from UserCreationForm and they bring attribute error that the User objects doesn’t have such fields, how do i solve the error?! how can i use them from request.user in views.py?