CUSTOM USER REGISTRATION IN DJANGO (register user in custom authentication)

Опубликовано: 16 Апрель 2023
на канале: Developer Bites
21
1

Custom Authentication is frequently used in Django Projects in which email acts as the username and also different custom fields are added to the custom user model. In this video, we are using the in-built class UserCreationForm to create new custom registration class which enables registration in the custom user model.

In the forms.py file, you can create a form class using the below code:

from django.contrib.auth.forms import UserCreationForm, UsernameField
from .models import Users
from django import forms
from django.utils.translation import gettext_lazy as _

class CustomUserCreationForm(UserCreationForm):
"to register user using the custom user model"

class Meta:
model = Users
fields = ("first_name","last_name","email")
field_classes = {"email": UsernameField}


In the views.py, you can put code as :

from django.shortcuts import render, redirect
from django.urls import reverse
from .forms import CustomUserCreationForm

def user_register(request):
"to register user using custom user model"
if request.method=='POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('success_register'))
else:
return render(request, "registration/user_register.html", {'form':form})
form = CustomUserCreationForm
return render(request, "registration/user_register.html", {'form':form})

def success_register(request):
"to show after successful registration"
return render(request, "registration/success_register.html", {})

In the urls.py, define your urls:

path('user_register', views.user_register, name="user_register"),
path('success_register', views.success_register, name="success_register"),

Please watch the video carefully so that you can better understand the registration functionality. Also go through my other videos, I shall wait for your feedback.