文章目录
- 前言
- 一、django配置
- 二、后端实现
- 1.新建app
- 2.编写view
- 3.配置路由
- 三、前端编写
- 1、index.html
- 2、register.html
- 3、 login.html
- 总结
前言
之前,写了django制作简易登录系统,这次利用django内置的authentication功能实现注册、登录
提示:可参考之前的文章
Django制作简易注册登录系统
一、django配置
python包具体配置见之前的文章,和之前一样,注释掉跨域,引入mysql
authentication需要额外引入redis
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://ip:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"session": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://ip:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {
"max_connections": 100
}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = "session"
SESSION_COOKIE_AGE = 500
二、后端实现
1.新建app
python manage.py startapp app名称
2.编写view
代码如下(示例):
# Create your views here.
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import redirect
from django.shortcuts import render
def login1(request):
if request.method == 'GET':
print("GET")
return render(
request,
'login.html',
)
elif request.method == 'POST':
print("POST")
# 获取参数
user_name = request.POST.get('username', '')
pwd = request.POST.get('password', '')
# 用户已存在
if User.objects.filter(username=user_name):
# 使用内置方法验证
user = authenticate(username=user_name, password=pwd)
print(user)
# 验证通过
if user:
# 用户已激活
if user.is_active:
login(request, user)
request.session["current_user"] = user.username # 将用户名存储在session中
request.session.set_expiry(0)
return render(request, "index.html")
# 未激活
else:
return JsonResponse({
'code': 403,
'msg': '用户未激活'
})
# 验证失败
else:
return JsonResponse({
'code': 403,
'msg': '用户认证失败'
})
# 用户不存在
else:
return redirect('register')
else:
return render(request, 'login.html')
def register(request):
if request.method == "GET":
return render(request, "register.html")
elif request.method == "POST":
username = request.POST.get('username', '')
pwd = request.POST.get('password', '')
if User.objects.filter(username=username):
return JsonResponse({
'code': 200,
'msg': 'user exists'
})
else:
user = User.objects.create_user(username=username, password=pwd)
return JsonResponse({
'code': 200,
'msg': '注册成功,去登陆'
})
else:
return render(request, 'register.html')
def logout1(request):
logout(request)
request.session.clear()
return redirect("index")
def index(request):
return render(request, "index.html")
3.配置路由
在app中新建urls.py
from django.urls import path
from loginapp import views
from loginapp.views import index, login1, register, logout1
urlpatterns = [
path('', index, name='index'), # 定义根路径'/'到index视图的映射
path('login/', login1, name='login'),
path('logout/', logout1, name='logout'),
path('register/', register, name='register'),
]
主路由(刚建完项目时的那个目录下)修改如下
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('app名称.urls')),
path('admin/', admin.site.urls),
]
三、前端编写
1、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
{% if request.session.current_user %}
<h1>Welcome, {{ request.session.current_user }}!</h1>
<p>You are logged in.</p>
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<h1>Welcome, Guest!</h1>
<p>Please <a href="{% url 'login' %}">Login</a> or <a href="{% url 'register' %}">Register</a>.</p>
{% endif %}
</body>
</html>
2、register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<form method="post" action="{% url 'register' %}">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Register</button>
</form>
<p>Already have an account? <a href="{% url 'login' %}">Login here</a>.</p>
</body>
</html>
3、 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
<p>Don't have an account? <a href="{% url 'register' %}">Register here</a>.</p>
</body>
</html>
可以看到登陆后,欢迎<用户名>用户
总结
用户的认证内容存储在session中,我设置的过期时间是5分钟。
没有对出错情况进行处理,一旦出错仅展示报错json数据。