Django制作簡易注冊登錄系統(tǒng)的實現(xiàn)示例
前言
Django手搭簡易的注冊登錄,不使用django.contrib.auth
一、Django是什么?
Django 最初被設(shè)計用于具有快速開發(fā)需求的新聞類站點,目的是要實現(xiàn)簡單快捷的網(wǎng)站開發(fā)。采用MTV架構(gòu)(Model,Template,View)。
說明文檔
二、建立Django項目
1.新建項目
選擇Django新建項目
基本環(huán)境
- python版本為3.10
- mysql版本為8.0
- Django版本為5.0.3
asgiref==3.8.0 async-timeout==4.0.3 cffi==1.16.0 cryptography==42.0.5 Django==5.0.3 django-redis==5.4.0 et-xmlfile==1.1.0 fuzzywuzzy==0.18.0 jieba==0.42.1 numpy==1.26.4 openpyxl==3.1.2 pandas==2.2.1 pillow==10.3.0 pycparser==2.21 PyMySQL==1.1.0 python-dateutil==2.9.0.post0 pytz==2024.1 redis==5.0.3 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.10.0 tzdata==2024.1 zhon==2.0.2
2.需要安裝的包
pip install django pip install django-redis pip install pymysql
3.新建app
python manage.py startapp app名稱
4.修改settings.py
增加
import pymysql pymysql.install_as_MySQLdb()
修改
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app名稱' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '數(shù)據(jù)庫名稱', 'USER': "用戶名", 'PASSWORD': '密碼', 'PORT': 3306 # 'LOCATION': IP } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), # 指定靜態(tài)文件目錄 ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
三、在app中寫后端
1.model.py
class webUser(models.Model): class Meta: db_table = "web_user" u_id = models.CharField(primary_key=True, max_length=50) u_pwd = models.CharField(max_length=30) u_name = models.CharField(max_length=20)
數(shù)據(jù)庫可以自己去建表,表名是web_user,有三個屬性,就是u_什么的這些。
也可以使用如下代碼,在終端輸入后,遷移模型。
python manage.py makemigrations python manage.py migrate
2.views.py
在app中會有views.py文件
def check_login(request): if request.method=="POST": print("login") u_id = request.POST.get("u_id") u_pwd = request.POST.get("u_pwd") try: user = webUser.objects.get(u_id=u_id) print(user) except Exception as e: user = None print(e) else: if u_pwd == user.u_pwd: print("success") # 登錄成功 request.session["current_user"] = { "u_id": user.u_id, "u_name": user.u_name, # 你可以根據(jù)需要添加更多屬性 } return HttpResponse("ok") request.session["current_user"] = None return render(request, "login.html", {'msg': '賬號或密碼錯誤'}) elif request.method=="GET": return render(request, "login.html") else: redirect("/") def register(request): if request.method=="POST": u_id = request.POST.get("u_id") u_pwd = request.POST.get("u_pwd") u_name = request.POST.get("u_name") try: print("ok") user = webUser(u_id=u_id,u_pwd=u_pwd,u_name=u_name) except Exception as e: print(e) return JsonResponse({ 'msg': 'register fail', 'code': 403 }) else: user.save() return JsonResponse({ 'code': 200, 'msg': 'register success', }) elif request.method=="GET": return render(request,"register.html") else : render(request,'index.html') def logout(request): request.session.clear() return HttpResponse("logout") def index(request): return render(request, "index.html")
3.配置路由
在app中新建urls.py
from django.urls import path urlpatterns = [ path("",index,name="index"), path('register/',register,name="register"), path('login/',check_login,name="login"), path('logout/',logout,name="logout") ]
主路由(剛建完項目時的那個目錄下)修改如下
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('app名稱.urls')), path('admin/', admin.site.urls), ]
四、在Template寫前端
根據(jù)路由,我們有三個頁面,首頁、登錄和注冊。
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首頁</h1> <p> <a href="{% url 'register' %}" rel="external nofollow" >register</a> <a href="{% url 'login' %}" rel="external nofollow" >login</a> </p> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1> login </h1> <div style="color:red;font-size:10pt;">{{ msg }}</div> <form action="{% url 'login' %}" id="frmlogin" method="post"> <label> <input type="text" name = "u_id" placeholder="請輸入您的電子郵箱"/> </label><br/> <label> <input type="password" name="u_pwd" placeholder="password"/> </label><br/> <label> <input type="submit" value="submit"> </label> </form> </body> </html>
register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1> register </h1> <form action="{% url 'register' %}" id="register-form" method="post"> <label> <input type="text" name="u_id" placeholder="請輸入您的電子郵箱"/> </label><br/> <label> <input type="password" name="u_pwd" placeholder="password"/> </label><br/> <label> <input type="text" name="u_name" placeholder="username"/> </label><br/> <label> <input type="submit" value="submit"> </label> </form> <script> document.getElementById('register-form').addEventListener('submit', function (event) { event.preventDefault(); console.log("script") alert("script") var form = this; var formData = new FormData(form); fetch('/register/', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { window.alert(data.msg); // 顯示消息彈窗 if (data.code === 200) { // 檢查狀態(tài)碼是否為 200 setTimeout(function () { // 使用 setTimeout 來確保彈窗關(guān)閉后再重定向 window.location.href = '{% url 'login' %}'; // 重定向到登錄頁面 }, 0); // 0 毫秒延遲,但足以讓瀏覽器處理彈窗的關(guān)閉 } }) .catch(error => { console.error('Error:', error); }); }); </script> </body> </html>
五、啟動
1. 首頁
2. 注冊
3. 登錄
六、關(guān)于報錯
可能會碰到許多報錯
- 數(shù)據(jù)庫未連接,或者數(shù)據(jù)庫里的表不對:可以刪除app目錄下的migrations再重新遷移試試
- 各種包的缺失
- 網(wǎng)頁報錯:根據(jù)報錯信息去修改
- 點擊了submit沒反映:通過瀏覽器console和pycharm終端打印信息看看哪里出問題了
總結(jié)
簡單的登錄系統(tǒng)制作完了,但大部分情況可能還是用Django自帶的django.contrib.auth進行登錄和注冊。接下來可以繼續(xù)擴展用戶的刪除、修改和查詢。
到此這篇關(guān)于Django制作簡易注冊登錄系統(tǒng)的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)Django制作注冊登錄系統(tǒng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Windows下Eclipse+PyDev配置Python+PyQt4開發(fā)環(huán)境
這篇文章主要介紹了Windows下Eclipse+PyDev配置Python+PyQt4開發(fā)環(huán)境的相關(guān)資料,需要的朋友可以參考下2016-05-05python用pandas數(shù)據(jù)加載、存儲與文件格式的實例
今天小編就為大家分享一篇python用pandas數(shù)據(jù)加載、存儲與文件格式的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12Django中實現(xiàn)點擊圖片鏈接強制直接下載的方法
這篇文章主要介紹了Django中實現(xiàn)點擊圖片鏈接強制直接下載的方法,涉及Python操作圖片的相關(guān)技巧,非常具有實用價值,需要的朋友可以參考下2015-05-05python實現(xiàn)學(xué)生成績測評系統(tǒng)
這篇文章主要為大家詳細介紹了python實現(xiàn)學(xué)生成績測評系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-06-06python 使用多線程創(chuàng)建一個Buffer緩存器的實現(xiàn)思路
這篇文章主要介紹了python 使用多線程創(chuàng)建一個Buffer緩存器的實現(xiàn)思路,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07