Introduction
Django's built-in authentication helps you easily manage users and their login securely. It saves time and avoids common security mistakes.
Jump into concepts and practice - no test required
Django's built-in authentication helps you easily manage users and their login securely. It saves time and avoids common security mistakes.
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User
user = authenticate(request, username='john', password='secret') if user is not None: login(request, user)
from django.contrib.auth.models import User user = User.objects.create_user('john', password='secret')
from django.contrib.auth.decorators import login_required @login_required def my_view(request): # Only logged-in users can access this view pass
This is a simple login view using Django's built-in authentication form. It checks user credentials and logs them in if correct.
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})
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.
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.
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
@login_required
def secret_page(request):
return HttpResponse('Secret content')/secret_page/?from django.contrib.auth import authenticate, login
from django.http import HttpResponse
def user_login(request):
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user:
login(user)
return HttpResponse('Logged in')
else:
return HttpResponse('Invalid credentials')