Django制作簡(jiǎn)易注冊(cè)登錄系統(tǒng)的實(shí)現(xiàn)示例
前言
Django手搭簡(jiǎn)易的注冊(cè)登錄,不使用django.contrib.auth
一、Django是什么?
Django 最初被設(shè)計(jì)用于具有快速開發(fā)需求的新聞?lì)愓军c(diǎn),目的是要實(shí)現(xiàn)簡(jiǎn)單快捷的網(wǎng)站開發(fā)。采用MTV架構(gòu)(Model,Template,View)。
說明文檔
二、建立Django項(xiàng)目
1.新建項(xiàng)目

選擇Django新建項(xiàng)目
基本環(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,有三個(gè)屬性,就是u_什么的這些。
也可以使用如下代碼,在終端輸入后,遷移模型。
python manage.py makemigrations python manage.py migrate
2.views.py
在app中會(huì)有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': '賬號(hào)或密碼錯(cuò)誤'})
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")
]
主路由(剛建完項(xiàng)目時(shí)的那個(gè)目錄下)修改如下
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('app名稱.urls')),
path('admin/', admin.site.urls),
]
四、在Template寫前端
根據(jù)路由,我們有三個(gè)頁面,首頁、登錄和注冊(cè)。
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="請(qǐng)輸入您的電子郵箱"/>
</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="請(qǐng)輸入您的電子郵箱"/>
</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>
五、啟動(dòng)

1. 首頁

2. 注冊(cè)

3. 登錄


六、關(guān)于報(bào)錯(cuò)
可能會(huì)碰到許多報(bào)錯(cuò)
- 數(shù)據(jù)庫未連接,或者數(shù)據(jù)庫里的表不對(duì):可以刪除app目錄下的migrations再重新遷移試試
- 各種包的缺失
- 網(wǎng)頁報(bào)錯(cuò):根據(jù)報(bào)錯(cuò)信息去修改
- 點(diǎn)擊了submit沒反映:通過瀏覽器console和pycharm終端打印信息看看哪里出問題了
總結(jié)
簡(jiǎn)單的登錄系統(tǒng)制作完了,但大部分情況可能還是用Django自帶的django.contrib.auth進(jìn)行登錄和注冊(cè)。接下來可以繼續(xù)擴(kuò)展用戶的刪除、修改和查詢。
到此這篇關(guān)于Django制作簡(jiǎn)易注冊(cè)登錄系統(tǒng)的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)Django制作注冊(cè)登錄系統(tǒng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Django小白教程之Django用戶注冊(cè)與登錄
- django用戶注冊(cè)、登錄、注銷和用戶擴(kuò)展的示例
- django的登錄注冊(cè)系統(tǒng)的示例代碼
- Django實(shí)現(xiàn)auth模塊下的登錄注冊(cè)與注銷功能
- django 框架實(shí)現(xiàn)的用戶注冊(cè)、登錄、退出功能示例
- Django調(diào)用百度AI接口實(shí)現(xiàn)人臉注冊(cè)登錄代碼實(shí)例
- Django用戶登錄與注冊(cè)系統(tǒng)的實(shí)現(xiàn)示例
- django+vue實(shí)現(xiàn)注冊(cè)登錄的示例代碼
- Django 登錄注冊(cè)的實(shí)現(xiàn)示例
- django authentication 登錄注冊(cè)的實(shí)現(xiàn)示例
相關(guān)文章
Windows下Eclipse+PyDev配置Python+PyQt4開發(fā)環(huán)境
這篇文章主要介紹了Windows下Eclipse+PyDev配置Python+PyQt4開發(fā)環(huán)境的相關(guān)資料,需要的朋友可以參考下2016-05-05
python用pandas數(shù)據(jù)加載、存儲(chǔ)與文件格式的實(shí)例
今天小編就為大家分享一篇python用pandas數(shù)據(jù)加載、存儲(chǔ)與文件格式的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Django中實(shí)現(xiàn)點(diǎn)擊圖片鏈接強(qiáng)制直接下載的方法
這篇文章主要介紹了Django中實(shí)現(xiàn)點(diǎn)擊圖片鏈接強(qiáng)制直接下載的方法,涉及Python操作圖片的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-05-05
python實(shí)現(xiàn)學(xué)生成績測(cè)評(píng)系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)學(xué)生成績測(cè)評(píng)系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06
Python列表中多元素刪除(移除)的實(shí)現(xiàn)
本文主要介紹了Python列表中多元素刪除(移除)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
python 使用多線程創(chuàng)建一個(gè)Buffer緩存器的實(shí)現(xiàn)思路
這篇文章主要介紹了python 使用多線程創(chuàng)建一個(gè)Buffer緩存器的實(shí)現(xiàn)思路,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07

