0
0
Djangoframework~5 mins

Why Django built-in auth matters

Choose your learning style9 modes available
Introduction

Django's built-in authentication helps you easily manage users and their login securely. It saves time and avoids common security mistakes.

When you want users to create accounts and log in to your website.
When you need to protect parts of your site so only logged-in users can see them.
When you want to handle user passwords safely without writing your own code.
When you want to add features like password reset or user permissions quickly.
When you want a trusted, tested way to manage user sessions and security.
Syntax
Django
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
Django provides ready-to-use functions and models for user management.
You don't need to build login or password handling from scratch.
Examples
This checks if the username and password are correct, then logs the user in.
Django
user = authenticate(request, username='john', password='secret')
if user is not None:
    login(request, user)
This creates a new user with a username and password safely stored.
Django
from django.contrib.auth.models import User
user = User.objects.create_user('john', password='secret')
This decorator protects a page so only logged-in users can see it.
Django
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    # Only logged-in users can access this view
    pass
Sample Program

This is a simple login view using Django's built-in authentication form. It checks user credentials and logs them in if correct.

Django
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('home')
    else:
        form = AuthenticationForm()
    return render(request, 'login.html', {'form': form})
OutputSuccess
Important Notes

Always use Django's built-in auth to keep user data safe.

Customize user models only if needed; otherwise, use the default User model.

Use Django's decorators and forms to simplify protecting pages and handling login.

Summary

Django built-in auth saves time and improves security for user login.

It provides ready tools for user creation, login, logout, and permissions.

Use it to protect your site and manage users without extra work.