1. 程式人生 > ><Django> 高級(其他知識點)

<Django> 高級(其他知識點)

onf time_zone 分組 根據 mage 註冊 mixin 中間鍵 tip

1. 管理靜態文件

  什麽是靜態文件?

    項目中的CSS、圖片、js都是靜態文件

配置靜態文件(settings.py)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

# 用於隱藏(偽裝),配置更改(邏輯顯示路徑)
STATIC_URL = ‘/static/‘
# 靜態文件的存放路徑(真實路徑)
STATICFILES_DIRS = [
	os.path.join(BASE_DIR, ‘static‘),
]

創建static文件夾,在這個文件夾下創建應用名的文件夾(類似模板的創建)

技術分享圖片

配置數據庫,為了不用遷移,還是用以前的

DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘NAME‘: ‘test2‘,
        ‘USER‘:‘root‘,
        ‘PASSWORD‘:‘‘,
        ‘HOST‘:‘localhost‘,
        ‘POST‘:‘3306‘,
    }
}

添加APP等操作就不提了 

views.py

from django.shortcuts import render

# Create your views here.

def index(request):
	return render(request,‘booktest/index.html‘) 

根urls.py

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^‘, include(‘booktest.urls‘)),
]

app中urls.py

from django.conf.urls import url,include
from booktest import views
urlpatterns = [
    url(r‘^$‘, views.index),
]

index.html

{# 加載模塊#}
{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>index</title>
</head>
<body>
{#直接通過硬編碼寫死的路徑進行調用#}
<img src="/static/booktest/a1.jpg" alt="圖片1" height="300" width="500">
<br>
{#類似反向解析,不要使用硬編碼寫死,跟上面效果一致,改了static_url 這個會跟著變#}
<img src="{% static ‘booktest/a1.jpg‘ %}" alt="圖片1" height="300" width="500">
</body>
</html>

  效果

技術分享圖片

2. 中間鍵

  默認創建項目settings.py中的文件,可以自己配置

  作用:是一個輕量級、底層的插件系統,可以介入Django的請求和響應處理過程,修改Django的輸入或輸出

  激活:添加到Django配置文件中的MIDDLEWARE_CLASSES元組中

  面向切面編程Aspect Oriented Programming(AOP):針對業務處理過程中的切面進行提取,它所面對的是處理過程中的某個步驟或階段,以獲得邏輯過程中各部分之間低耦合性的隔離效果。

  Django面向切面編程(類似,但也不全是)就是中間件

  請求request→中間件1→url→中間鍵2→view→中間鍵3→Template→中間鍵4→返回response

  Django本質:一個獨立的python類,可以定義下面方法中的一個或多個

  • _init _:無需任何參數,服務器響應第一個請求的時候調用一次,用於確定是否啟用當前中間件(只執行一次)
  • process_request(request):執行視圖之前被調用,在每個請求上調用,返回None或HttpResponse對象(中間鍵1)
  • process_view(request, view_func, view_args, view_kwargs):調用視圖之前被調用,在每個請求上調用,返回None或HttpResponse對象(中間件2)
  • process_template_response(request, response):在視圖剛好執行完畢之後被調用,在每個請求上調用,返回實現了render方法的響應對象(中間鍵3)
  • process_response(request, response):所有響應返回瀏覽器之前被調用,在每個請求上調用,返回HttpResponse對象(中間鍵4)
  • process_exception(request,response,exception):當視圖拋出異常時調用,在每個請求上調用,返回一個HttpResponse對象(中間鍵3改,出錯不調用模板,直接返回的中間鍵,例404)

使用中間件,可以幹擾整個處理過程,每次請求中都會執行中間件的這個方法

步驟

  步驟一:寫好類的方法(上述五種)

  步驟二:將中間件註冊在settings.py

演示:

  在APP中創建一個MyException.py文件

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin


class MyException(MiddlewareMixin):
	def process_exception(self, request, exception):
		# 出現異常,返回異常響應信息
		return HttpResponse(exception)

 技術分享圖片 

settings.py中註冊

MIDDLEWARE = [
	‘booktest.MyException.MyException‘,
	‘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‘,
]

views.py(定義視圖)

from django.http import HttpResponse
def myExp(request):
	# 故意定義錯誤
	a1 = int(‘abc‘)
	return HttpResponse(‘hello‘) 

urls.py

    url(r‘^myexp$‘, views.myExp),

  效果

技術分享圖片

3 上傳文件

  需要依賴pillow包

  • 當Django在處理文件上傳的時候,文件數據被保存在request.FILES
  • FILES中的每個鍵為<input type="file" name="" />中的name
  • 註意:FILES只有在請求的方法為POST 且提交的<form>帶有enctype="multipart/form-data" 的情況下才會包含數據。否則,FILES 將為一個空的類似於字典的對象

settings.py

# 上傳圖片的存儲路徑
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")

 

在static中創建目錄media存儲上傳文件

技術分享圖片

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
import os
# Create your views here.

# 上傳文件界面
def uploadPic(request):
	return render(request, ‘booktest/uploadPic.html‘)

# 接受圖片
def	uploadHandle(request):
	if request.method == "POST":
		# 接收上傳的圖片
		pic1 = request.FILES[‘pic1‘]
		# 名字:絕對路徑(圖片存儲路徑)+項目名+文件名
		fname = os.path.join(settings.MEDIA_ROOT,pic1.name)
		with open(fname, ‘wb‘) as pic:
			# 一點一點讀
			for c in pic1.chunks():
				# 一點一點寫
				pic.write(c)
		return HttpResponse("ok:%s<img src=‘/static/media/%s‘>"%(fname,fname))
	else:
		return HttpResponse("error")

urls.py

    url(r‘^uploadPic$‘, views.uploadPic),
    url(r‘^uploadHandle$‘, views.uploadHandle),

uploadPic.html 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>上傳文件</title>
</head>
<body>
{#提交的另一個視圖#}
<form action="/uploadHandle" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="pic1"><br>
    <hr>
    <input type="submit" value="上傳">
</form>
</body>
</html>

  效果

技術分享圖片

上傳後

技術分享圖片

4 站點管理

  默認啟動admin模塊

  技術分享圖片

 使用方法:

  步驟一:創建超級管理員

python manage.py createsuperuser

  賬號:root

  郵箱:隨便填

  密碼:123root123

  步驟二:管理模型類

admin.py

from django.contrib import admin
from django.db import models
# Register your models here.
class UesrInfo(models.Model):
	uname = models.CharField(max_length=10)
	upwd = models.CharField(max_length=40)
	isDelete = models.BooleanField()

註:需要在models.py中把文件模型先寫好,一起生成遷移文件,遷移,單獨遷移會存在問題

生成遷移文件----生成模型類相關SQL語句

python manage.py makemigrations

 執行遷移----根據SQL語句生成相關表

python manage.py migrate

  

settings.py設置中文

LANGUAGE_CODE = ‘zh-Hans‘
TIME_ZONE = ‘Asia/Shanghai‘

  

註冊admin.py

admin.site.register(BookInfo)

  效果

技術分享圖片

admin.py(在前面入門的例子中有寫)

from django.contrib import admin
from django.db import models
from .models import *
# 關聯註冊 (內部停靠),
# class HeroInfoline(admin.StackedInline):
# 表格效果
class HeroInfoline(admin.TabularInline):
    # 嵌入哪個類(一對多中,多的部分)
    model = HeroInfo
    # 增加一本圖書的時候,還可以增加2個heroinfo
    extra = 2
 
class BookInfoAdmin(admin.ModelAdmin):
    # 列表頁顯示
    # 列表
    list_display = [‘id‘, ‘btitle‘, ‘bpub_date‘]
    # 過濾
    list_filter = [‘btitle‘]
    # 搜索(支持模糊查詢)
    search_fields = [‘btitle‘]
    # 分頁(每頁顯示多少條)
    list_per_page = 10
 
    # 添加頁,修改頁
    # 展示列表fields 和  fieldsets只能同時存在一個,功能一致
    # fields = [‘bpub_date‘,‘btitle‘]
    # 分組
    fieldsets = [
        (‘base‘, {‘fields‘: [‘btitle‘]}),
        (‘super‘, {‘fields‘: [‘bpub_date‘]})
    ]
 
    # 關聯註冊第二步,關聯起來(一對多中,一的部分)
    inlines = [HeroInfoline]
 
 
 
# admin.site.register(BookInfo)
# 註冊
admin.site.register(BookInfo, BookInfoAdmin)
admin.site.register(HeroInfo)

  效果

技術分享圖片

可以使用裝飾器註冊(其實也一樣)----只能在繼承admin.ModelAdmin時使用裝飾器

# admin.site.register(BookInfo, BookInfoAdmin)
@admin.register(BookInfo)
class BookInfoAdmin(admin.ModelAdmin):

5 分頁

  • Django提供了一些類實現管理數據分頁,這些類位於django/core/paginator.py中

Paginator對象

  • Paginator(列表,int):返回分頁對象,參數為列表數據,每面數據的條數

屬性

  • count:對象總數
  • num_pages:頁面總數
  • page_range:頁碼列表,從1開始,例如[1, 2, 3, 4]

方法

  • page(num):下標以1開始,如果提供的頁碼不存在,拋出InvalidPage異常(無效頁碼)

異常exception

  • InvalidPage:當向page()傳入一個無效的頁碼時拋出
  • PageNotAnInteger:當向page()傳入一個不是整數的值時拋出
  • EmptyPage:當向page()提供一個有效值,但是那個頁面上沒有任何對象時拋出

Page對象

  • Paginator對象的page()方法返回Page對象,不需要手動構造

屬性

  • object_list:當前頁上所有對象的列表(當前頁所有對象)
  • number:當前頁的序號,從1開始
  • paginator:當前page對象相關的Paginator對象

方法

  • has_next():如果有下一頁返回True
  • has_previous():如果有上一頁返回True
  • has_other_pages():如果有上一頁或下一頁返回True
  • next_page_number():返回下一頁的頁碼,如果下一頁不存在,拋出InvalidPage異常
  • previous_page_number():返回上一頁的頁碼,如果上一頁不存在,拋出InvalidPage異常
  • len():返回當前頁面對象的個數
  • 叠代頁面對象:訪問當前頁面中的每個對象

<Django> 高級(其他知識點)