django authentication 登錄注冊的實現(xiàn)示例
前言
之前,寫了django制作簡易登錄系統(tǒng),這次利用django內置的authentication功能實現(xiàn)注冊、登錄
可參考之前的文章:Django制作簡易注冊登錄系統(tǒng)
一、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
二、后端實現(xiàn)
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") # 獲取參數(shù) 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' %}" rel="external nofollow" >Logout</a> {% else %} <h1>Welcome, Guest!</h1> <p>Please <a href="{% url 'login' %}" rel="external nofollow" rel="external nofollow" >Login</a> or <a href="{% url 'register' %}" rel="external nofollow" rel="external nofollow" >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' %}" rel="external nofollow" rel="external nofollow" >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' %}" rel="external nofollow" rel="external nofollow" >Register here</a>.</p> </body> </html>
可以看到登陸后,歡迎<用戶名>用戶
總結
用戶的認證內容存儲在session中,我設置的過期時間是5分鐘。
沒有對出錯情況進行處理,一旦出錯僅展示報錯json數(shù)據。
到此這篇關于django authentication 登錄注冊的實現(xiàn)示例的文章就介紹到這了,更多相關django authentication 登錄注冊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python中函數(shù)的創(chuàng)建與調用你了解嗎
這篇文章主要為大家詳細介紹了Python中函數(shù)的創(chuàng)建與調用,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03PyTorch讀取Cifar數(shù)據集并顯示圖片的實例講解
今天小編就為大家分享一篇PyTorch讀取Cifar數(shù)據集并顯示圖片的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07python機器學習XGBoost梯度提升決策樹的高效且可擴展實現(xiàn)
這篇文章主要為大家介紹了python機器學習XGBoost梯度提升決策樹的高效且可擴展實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01