UserCreationForm - ( User Management in Django )
Heading h2
Syntax
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
Example
from django.shortcuts import render, redirect
from .forms import MyUserCreationForm
def signup(request):
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = MyUserCreationForm()
return render(request, 'signup.html', {'form': form})
Output
Upon submission, the form is validated and if valid, the user is created and redirected to the home page.
Explanation
The UserCreationForm is a built-in Django form for creating new users. It includes default fields such as username and password but can also be customized to include additional fields such as email, first name, last name etc.
In the above example, we have created a customized user creation form that includes an email field. When the form is submitted, it is validated and if valid, the user is created and redirected to the home page.
Use
The UserCreationForm is used for creating new users in a Django application. It can be customized to include additional fields as needed.
Important Points
- UserCreationForm is a built-in Django form for creating new users
- It includes default fields such as username and password
- It can be customized to include additional fields such as email, first name, last name etc.
Summary
In summary, the UserCreationForm is a powerful tool in Django for managing user creation in a web application. By default, the form includes username and password fields, but it can be customized to add additional user fields such as email, first name, last name and others.