YouTip LogoYouTip

Django Blog Auth

## User System β€” Registration, Login, Logout In this chapter, you will learn how to use Django's built-in authentication system to implement user registration, login, and logout functionality. * * * ## Django Built-in auth System Django comes with a complete user authentication module: * Built-in `User` model (username, password, email, etc.) * Built-in login/logout views (no need to write your own logic) * Built-in permission and group management * Form validation and security protection (CSRF, XSS) This module is `django.contrib.auth`, which is already registered in INSTALLED_APPS by default when creating a project. * * * ## Registration Page Django has built-in login/logout views, but no built-in registration view, so we need to create it ourselves. ### Step 1: Create Registration Form ## Example # File path: blog/forms.py (new file) from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): """Custom registration form: inherits UserCreationForm, adds email field""" email= forms.EmailField( label='Email', required=True, help_text='Please enter a valid email address.' ) class Meta: model = User fields =['username','email','password1','password2'] labels ={ 'username': 'Username', } ### Step 2: Write Registration View ## Example # File path: blog/views.py (add new) from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib import messages from .forms import RegisterForm def register(request): """User registration view""" # If user is already logged in, redirect to homepage if request.user.is_authenticated: return redirect('index') if request.method=='POST': # User submitted registration form form = RegisterForm(request.POST) if form.is_valid(): user= form.save()# Save user to database login(request,user)# Auto login after registration messages.success(request, f'Registration successful, welcome {user.username}!') return redirect('index') else: # GET request: show empty registration form form = RegisterForm() return render(request,'blog/register.html',{ 'form': form, 'title': 'Register - TUTORIAL Blog' }) > Django's `messages` framework is used to pass one-time messages between requests (e.g., "Registration successful"). By rendering the messages area in the template, users can see the feedback. It works with sessions, and the message automatically disappears after being displayed once. * * * ## Login and Logout Django has built-in login and logout views, just import them in the routing. ## Example # File path: blog/urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns =[ path('', views.index, name='index'), path('post//', views.post_detail, name='post_detail'), path('register/', views.register, name='register'), # Django built-in login view # template_name: specifies which template to use path('login/', auth_views.LoginView.as_view( template_name='blog/login.html', redirect_authenticated_user=True# Redirect logged-in users accessing login directly ), name='login'), # Django built-in logout view path('logout/', auth_views.LogoutView.as_view(), name='logout'), ] Configure login/logout redirect URLs in settings.py: ## Example # File path: blog_project/settings.py (add at the end) LOGIN_URL ='login'# Redirect to login page when unauthenticated user accesses protected page LOGIN_REDIRECT_URL ='index'# Redirect to homepage after successful login LOGOUT_REDIRECT_URL ='index'# Redirect to homepage after logout * * * ## Create Authentication Related Templates ### Login Template ## Example {% extends 'blog/base.html' %} {% block title %}Login - TUTORIAL Blog{% endblock %} {% block content %}

Login

{% csrf_token %}
{{ form.username }}
{{ form.password }}
{% if form.errors %}

Incorrect username or password, please try again.

{% endif %}
{% endblock %} ### Registration Template ## Example {% extends 'blog/base.html' %} {% block title %}Register - TUTORIAL Blog{% endblock %} {% block content %}

Register

{% csrf_token %} {{ form.as_p }}
{% endblock %} > `{% csrf_token %}` is Django's security mechanism to prevent Cross-S
← Django Blog CbvDjango Blog Url Routing β†’