本文實例講述了Django基礎知識與基本應用。分享給大家供大家參考,具體如下:
MVC模式和MTV模式
MVC model view controller
MTV model templates view controller
Django的MTV模式本質是各組件之間為了保持松耦合關系,Django的MTV分別代表:
Model(模型):負責業務對象與數據庫的對象(ORM)
Template(模版):負責如何把頁面展示給用戶
View(視圖):負責業務邏輯,并在適當的時候調用Model和Template
此外,Django還有一個url分發器,它的作用是將一個個URL的頁面請求分發給不同的view處理,view再調用相應的Model和Template。
Django基本命令
創建一個Django項目
django-admin startproject project_name
創建項目應用
python manage.py startapp appName
啟動Django項目
python manage.py runserver IP PORT #默認是8000
查看django版本信息
import djangoprint(django.VERSION)
創建一個mysite項目
django-admin.py startproject mysite
當前目錄下會生成一個mysite項目目錄,結構如下:
manage.py是Django項目里的工具,通過它可以調用django shell
和數據庫等。
settings.py是項目的默認設置文件,包括數據庫的信息,調試標志以及其他工作的變量。
urls.py是負責把url模式映射到應用程序。
項目與應用:
一個項目可以有多個應用
一個應用可以被多個項目擁有
在mysite目錄下創建應用,比如blog
python manage.py startapp blog
生成如上目錄結構。
models:與數據庫交互的文件
views:存放視圖函數的
啟動django項目
python manage.py runserver 8080
這樣項目就能啟動了,訪問http://127.0.0.1:8080即可訪問。
注意csrf保護機制
在mysite項目目錄下的settings配置文件中,中間件MIDDLEWARE設置中,有一條django.middleware.csrf.CsrfViewMiddleware
一行,新手練習時可以先將其注釋掉。
下面我在mysite這個項目寫一個練手blog應用,注冊和登錄。
下面是blog應用中views.py的代碼:
from django.shortcuts import render,HttpResponse #導入render是為了返回渲染后的網頁,HttpResponse是可以返回字符串import json# Create your views here.def login(request): if request.method=="POST":#指定格式為POST print(request.POST) username=request.POST.get("user") password=request.POST.get("pwd") f=open("a.txt","r") # data=f.read() dic=json.load(f) if username in dic and password==dic[username]: return HttpResponse("登錄成功") #返回字符串內容 return render(request,"login.html") #返回網頁內容def auth(request): if request.method=="POST": # print(request.POST) username=request.POST.get("user") password=request.POST.get("pwd") info={} info[username]=password print(info) f=open("a.txt","a") data=json.dump(info,f) f.close() return render(request,"auth.html")
新聞熱點
疑難解答