Python的WEB框架有Django、Tornado、Flask 等多種,Django相較與其他WEB框架其優勢為:大而全,框架本身集成了ORM、模型綁定、模板引擎、緩存、Session等諸多功能。
一、基本配置
1、創建Django程序
- 終端命令:django-admin startproject sitename
- IDE創建Django程序時,本質上都是自動執行上述命令
上述的sitename是自己定義的項目名稱!
其他常用命令:
python manage.py runserver 0.0.0.0:port python manage.py startapp appname python manage.py syncdb python manage.py makemigrations python manage.py migrate python manage.py createsuperuser
2、程序目錄
settings.py 放配置文件
urls.py 存放路由系統(映射)
wsgi.py 讓你做配置:wsgi有多重一種uwsgi和wsgi,你用那種wsgi來運行Django,一般不用改只有你用到的時候在改
manage.py 就是Django的啟動管理程序
以上配置文件,如果是初學者當創建完project后都不要修改,因為涉及到很多配置文件需要修改
3、Project和App概念
咱們目前創建的是Project,Project下面可以有很多app,原理是什么呢!
我們創建的Project是一個大的工程,下面有很多功能:(一個Project有多個App,其實他就是對你大的工程的一個分類)
''' Project --web (前台功能) --administrator (后台管理功能) 一個Project有多個app,其實他就是對你大的工程的一個分類 '''
看下面的圖:
4、創建App
python manage.py startapp app01
如果在創建一個App,我們可以理解為App是手機里的App程序他們之間是完全獨立的,好處是降低他們之間的耦合性,不到萬不得已不要讓他們之間建立關系!
app里面的admin 是提供了后台管理的平台,test是用來測試的!
admin后台管理:
同步數據庫
python manage.py syncdb #注意:Django 1.7.1及以上的版本需要用以下命令 python manage.py makemigrations python manage.py migrate
創建超級用戶
python manage.py createsuperuser
輸入你要設置的用戶名和密碼,然后啟動Django,然后輸入RUL/admin即可:http://127.0.0.1:8000/admin/
二、路由系統
OK,開始我們的Django之旅吧!使用Django第一次實現Ht
1、每個路由規則對應一個view中的函數
在urls.py里添加RUL跳轉
from django.conf.urls import url from django.contrib import admin #首先得導入App里面的views(Django是MTV框架 Views保存路由規則) from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/', views.home), ]
並在App里views.py里添加函數
from django.shortcuts import render #Django 在返回的時候需要一層封裝,需要導入HttpResponse from django.shortcuts import HttpResponse # Create your views here. def home(request): #使用HttpRespons 封裝返回信息 return HttpResponse('<h1>Hello Home</h1>')
django中的路由系統和其他語言的框架有所不同,在django中每一個請求的url都要有一條路由映射,這樣才能將請求交給對一個的view中的函數去處理。其他大部分的Web框架則是對一類的url請求做一條路由映射,從而是路由系統變得簡潔。
通過反射機制,為django開發一套動態的路由系統Demo !
啟動:兩種方式一種直接在IDE運行另一種命令行啟動:python manage.py runserver 127.0.0.1:6666
測試訪問即可。(如果在里面加中文注釋不要忘記加編碼配置!)
那我要返回html呢?
#/usr/bin/env python #-*- coding:utf-8 -*- from django.shortcuts import render #Django 在返回的時候需要一層封裝,需要導入HttpResponse from django.shortcuts import HttpResponse # Create your views here. def home(request): #他內部做了幾步操作 #找到home.html #讀取home.html返回給用戶 return render(request,'home.html')
三、模板
上面已經可以正常的返回html了,我們要給他使用模板語言進行渲染怎么渲染呢?和上面的jinja2是一樣的。
#/usr/bin/env python #-*- coding:utf-8 -*- from django.shortcuts import render #Django 在返回的時候需要一層封裝,需要導入HttpResponse from django.shortcuts import HttpResponse # Create your views here. def home(request): #他內部做了幾步操作 #找到home.html #讀取home.html返回給用戶 #定義一個字典然后傳給render dic = {'name':'luotianshuai','age':'18','user_list':['shuai','ge','hen','shuai'],} return render(request,'home.html',dic)
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shuaige</title> </head> <body> <div style="background-color:red ;height: 100px"> {{ name }} {{ age }} </div> <div style="background-color:blue ;height: 100px"> <ul> {% for iterm in user_list %} <li> {{ iterm }} </li> {% endfor %} </ul> </div> <div style="background-color:green ;height: 100px"> {% if name == 'luotianshuai' %} <div style="background-color:red">Shuai</div> {% else %} <div style="background-color:blue">Ge</div> {% endif %} </div> </body> </html>
- {{ item }}
- {% for item in item_list %} <a>{{ item }}</a> {% endfor %}
forloop.counter
forloop.first
forloop.last - {% if ordered_warranty %} {% else %} {% endif %}
- 母板:{% block title %}{% endblock %}
子板:{% extends "base.html" %}
{% block title %}{% endblock %} - 幫助方法:
{{ item.event_start|date:"Y-m-d H:i:s"}}
{{ bio|truncatewords:"30" }}
{{ my_list|first|upper }}
{{ name|lower }}
縱然上面的方法不少但是還是不夠,所以就出現了自定義方法。
2、自定義模板語言
2.1、在app中創建templatetags模塊
2.3、創建任意 .py 文件,如:html_Template_Langureg.py
#!/usr/bin/env python #coding:utf-8 from django import template from django.utils.safestring import mark_safe from django.template.base import resolve_variable, Node, TemplateSyntaxError register = template.Library() @register.simple_tag def my_simple_time(v1,v2,v3): return v1 + v2 + v3 @register.simple_tag def my_input(id,arg): result = "<input type='text' id='%s' class='%s' />" %(id,arg,) return mark_safe(result)
2.3、在使用自定義simple_tag的html文件中最頂部導入之前創建的 xx.py(html_Template_Langureg.py) 文件名
{% load html_Template_Langureg %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shuaige</title> </head> <body> <div style="background-color:red ;height: 100px"> {{ name }} {{ age }} </div> <div style="background-color:blue ;height: 100px"> <ul> {% for iterm in user_list %} <li> {{ iterm }} </li> {% endfor %} </ul> </div> <div style="background-color:green ;height: 100px"> {% if name == 'luotianshuai' %} <div style="background-color:red">Shuai</div> {% else %} <div style="background-color:blue">Ge</div> {% endif %} </div> </body> </html>
2.4、在settings中配置當前app,不然django無法找到自定義的simple_tag
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ]
2.5、測試使用
{% load html_Template_Langureg %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shuaige</title> </head> <body> <div style="background-color:red ;height: 100px"> {{ name }} {{ age }} </div> <div style="background-color:blue ;height: 100px"> <ul> {% for iterm in user_list %} <li> {{ iterm }} </li> {% endfor %} </ul> </div> <div style="background-color:green ;height: 100px"> {% if name == 'luotianshuai' %} <div style="background-color:red">Shuai</div> {% else %} <div style="background-color:blue">Ge</div> {% endif %} </div> <div> {% my_simple_time 1 2 3 %} {% my_input 'id_name' 'arg_value' %} </div> </body> </html>
3、母板
首先了解下模板是什么概念?首先已博客園為例:
看下面的圖片,在點擊首頁、精華、候選、新聞、管住、我評、我贊的時候 上面、左側的紅色框體都沒有變,變得是中間的內容是怎么實現的呢?就是通過母版來實現的
我們創建一個母版 - 子版去繼承母版就可以了,子版里是變化的內容即可。
在templates目錄下面創建一個master目錄(統一用他吧),然后在master目錄下創建一個master_templates.html
看下模板的配置:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .header{ height: 48px; background-color: red; } .body{ background-color: #dddddd; } .body .menu{ background-color: green; float: left; width: 20%; } .body .content{ background-color: aquamarine; float: left; width:70%; } </style> </head> <body> <div class="header"><h1>LOGO</h1></div> <div class="body"> <div class="menu">左側菜單</div> <div class="content"> {#可變的子版內容,這個content和class content無關#} {% block content %} {% endblock %} </div> </div> </body> </html>
然后在看下子版的內容
{% extends 'master/master_templates.html' %} {% block content %} <h1>NAME LuoTianShuai</h1> {% endblock %}
extends 集成那個模板 ,在加一個block content 來書寫變化的內容。
3.2、增加URL路由和函數
def son(request): return render(request,'son_html.html')
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/', views.home), url(r'^son/', views.son), ]
效果圖:
母版最多允許出現一個母版(可以寫多個,但是建議不要寫多個)
4、導入標簽
哪有什么辦法可以,可以通過導入的方式
創建一個include目錄(名字可以隨意定義),下面創建需要的html文件,里面寫上要導入的內容
<h1>輸入組合</h1> <input type="text"/> <input type="text"/> <input type="text"/> <input type="text"/> <input type="text"/>
然后在html中導入
{% extends 'master/master_templates.html' %} {% block content %} <h1>NAME LuoTianShuai</h1> {% include 'include/simple_input.html' %} {% endblock %}
查看效果:
以后比如某些公共的模塊可以使用include的方式導入!很方便
三、Django靜態文件配置
把所有的靜態都放在static目錄下,比如:css、js、imgs、等
common.css里寫相關的css文件
然后在html里引用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/css/common.css"> {# 然后在模板里,我們也會寫一個block,如果子版里有需要使用自己的css樣式可以自己定義#} {% block css %} {% endblock %} </head> <body> <div class="header"><h1>LOGO</h1></div> <div class="body"> <div class="menu">左側菜單</div> <div class="content"> {#可變的子版內容,這個content和class content無關#} {% block content %} {% endblock %} </div> </div> {# 公共的js寫到母版中,如果某一個模板里使用自己的js,在寫一個block即可#} {% block js %} {% endblock %} </body> </html>
注:在模板里引入了相應的css和js之后,子版里是默認繼承的。如果某個子版想獨立使用它自己的js,我們可以通過:{% block css %} {% endblock %} || {% block js %} {% endblock %}來定義!
2、配置引入static目錄,在settings里,否則無法使用static目錄下的靜態文件,因為他找不到路徑!的需要告訴django
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), )
用戶登錄實例
1、創建兩個html,login.html & index.html
login.html(不要忘記導入bootstrap)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> <!--指定告訴ID用高版本的解析--> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! --> <!-- Bootstrap --> <!-- 新 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.4-dist/css/bootstrap.min.css"> </head> <body> <div style="width: 200px;"> <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" id="inputEmail3" placeholder="Email"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" class="form-control" id="inputPassword3" placeholder="Password"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Sign in</button> </div> </div> </form> </div> <!-- jQuery文件。務必在bootstrap.min.js 之前引入 --> <script src="/static/js/jquery-2.2.1.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="/static/plugins/bootstrap-3.3.4-dist/js/bootstrap.min.js"></script> </body> </html>
1.2、創建URL路由規則和函數
url
url(r'^login/', views.login),
函數
def login(request): return render(request,'login.html')
2.2、提交到哪里在哪里定義?
<form class="form-horizontal" action="/login/" method="post">
提交到在form表單中的action里定義:這里的/login/是URL,當咱們訪問URL的時候回給執行咱們定義的函數,前面和后面都要有/ 並且使用方法為post
咱們訪問的時候是使用的GET方式,當咱們提交的時候使用的是post請求!我們就可以判斷!
def login(request): #如果是GET請求 #如果是POST,檢查用戶輸入 #print request.method 來查看用戶是通過什么方式請求的 #還有個問題:當你POST的時候,會出現問題,現在臨時解決方法是:在seetings里注釋掉 ''' MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 注釋掉這一行 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ''' if request.method == 'POST': input_email = request.POST['email'] input_pwd = request.POST['pwd'] if input_email == 'luotianshuai@qq.com' and input_pwd == '123': #當登錄成功后給它跳轉,這里需要一個模塊from django.shortcuts import redirect #成功后跳轉到指定網址 return redirect('http://www.etiantian.org') else: #如果沒有成功,需要在頁面告訴用戶用戶名和密碼錯誤. return render(request,'login.html',{'status':'用戶名或密碼錯誤'}) #通過模板語言,來在login.html中添加一個status的替換告訴用戶<span>{{ status }}</span> return render(request,'login.html')
然后看下html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> <!--指定告訴ID用高版本的解析--> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! --> <!-- Bootstrap --> <!-- 新 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.4-dist/css/bootstrap.min.css"> </head> <body> <div style="width: 200px;"> <form class="form-horizontal" action="/login/" method="post"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" name="email" placeholder="Email"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" class="form-control" name="pwd" placeholder="Password"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Sign in</button> <span style="color: red;">{{ status }}</span> </div> </div> </form> </div> <!-- jQuery文件。務必在bootstrap.min.js 之前引入 --> <script src="/static/js/jquery-2.2.1.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="/static/plugins/bootstrap-3.3.4-dist/js/bootstrap.min.js"></script> </body> </html>
看下效果在登錄錯誤的時候(登錄成功會跳轉):
如果想跳轉到自己的頁面可以這么寫:
def login(request): #如果是GET請求 #如果是POST,檢查用戶輸入 #print request.method 來查看用戶是通過什么方式請求的 #還有個問題:當你POST的時候,會出現問題,現在臨時解決方法是:在seetings里注釋掉 ''' MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 注釋掉這一行 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ''' if request.method == 'POST': input_email = request.POST['email'] input_pwd = request.POST['pwd'] if input_email == 'luotianshuai@qq.com' and input_pwd == '123': #當登錄成功后給它跳轉,這里需要一個模塊from django.shortcuts import redirect #成功后跳轉到指定網址 return redirect('/son/') else: #如果沒有成功,需要在頁面告訴用戶用戶名和密碼錯誤. return render(request,'login.html',{'status':'用戶名或密碼錯誤'}) #通過模板語言,來在login.html中添加一個status的替換告訴用戶<span>{{ status }}</span> return render(request,'login.html')
四、Model基本操作和增、刪、改、查、實例
1、創建數據庫
1、創建model類
#/usr/bin/env python #-*- coding:utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. #這個類是用來生成數據庫表的,這個類必須集成models.Model class UserInfo(models.Model): #創建表的字段 email = models.CharField(max_length=16) #這個就表示去數據庫創建一個字符串類型的字段 pwd = models.CharField(max_length=32)#對於字符串類型的字段必須設置一個最大長度
2、注冊APP(在settings里面注冊,咱們上面已經注冊了,如果沒有注冊不能忘記要不然不能創建數據表)
3、執行命令
python manage.py makemigrations
python manage.py migrate
這一部分相當於生成一個源,相當於一個特殊的結構。
文件內容:
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-11 12:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UserInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.CharField(max_length=16)), ('pwd', models.CharField(max_length=32)), ], ), ]
然后:python manage.py migrate 會讀取這個數據庫結構生成數據庫表!
上一遍文章里已經有創建過超級用戶,我們可以通過配置admin來配置后台管理
#/usr/bin/env python #-*- coding:utf-8 -*- from django.contrib import admin # Register your models here. #導入app01模塊 from app01 import models #注冊咱們創建的類,通過他來訪問 admin.site.register(models.UserInfo)
打開網頁查看:
2、增刪改查
我們修改下代碼,讓他登錄成功之后跳轉到index頁面,然后讓index頁面返回所有的用戶信息
url:
url(r'^index/', views.index),
函數
def login(request): #如果是GET請求 #如果是POST,檢查用戶輸入 #print request.method 來查看用戶是通過什么方式請求的 #還有個問題:當你POST的時候,會出現問題,現在臨時解決方法是:在seetings里注釋掉 ''' MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 注釋掉這一行 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ''' if request.method == 'POST': input_email = request.POST['email'] input_pwd = request.POST['pwd'] if input_email == 'luotianshuai@qq.com' and input_pwd == '123': #當登錄成功后給它跳轉,這里需要一個模塊from django.shortcuts import redirect #成功后跳轉到指定網址 return redirect('/index/') else: #如果沒有成功,需要在頁面告訴用戶用戶名和密碼錯誤. return render(request,'login.html',{'status':'用戶名或密碼錯誤'}) #通過模板語言,來在login.html中添加一個status的替換告訴用戶<span>{{ status }}</span> return render(request,'login.html')
index
def index(request): #數據庫去數據 #數據和HTML渲染 #如果想使用數據庫,需要先導入(需要在開頭導入) from app01 import models #獲取UserInfo表中的數據,下面一行語句是固定搭配 user_info_list = models.UserInfo.objects.all() #user_info 列表,列表的元素就是一行.每一行有兩個字段:一個是email 一個pwd return render(request,'index.html',{'user_info_list':user_info_list},)
然后在html中循環通過模板語言進行渲染
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shuaige</title> </head> <body> <div> <table> <thead> <tr> <th>郵箱</th> <th>密碼</th> </tr> </thead> <tbody> {% for line in user_info_list %} <tr> <td>{{ line.email }}</td> <td>{{ line.pwd }}</td> </tr> {% endfor %} </tbody> </table> </div> </body> </html>
現在是沒有數據的我們可以現在后台添加幾個:
然后登陸測試下:
2、添加數據
在index.html中在加一個表單
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shuaige</title> </head> <body> <div> <form action="/index/" method="post"> <input type="text" name="em" /> <input type="text" name="pw" /> <input type="submit" value="添加" /> </form> </div> <div> <table> <thead> <tr> <th>郵箱</th> <th>密碼</th> </tr> </thead> <tbody> {% for line in user_info_list %} <tr> <td>{{ line.email }}</td> <td>{{ line.pwd }}</td> </tr> {% endfor %} </tbody> </table> </div> </body> </html>
函數
def index(request): #數據庫去數據 #數據和HTML渲染 #如果想使用數據庫,需要先導入(需要在開頭導入) from app01 import models if request.method =='POST': #添加數據 input_em = request.POST['em'] input_pw = request.POST['pw'] #創建數據也得用model models.UserInfo.objects.create(email=input_em,pwd=input_pw) #他就表示去創建一條數據 #獲取UserInfo表中的數據,下面一行語句是固定搭配 user_info_list = models.UserInfo.objects.all() #user_info 列表,列表的元素就是一行.每一行有兩個字段:一個是email 一個pwd return render(request,'index.html',{'user_info_list':user_info_list},)
登陸后測試:
3、查、刪除數據
要刪除肯定的先找到他,通過filter去找到,然后后面加delete刪除
models.UserInfo.objects.filter(email=input_em).delete() #找到email=input_em的數據並刪除
函數
def index(request): #數據庫去數據 #數據和HTML渲染 #如果想使用數據庫,需要先導入(需要在開頭導入) from app01 import models if request.method =='POST': #添加數據 input_em = request.POST['em'] input_pw = request.POST['pw'] #創建數據也得用model #models.UserInfo.objects.create(email=input_em,pwd=input_pw) #他就表示去創建一條數據 models.UserInfo.objects.filter(email=input_em).delete() #找到email=input_em的數據並刪除 #獲取UserInfo表中的數據,下面一行語句是固定搭配 user_info_list = models.UserInfo.objects.all() #user_info 列表,列表的元素就是一行.每一行有兩個字段:一個是email 一個pwd return render(request,'index.html',{'user_info_list':user_info_list},)
效果: