目錄
注册页面:
登录页面:
恭喜,{{operation}}成功!
首頁 後端開發 Python教學 Django教程之Django用戶註冊與登入方法

Django教程之Django用戶註冊與登入方法

Mar 10, 2017 pm 01:49 PM

這篇文章主要介紹了Django教程之Django用戶註冊與登入方法的相關資料,需要的朋友可以參考下

 Django 是由Python 開發的一個免費的開源網站框架,可以用於快速搭建高效能,優雅的網站!

學習django學得超級吃力,最近弄個最簡單的用戶登入與註冊介面都是那麼難,目前算是基本實現了,雖然功能特別特別簡單但是做一個記錄,以後學習深入了再來補充:

先建立專案,到專案所在目錄:django-admin startproject demo0414_userauth

進入專案:cd demo0414_userauth

建立對應的app:django-admin startapp account

整個專案的結構圖如圖所示

├──account
│ ├── admin.py
│ ├── admin.pyc
│ ├── apps.py
│ ├── init.py
│ ├── init.pyc
│ ├── migrations
│ │ ├ │ ├ ── 0001_initial.py
│ │ ├── 0001_initial.pyc
│ │ ├── init.py
│ │ └── init.pyc
│ ├── smodp. #│ ├── models.pyc
│ ├── tests.py
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── demo0414_userauth
│ ├── init.py
│ ├── init.pyc
│ ├── settings.py ##│
│# ── settings.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
├─ ─ manage.py
└── templates
├── register.html
├── success.html
└── userlogin.html

#4 directories, 29 files

然後在setting檔案的installed_app中新增app account;

 Django教程之Django用戶註冊與登入方法

建立一個templates資料夾,可以放在專案的根目錄下也可以放在app的目錄下。一般情況下提倡放在app的目錄下。如果放下項目的根目錄下需要在setting檔案中TEMPLATES中設定'DIRS': [os.path.join(BASE_DIR,'templates')],否則不能使用範本。

 Django教程之Django用戶註冊與登入方法

另外因為這個項目有頁面跳躍的問題,為了安全地防止csrf攻擊,一把模板中都有了相關的設定。目前我還不會用這個東西,據說在form表單中加上標籤{% csrf_token %}就可以實現了,但我沒有成功。所以先不考慮這個問題,把seeting中的這個中間件'django.middleware.csrf.CsrfViewMiddleware',註解掉


 Django教程之Django用戶註冊與登入方法

#然後在model中建立相應的資料庫:在

class User(models.Model):
 username = models.CharField(max_length=50)
 password = models.CharField(max_length=50)
 email = models.EmailField()
登入後複製

view中加入對應的程式。 Pdb當時用來斷點調試,我很喜歡,超喜歡。如果你不敢興趣,直接註解即可。

#coding=utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django.contrib import auth
from models import User

import pdb

def login(request): 
 if request.method == "POST":
  uf = UserFormLogin(request.POST)
  if uf.is_valid():
   #获取表单信息
   username = uf.cleaned_data['username']
   password = uf.cleaned_data['password']   
   userResult = User.objects.filter(username=username,password=password)
   #pdb.set_trace()
   if (len(userResult)>0):
    return render_to_response('success.html',{'operation':"登录"})
   else:
    return HttpResponse("该用户不存在")
 else:
  uf = UserFormLogin()
return render_to_response("userlogin.html",{'uf':uf})
def register(request):
 curtime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime());
 if request.method == "POST":
  uf = UserForm(request.POST)
  if uf.is_valid():
   #获取表单信息
   username = uf.cleaned_data['username']
   #pdb.set_trace()
   #try:
   filterResult = User.objects.filter(username = username)
   if len(filterResult)>0:
    return render_to_response('register.html',{"errors":"用户名已存在"})
   else:
    password1 = uf.cleaned_data['password1']
    password2 = uf.cleaned_data['password2']
    errors = []
    if (password2 != password1):
     errors.append("两次输入的密码不一致!")
     return render_to_response('register.html',{'errors':errors})
     #return HttpResponse('两次输入的密码不一致!,请重新输入密码')
    password = password2
    email = uf.cleaned_data['email']
   #将表单写入数据库
    user = User.objects.create(username=username,password=password1)
    #user = User(username=username,password=password,email=email)
    user.save()
    pdb.set_trace()
   #返回注册成功页面
    return render_to_response('success.html',{'username':username,'operation':"注册"})
 else:
  uf = UserForm()
return render_to_response('register.html',{'uf':uf})
class UserForm(forms.Form):
 username = forms.CharField(label='用户名',max_length=100)
 password1 = forms.CharField(label='密码',widget=forms.PasswordInput())
 password2 = forms.CharField(label='确认密码',widget=forms.PasswordInput())
 email = forms.EmailField(label='电子邮件')
class UserFormLogin(forms.Form):
 username = forms.CharField(label='用户名',max_length=100)
 password = forms.CharField(label='密码',widget=forms.PasswordInput())
登入後複製

Tempaltes資料夾下總共有3個頁面:

Register.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>用户注册</title>
</head>
 <style type="text/css">
 body{color:#efd;background:#453;padding:0 5em;margin:0}
 h1{padding:2em 1em;background:#675}
 h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
 p{margin:1em 0}
 </style>
<body>
<h1 id="注册页面">注册页面:</h1>
<form method = &#39;post&#39; enctype="multipart/form-data">
{{uf.as_p}}
{{errors}}
</br>
<input type="submit" value = "ok" />
</form>
</body>
</html>
登入後複製

Userlogin.html

#

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>用户注册</title>
</head>
 <style type="text/css">
 body{color:#efd;background:#453;padding:0 5em;margin:0}
 h1{padding:2em 1em;background:#675}
 h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
 p{margin:1em 0}
 </style>
<body>
<h1 id="登录页面">登录页面:</h1>
<form method = &#39;post&#39; enctype="multipart/form-data">
{{uf.as_p}}
<input type="submit" value = "ok" />
</form>
</body>
</html>
登入後複製

##Success.html

#
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title></title>
</head>
<body>
<form method = &#39;post&#39;>
 <h1 id="恭喜-operation-成功">恭喜,{{operation}}成功!</h1>
</form>
</body>
</html>
登入後複製

更新資料庫:

Django教程之Django用戶註冊與登入方法#執行伺服器:

 

Django教程之Django用戶註冊與登入方法註冊頁面:

 

Django教程之Django用戶註冊與登入方法如果註冊的用戶沒有註冊過,則能註冊成功點擊OK進入success介面


登錄頁面:

Django教程之Django用戶註冊與登入方法 

點擊OK就能進入到success頁面

關於Django用戶註冊與登入教學就給大家介紹完了,希望對大家有幫助!

以上是Django教程之Django用戶註冊與登入方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1322
25
PHP教程
1270
29
C# 教程
1250
24
Python vs.C:申請和用例 Python vs.C:申請和用例 Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

Python:遊戲,Guis等 Python:遊戲,Guis等 Apr 13, 2025 am 12:14 AM

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python與C:學習曲線和易用性 Python與C:學習曲線和易用性 Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

Python和時間:充分利用您的學習時間 Python和時間:充分利用您的學習時間 Apr 14, 2025 am 12:02 AM

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python vs.C:探索性能和效率 Python vs.C:探索性能和效率 Apr 18, 2025 am 12:20 AM

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python:自動化,腳本和任務管理 Python:自動化,腳本和任務管理 Apr 16, 2025 am 12:14 AM

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

Python標準庫的哪一部分是:列表或數組? Python標準庫的哪一部分是:列表或數組? Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

學習Python:2小時的每日學習是否足夠? 學習Python:2小時的每日學習是否足夠? Apr 18, 2025 am 12:22 AM

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。

See all articles