Django學(xué)習(xí)

一、Django簡介

Django是一個用python編寫的web框架(MVC架構(gòu))版本標(biāo)有LTS: 長期支持版本

1.MVC設(shè)計模式

一種設(shè)計模式,用業(yè)務(wù)邏輯使數(shù)據(jù)、界面顯示分離的方法組織代碼,將業(yè)務(wù)邏輯聚集到一個部件上,在改進和個性化界面與用戶交互的同時不需要重新編寫業(yè)務(wù)邏輯。(M:model V:view C:controller)

  • 核心思想: 解耦(更好從組織代碼,1個文件拆成5個文件,可以分攤風(fēng)險)

  • 優(yōu)點: 降低各模塊之間的耦合性,方便變更,更容易重構(gòu)代碼,最大程度實現(xiàn)了代碼的重用

2.MVT設(shè)計模式(Django)

本質(zhì)上和mvc差不多,也是各組件之間為了保持松耦合關(guān)系,只是定義不同

  • Model: 負責(zé)業(yè)務(wù)對象與數(shù)據(jù)庫(ORM)的對象
  • View: 負責(zé)業(yè)務(wù)邏輯,并在適當(dāng)?shù)臅r候調(diào)用Model和Template,相當(dāng)于C
  • Template: 負責(zé)把頁面展示給用戶

Django里還有一個url分發(fā)器(路由),主要用來將一個個url頁面的請求分發(fā)給不同的view進行處理,View在調(diào)用相應(yīng)的Model,和Template.

二、Django安裝

  1. 通過pip安裝(Python包管理器) (pip用法
$curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py   # 下載安裝腳本

$sudo -H python get-pip.py --no-wheel    # 運行安裝腳本(加上options忽略wheels)
# 安裝如果出現(xiàn)以下提示加上 --no-wheel
ERROR: Could not find a version that satisfies the requirement wheel (from versions: none)
ERROR: No matching distribution found for wheel
# 驗證安裝
$pip --version
# 卸載
$python -m pip uninstall pip
# 查看指定包的安裝位置
$pip show packageName

注意:用哪個版本的 Python 運行安裝腳本,pip 就被關(guān)聯(lián)到哪個版本,如果是 Python3 則執(zhí)行以下命令:

$sudo -H python3 get-pip.py    # 運行安裝腳本
  1. 安裝django (不指定的話,安裝很慢)
$pip install django==1.11.7 -i https://pypi.douban.com/simple/ tornado # 指定版本號 指定鏡像源

# 驗證
$pip list 
  1. 創(chuàng)建項目
$django-admin startproject projectName # 創(chuàng)建項目
$tree # 樹形查看項目結(jié)構(gòu)
$python manage.py startapp appName # 創(chuàng)建一個應(yīng)用

4.開啟服務(wù)

$python manager.py runserver [127.0.0.1:][8000] #啟動服務(wù) - 可以直接寫端口號 - 默認是8000

5.IDE打開要與manager.py同級, 打開projectName項目

三、Django文件解讀

1.settings.py(項目配置)

BASE_DIR  #項目的絕對路徑:也就是根路徑
SECRECT_KEY #秘鑰 - 用于生產(chǎn)環(huán)境
DEBUG #調(diào)試開關(guān) - 用于開發(fā)
ALLOWED_HOSTS = ["*"] #允許訪問的主機
INSTALLED_APPS = [...] #已經(jīng)安裝的app,django安裝的應(yīng)用
MIDDLEWARE = [...] #中間件
ROOT_URLCONF = '....urls' #根路由
TEMPLATES #模板
WSGI_APPLICATION #部署用的
DATABASES #數(shù)據(jù)庫
AUTH_PASSWORD_VALIDATORS #鑒權(quán)相關(guān)
LAUGUAFE_CODE = 'zh-hans' #語言編碼

2.urls.py(路由)

3.apps.py 應(yīng)用配置

4.admin.py 后臺管理

5.model.py 數(shù)據(jù)模型

6.tests.py 寫測試

7.sqlite

  • 輕量級嵌入式數(shù)據(jù)庫
  • 特點小,常用于Android ios wp
  • 數(shù)據(jù)庫常規(guī)操作和mysql很像
$python3 manage.py migrate # 數(shù)據(jù)庫遷移

四、路由管理

from django.contrib import admin
from django.urls import path

# 導(dǎo)入view
from App import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('test/', views.hello),  # 添加路由 - 對應(yīng)模塊下的方法
    path('html/', views.index)
]

# App/views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def hello(request):
    return HttpResponse('可還行') # 直接響應(yīng) - 也可以是html字符串 返回給瀏覽器會直接渲染

def index(request):
    return render(request, "index.html") # 渲染模板文件

五、Model數(shù)據(jù)模型

Django的models使用了ORM(Object Relational Mapping 對象關(guān)系映射)技術(shù),將業(yè)務(wù)邏輯進行了一個解耦合,在操作數(shù)據(jù)庫時無需關(guān)注什么數(shù)據(jù)庫,只需要調(diào)用對應(yīng)的對象和方法,就可以映射成對應(yīng)的sql語句去執(zhí)行。

相關(guān)文章https://www.bbsmax.com/A/KE5QXjPZJL/

1.創(chuàng)建一張表

DDL: 定義數(shù)據(jù)庫,Django里用models去定義一個數(shù)據(jù)庫模型 - 表

App/models.py
from django.db import models

# Create your models here.

# 新建一個Sduent模型 - student表
class Student(models.Model):
    name = models.CharField(max_length=16) #設(shè)置字段名稱
    age = models.IntegerField(default=1)

然后執(zhí)行出,表名稱 APP_Student

$python3 manage.py makemigrations # 生成用戶表
$python3 manage.py migrate # 數(shù)據(jù)庫遷移
2.新增數(shù)據(jù)
from django.shortcuts import render
from django.http import HttpResponse
import random

# 導(dǎo)入模型
from App.models import Student


# 新增用戶數(shù)據(jù)
def student(request):
    students = Student()
    students.name = 'tom %d' % random.randrange(90)
    students.save()

    return HttpResponse('success %s' % students.name)
3.查詢數(shù)據(jù)
from django.shortcuts import render
from django.http import HttpResponse
from django.core import serializers

import random

# 導(dǎo)入模型
from App.models import Student

# 獲取學(xué)生數(shù)
def getStudent():
    students = Student.objects.all()
    # 返回json序列化
    str_students = serializers.serialize("json", students)

    return HttpResponse(str_students)
// 會返回如下信息
[{
    "model": "App.student",
    "pk": 1,
    "fields": {
        "name": "tom 39",
        "age": 1
    }
}]
4.更新數(shù)據(jù)
# 更新學(xué)生數(shù)據(jù)
def updateStudent(req):
    # 先查后保存
    student = Student.objects.get(id=1)
    student.name = 'test_update_name'
    student.save()

    return HttpResponse('update success')
5.刪除數(shù)據(jù)
# 刪除學(xué)生數(shù)據(jù)
def deleteStudent(req):
    student = Student.objects.get(id=1)
    student.delete()

    return HttpResponse('delete success')
6.鏈接mysql數(shù)據(jù)庫
  1. 首先修改settings.py下的 DATABASES
DATABASES = {
    # mysql
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangoStudy', # dbName
        'USER': 'admin',
        'PASSWORD': 'admin',
        'HOST': '127.0.0.1',
        'port': '3306'
    }
}
  1. 安裝mysql驅(qū)動

    (1)mysqlclient: 對mysql有要求,需要存在指定位置的配置文件

    (2)python-mysql: 支持python2

    (3) pymysql: 這個都支持--- 常用

  2. 執(zhí)行shell

$python3 manage.py makemigrations
$python3 manage.py migrate

如果報: raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.version)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

到django /db/mysql下把base.py如下代碼注釋掉:

# base.py
# if version < (1, 3, 13):
#     raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

如果報: query = query.decode(errors='replace') AttributeError: 'str' object has no attribute 'decode'

修改 operations.py, 將decode 修改為 encode

#query = query.decode(errors='replace')
query = query.encode(errors='replace')

如果開啟服務(wù)報: raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password") RuntimeE

執(zhí)行該條命令

$pip install cryptography
7.數(shù)據(jù)庫操作
  • 外鍵約束
# models.py
from django.db import models

# Create your models here.

# 年級表
class Grade(models.Model):
    name = models.CharField(max_length=32)


# 新建一個Sduent模型 - student表
class Student(models.Model):
    name = models.CharField(max_length=16) #設(shè)置字段名稱
    age = models.IntegerField(default=1)
    # 級聯(lián)關(guān)系 2.0后定義外鍵和一對一的關(guān)系時要加上這個參數(shù)
    grade_id = models.ForeignKey(Grade, on_delete=models.CASCADE) 
    
    
# 相關(guān)參數(shù)
on_delete=None,               # 刪除關(guān)聯(lián)表中的數(shù)據(jù)時,當(dāng)前表與其關(guān)聯(lián)的field的行為
on_delete=models.CASCADE,     # 刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)也刪除
on_delete=models.DO_NOTHING,  # 刪除關(guān)聯(lián)數(shù)據(jù),什么也不做
on_delete=models.PROTECT,     # 刪除關(guān)聯(lián)數(shù)據(jù),引發(fā)錯誤ProtectedError

models.ForeignKey('關(guān)聯(lián)表', on_delete=models.SET_NULL, blank=True, null=True)

on_delete=models.SET_NULL,    # 刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)的值設(shè)置為null(前提FK字段需要設(shè)置為可空,一對一同理)

models.ForeignKey('關(guān)聯(lián)表', on_delete=models.SET_DEFAULT, default='默認值')
on_delete=models.SET_DEFAULT, # 刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)的值設(shè)置為默認值(前提FK字段需要設(shè)置默認值,一對一同理)

# views.py
def getGradeName(req):
    student = Student.objects.get(id=3)
    grade = student.grade_id
    print(grade.name) # 二年級 關(guān)聯(lián)到了grade表

    return HttpResponse(req)

# 通過外鍵查詢所有學(xué)生名單
def getStudentsName(req):
    # 先查年級
    grade = Grade.objects.get(name='一年級')
    students = grade.student_set.all()

    return render(req, 'student.html', context={ 'students': students })

六、template模板語法

1.基本語法
# 返回字典對象
return render(request, 'contexts.html', context = { "name": "xiaoming", "age": 12 })
# 這個過程其實是處理好的html字符串返回給客戶端
# 利用loader.get_template('index.html').render(context=context)
  
# html
<h1>{{ name }}</h1>
<h2>{{ age }}</h2>
2.for循環(huán)
# 渲染一個列表
 return render(request, 'list.html', context = { "students": students})

# list.html
<!-- 渲染模板列表 -->
<ul>
    {% for student in students %}
       <li>{{ student.name }}</li>
    {% endfor %}
</ul>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容