Django user authentication part 1

First create a urls.py file and add these urls there

urlpatterns = [
    path('register/', views.register_user, name="user_register"),
    path('login/', views.user_login, name="user_login"),
    path('logout/', views.user_logout, name="user_logout"),
]

Create a forms.py file, if you want to include extra fields (e.g-email field)

from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

Now craete funcation in views.py file..

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Group
from .forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from account.decorators import unauthenticated_user, allowed_users, admin_only

@unauthenticated_user
def register_user(request):
    form = CreateUserForm(request.POST)
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            
            group = Group.objects.get(name='customer') 
            user.groups.add(group)

            messages.success(request, 'Account was created success for ' + username)
            return redirect('/login')

    context={'form':form}
    template_name='register.html'
    return render(request, template_name, context)
@unauthenticated_user
def user_login(request):
    if request.user.is_authenticated:
       return redirect('/')
    else:
        if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')

            user = authenticate(request, username=username, password=password)

            if user is not None:
                login(request, user)
                return redirect('/')
            else:
                messages.info(request, 'Username OR Password is Incorrect')

        template_name='login.html'
        context={}
        return render(request, template_name, context)
def user_logout(request):
    logout(request)
    return redirect('/login')

Create register.html file…and use this package (Django Widget Tweaks) to design you register form as per your requirements

 <form id="register-form" action='' method="POST">
                                    {% csrf_token %}
                                    <div class="form-group">
                                        {% render_field form.username class="form-control" placeholder="Enter Username..." %}
                                    </div>
                                    <div class="form-group">
                                        {% render_field form.email class="form-control" placeholder="Enter Email Id..." %}
                                    </div>
                                    <div class="form-group">
                                        {% render_field form.password1 class="form-control" placeholder="Enter Password..." %}
                                    </div>
                                    <div class="form-group">
                                        {% render_field form.password2 class="form-control" placeholder="Enter Confirm Password..." %}
                                    </div>
                                    <div class="res-box text-center mt-30">
                                        <button type="submit" class="btn v8"><i class="lnr lnr-enter"></i>Sign Up</button>
                                    </div>
                                </form>

Create login.html file..

<form id="register-form" action="" method="POST">
                                    {% csrf_token %}
                                    <div class="form-group">
                                        <input type="text" name="username" class="form-control" placeholder="Enter Username..."/>
                                    </div>
                                    <div class="form-group">
                                        <input type="password" name="password" class="form-control" placeholder="Enter Password..."/>
                                    </div>
                                    <div class="res-box text-center mt-30">
                                        <button type="submit" class="btn v8"><i class="lnr lnr-enter"></i>Sign Up</button>
                                    </div>
                                </form>

Read Also: Django user Authentication and Permission (Part-2)

LEAVE A REPLY

Please enter your comment!
Please enter your name here