Django 用户认证(Auth)组件一般用在用户的登录注册上,用于判断当前的用户是否合法,并跳转到登陆成功或失败页面。Auth 组件 (django.contrib.auth),会自动包含在创建的Django 3.x 项目中。
1. 开发环境
Windows 10 Home (20H2)
MariaDB 10.4.21
Python 3.8.1
Pip 19.2.3
Django: 3.0
Windows下搭建开发环境,可以参考 Windows下搭建 Django 3.x 开发和运行环境
2. 创建 Django 项目
> django-admin startproject djangoLoginDemo
3. 添加 App
> cd djangoLoginDemo
> python manage.py startapp accounts
生成的项目目录结构,参考 如何在Django中使用template和Bootstrap
修改 djangoLoginDemo/settings.py
ALLOWED_HOSTS = ['localhost', '192.168.0.5']
...
INSTALLED_APPS = [
...
'accounts',
]
4. 数据库和实体
1) MariaDB
创建一个新的空数据库 "django_logindemo",修改 djangoLoginDemo/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_logindemo',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
2) 表单
添加 accounts/acc_forms.py
from django import forms
from django.forms import fields
from django.forms import widgets
from django.core.exceptions import ValidationError
class loginForm(forms.Form):
username = fields.CharField(
label="Username",
widget=widgets.TextInput(),
)
password = fields.CharField(
label="Password",
widget=widgets.TextInput(attrs={'type': 'password'}),
)
3) 创建表,生成用户
> python manage.py migrate
> python manage.py createsuperuser # Admin 用户
Username (leave blank to use 'xxx'): admin
Email address: [email protected]
Password: 123456
Password (again): 123456
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
一般用户,用Admin 用户登录 http://localhost:8000/admin 后,在后台创建。
两种用户都可以登陆 http://localhost:8000/admin, 区别是权限不同,具体差异这里不讨论。
5. 视图和路由
1) 模版
(1) 添加 accounts/templates/home.html
{% if success_msg %}
{{ success_msg }}
{% endif %}
{% if error_msg %}
{{ error_msg }}
{% endif %}
{% if request.user.is_authenticated %}
Welcome {{ request.user.username }}, click Here to logout.
{% endif %}
Home Page
(2) 添加 accounts/templates/login.html
{% if success_msg %}
{{ success_msg }}
{% endif %}
{% if error_msg %}
{{ error_msg }}
{% endif %}
Login Page
2) 修改 accounts/views.py
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from accounts.acc_forms import loginForm
# Create your views here.
@login_required
def home(request):
return render(request, "home.html")
def accounts_login(request):
if request.method == "GET":
form = loginForm()
return render(request, "login.html", {"form": form, "next": request.GET.get('next', '')})
else:
form = loginForm(request.POST)
if form.is_valid():
data = form.cleaned_data
user = authenticate(username=data['username'], password=data['password'])
if user:
login(request, user)
next = request.POST.get('next', '')
if next:
return redirect(next)
else:
#request.session["success_msg"] = "Login '" + data['username'] + "' successfully"
return redirect("home")
else:
return render(request, "login.html", {"form": form, "error_msg": "Invalid username or password"})
else:
#print(form.errors)
clean_errors = form.errors.get("__all__")
#print(222, clean_errors)
return render(request, "login.html", {"form": form, "clean_errors": clean_errors})
def accounts_logout(request):
logout(request)
return redirect("accounts_login")
3) 添加 accounts/urls.py
from django.urls import path
from accounts import views
urlpatterns = [
path('login/', views.accounts_login, name='accounts_login'),
path('logout/', views.accounts_logout, name='accounts_logout'),
]
4) 修改 djangoLoginDemo/urls.py
from django.contrib import admin
from django.urls import path, include
from accounts import views
urlpatterns = [
path('', views.home, name='home'),
path('accounts/', include('accounts.urls')),
path('admin/', admin.site.urls),
]
6. 运行
> python manage.py runserver
访问 http://localhost:8000/ , 自动跳转到 http://localhost:8000/accounts/login/?next=/, 输入
Username: admin
Password: 123456
点击 "Login" 按钮,可以见到如下页面内容:
Welcome admin, click Here to logout.
Home Page
> python manage.py runserver 192.168.0.5:8080 # 可以指定IP和端口
访问 http://192.168.0.5:8080/, 同上。