Python筆記16(Django介紹與安裝)

1、Django介紹

Django是一個開放源代碼的Web應用框架,由Python寫成。採用了MVC的框架模式,即模型M,視圖V和控制器C。它最初是被開發來用於管理勞倫斯出版集團旗下的一些以新聞內容爲主的網站的,便是CMS(內容管理系統)軟件。並於2005年7月在BSD許可證下發布。這套框架是以比利時的吉普賽爵士吉他手Django Reinhardt來命名的。css

版本:1.8.三、1.11.x (推薦)、2.xhtml

2、Django安裝

官網下載地址:https://www.djangoproject.com/download/python

pip3 install django==1.11.11 安裝

pip3 install django==1.11 -i https://pypi.tuna.tsinghua.edu.cn/simple 指定安裝源

pip3 uninstall django 卸載

pip3 list 查看當前Python解釋器安裝了哪些第三方包

3、建立Django項目

一、命令行建立

django-admin startproject s21django
在當前目錄下建立一個名爲 s21django 的Django項目 mysql

二、PyCharm建立

第一步:選擇File>>New Project;web

第二步:選擇Django,點擊Create;正則表達式

第三步:選擇在新的窗口中打開,點擊ok;sql

建立完成後目錄結構:
數據庫

#目錄結構介紹
mysite/
├── manage.py  # 管理文件
└── mysite  # 項目目錄
    ├── __init__.py
    ├── settings.py  # 配置
    ├── urls.py  # 路由 --> URL和函數的對應關係
    └── wsgi.py  # runserver命令就使用wsgiref模塊作簡單的web server

啓動Django項目:
django

更改端口:
編程

 

三、建立第一個Django項目:

index文件內容以下:

 urls.py文件內容以下:

views.py文件內容以下:

settings.py文件內容以下:

"""
Django settings for mysite2 project.

Generated by 'django-admin startproject' using Django 1.11.11.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# BASE_DIR是我當前Django項目的根目錄
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'vj5z&5kl+%sk@a%rbfl=z*&!(6amfme758_cw6ke6&ymv=^gyq'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

# 當前Django項目按照的app都有哪一些
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    #'app02' # 簡便寫法 將咱們建立的app02在Django項目註冊一下
]

MIDDLEWARE = [
    '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',
]

ROOT_URLCONF = 'mysite2.urls'

# 全部和html文件相關的配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # Django項目中用到的html文件要去哪裏找
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite2.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
setting.py文件

四、啓動Django項目

1)PyCharm裏面啓動:
點綠色的小三角
2)命令行啓動
a. 切換到項目目錄下!
b. python manage.py runserver
 python manage.py runserver 127.0.0.1:8090
   python manage.py runserver 8091

五、建立APP

1) 在PyCharm建立,只能在開始建立項目的時候建立一次,以後再建立須要在命令行建立。
2)在命令行建立
a. 切換到項目目錄下!
b. python manage.py startapp app名字
c. 在settings.py裏面註冊你新建立的那個app

4、知識點

一、request相關的知識點:

   1. request.method  --> 獲取用戶請求的方法
- GET --> 表示用戶向我要一個頁面這種操做
- POST --> 表示用戶向我發送一些數據
2. request獲取URL中的參數
/xx/?name=alex&age=9000
request.GET --> 大字典
- request.GET['name'] --> 不推薦 取不到值會報錯
- request.GET.get("name","") --> 推薦 能夠設置默認值
3. request.POST --> 一個大字典,存的是用戶post發過來的數據
1. request.POST['key'] --> 不推薦
2. request.POST.get('key', '默認值')

二、基本視圖函數(views.py)

   1. 基礎必會三件套
from django.shortcuts import HttpResponse, render, redirect
1. HttpResponse('字符串') 用來返回具體的字符串
2. render(request, 'xx.html') 用戶返回一個html頁面
3. redirect 重定向 跳轉

三、基本路由系統(urls.py)

   1. 路由是一個有順序的列表,從上到下去匹配
   2. 路由的路徑是根據正則表達式來匹配的

四、基本引擎模板

基本模板引擎(templates/xx.html) 
1. render(request, 'xx.html', {"k": "v"})
2. 經常使用語法:
1. {{ 變量名 }}
2. {{ 變量名.key }}

3. for循環
{% for x in xx %}
{{x}}
{% endfor %}
4. if判斷
{% if 條件 %}
...
{% else %}
...
{% endif %}

五、MVC與MTV(瞭解便可)

1)MVC

MVC,全名是Model View Controller,是軟件工程中的一種軟件架構模式,把軟件系統分爲三個基本部分:模型(Model)、視圖(View)和控制器(Controller),具備耦合性低、重用性高、生命週期成本低等優勢。

2)MTV

Django框架的設計模式借鑑了MVC框架的思想,也是分紅三部分,來下降各個部分之間的耦合性。

Django框架的不一樣之處在於它拆分的三部分爲:Model(模型)、Template(模板)和View(視圖),也就是MTV框架。

Model(模型):負責業務對象與數據庫的對象(ORM)

Template(模版):負責如何把頁面展現給用戶

View(視圖):負責業務邏輯,並在適當的時候調用Model和Template

此外,Django還有一個urls分發器,它的做用是將一個個URL的頁面請求分發給不一樣的view處理,view再調用相應的Model和Template

 

 

 

4、登陸功能實現

1)在urls.py文件中添加訪問url和將要執行的函數對應關係;

2)在views.py中添加login函數;

3)在templates下添加login.html頁面;

 4)完善views.py中添加login函數:

備註:報錯403,找到如下代碼註釋。

5、Django項目使用靜態文件的配置

一、在項目目錄下新建一個保存靜態文件的文件夾,把bootstrap包放在此路徑下;

二、settings.py中加上相應的配置項,告訴Django在新建的路徑下去找靜態文件;

三、在HTML頁面中使用剛纔配置的靜態文件,使用/static/... 來引用;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
<h1 style="text-align: center">登陸頁面</h1>
<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4" style="margin-top: 70px">
            <form action="/login/" method="post">
                <div class="form-group">
                    <label for="exampleInputEmail1">用戶名</label>
                    <input type="text" name="username" class="form-control" id="exampleInputEmail1" placeholder="用戶名">
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">密碼</label>
                    <input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="密碼">
                </div>
                <button type="submit" class="btn btn-default">登陸</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

 6、ORM

一、ORM介紹

1. 用pymysql鏈接MySQL數據庫查詢數據
1. import pymysql
2. 創建鏈接
3. 獲取光標
4. 執行SQL語句
5. 獲取數據
6. 關閉光標
7. 關閉鏈接
2. 使用pymysql鏈接數據庫缺點:
1. 麻煩
2. 本身寫SQL語句!!! 執行效率不高
3. 使用ORM工具鏈接數據庫
- 優勢:
1. 不用本身寫SQL語句!!! 開發效率高
- 缺點:
1. 執行效率不高
4. 什麼是ORM?
對象關係映射(英語:(Object Relational Mapping,簡稱ORM,或O/RM,或O/R mapping),是一種程序技術,用於實現面向對象編程語言裏不一樣類型系統的數據之間的轉換

[1]

。從效果上說,它實際上是建立了一個可在編程語言裏使用的--「虛擬對象數據庫」。
   1)對象關係映射

類 數據表
屬性 字段
對象 數據行

5. ORM的使用
   1. 操做數據表
   2. 操做數據行
6. Django中如何使用ORM
1. 告訴Django鏈接哪一個MySQL數據庫(settings.py)
2. 告訴Django用pymysql鏈接MySQL數據庫 (默認用的是MySQLDB 這個是在python2使用的模塊)
3. 去app/models.py裏面建立類
4. 讓Django去數據庫幫我建立類對應的數據表
1. python manage.py makemigrations --> 記錄models.py的任何改動 記錄在migrations目錄下
2. python manage.py migrate --> 將變動記錄翻譯成SQL語句,去數據庫執行
7. ORM單表的增刪改查
1. 查詢
models.Publisher.objects.all() --> 查詢全部的出版社數據
models.Publisher.objects.get(id=1) --> 查詢id=1的那個出版社
2. 增長
models.Publisher.objects.create(name='xx') --> 建立一個名爲xx的出版社
3. 刪除
models.Publisher.objects.get(id=2).delete() --> 刪除id=2的那個出版社
4. 編輯
obj = models.Publisher.objects.get(id=2) --> 找到要編輯的對象
obj.name = "新值" --> 修改
obj.save()

二、Django中如何使用ORM(配置Sqlite3步驟)

1)告訴Django鏈接sqlite數據庫(settings.py);

2)在migrations下的_init_.py中,不須要添加任何內容(由於默認用的是sqlite3);

3)去app/models.py裏面建立類;

4)讓Django去數據庫幫我建立類對應的數據表;

5)在pycharm中鏈接sqlite3數據庫;

6)若是以前沒有鏈接過,須要先下載一下,點擊藍色字體的download;

7)能夠在file下,找到sqlite3文件的路徑或者直接點擊ok後,把項目目錄下的sqlite3直接拖動到右側打開的數據庫中;

 

三、Django中如何使用ORM(配置Mysql步驟)

1)告訴Django鏈接哪一個MySQL數據庫(settings.py);

2)告訴Django用pymysql鏈接MySQL數據庫 (默認用的是MySQLDB 這個是在python2使用的模塊);

3)去app/models.py裏面建立類;

4)讓Django去數據庫幫我建立類對應的數據表;

四、建立圖書管理系統

1)使用pycharm自帶的數據庫工具:

選擇Database>>Data Sourse>>MySQL;

點擊Download,下載驅動;

 輸入主機、數據庫名、用戶名、密碼,測試鏈接成功後,點擊ok;

五、出版社管理系統

1)urls.py文件

"""mysite2 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
# from django.contrib import admin
from app01 import views

#用戶訪問url和將要執行函數的對應關係
urlpatterns = [
    # url( r'^admin/', admin.site.urls ),
    url( r'^index/$', views.index ),
    url( r'^login/$',views.login),
    # 出版社列表頁
    url(r'publisher_list/',views.publisher_list),
    # 添加出版社
    url(r'add_publisher/',views.add_publisher),
    # 刪除出版社
    url(r'delete_publisher/',views.delete_publisher),
    # 編輯出版社
    url(r'edit_publisher/',views.edit_publisher),
]

2)views.py文件

from django.shortcuts import render

# Create your views here.

from django.shortcuts import HttpResponse, render ,redirect
from app01 import models

#定義一些用戶請求處理的函數
def index(request):
    """
    :param request: 全部跟用戶請求相關的數據都封裝到了一個名爲request的對象中
    :return:
    """
    # print(request.method) # 獲取到用戶請求的方法
    # print(request.path_info) # 拿到用戶請求的路徑
    # 本身找文件打開而後讀取內容
    # with open('index.html','rb') as f:
    #     data = f.read()
    # return HttpResponse(data)
    #Django幫我打開html文件,而後把文件裏面的內容讀取出來給用戶返回
    return render(request,"index.html")

# 登陸頁面
def login(request):
    # 根據用戶發送請求的方法不一樣,作不一樣的操做
    print(request.method)
    if request.method == "POST":
        # 表示用戶給我提交用戶名和密碼數據了
        # 從request中取用戶 post 過來的數據
        print(request.POST)  # 是一個大字典
        # 用戶名密碼正確性校驗
        username = request.POST.get("username", "")
        pwd = request.POST.get("password", "")
        if username == "admin" and pwd == "123456":
            # 登錄成功
            # return HttpResponse("登錄成功")
            # 跳轉到index頁面,讓用戶的瀏覽器去訪問新的頁面(index頁面)
            return redirect("/index/")
        else:
            # 登陸失敗
            return HttpResponse("登陸失敗")
    # 給用戶返回一個頁面 用來作登陸
    return render(request, 'login.html')

# 出版社列表
def publisher_list(request):
    # 一、查詢出全部的出版社數據
    data = models.Publisher.objects.all()
    print(data)
    # 二、在頁面上顯示、將頁面數據返回給用戶
    return render(request,"publisher_list.html",{"data":data})

# 添加出版社
def add_publisher(request):
    # 當請求方法是POST的時候,表示用戶填寫完成出版社名字 給我發數據了
    if request.method == "POST":
        # 一、取到用戶發送的數據
        publisher_name = request.POST.get("publisher_name")
        # 二、取數據庫存儲
        models.Publisher.objects.create(name = publisher_name)
        # 三、給用戶返回響應, 讓用戶跳轉到出版社列表頁面
        return redirect("/publisher_list/")
    return render(request,"add_publisher.html")

# 刪除出版社
def delete_publisher(request):
    print(request.GET)
    # 一、取到用戶要刪除的那一條數據
    delete_id = request.GET.get("id")
    # 二、去數據庫刪除掉
    models.Publisher.objects.get(id = delete_id).delete()
    # 三、刪除成功以後, 再跳轉回出版社列表頁面
    return redirect("/publisher_list/")

# 編輯出版社
def edit_publisher(request):
    # 當請求方式是POST時,表示用戶已經修改完成 給我發修改以後的數據了
    if request.method == "POST":
        # 用戶提交過來的數據
        edit_id = request.POST.get("id")
        new_publisher_name = request.POST.get("publisher_name")
        # 去修改數據庫中指定出版社的name字段的值
        # 先根據edit_id找到要編輯的出版社
        obj = models.Publisher.objects.get(id = edit_id)
        # 修改出版社的name
        obj.name = new_publisher_name
        # 將改動同步到數據庫
        obj.save()
        # 編輯成功,跳轉到出版社列表頁米愛你
        return redirect("/publisher_list/")


    # 一、獲取用戶要編輯的出版社id
    edit_id = request.GET.get("id")
    # 二、根據id去數據庫找到這條記錄
    obj = models.Publisher.objects.get(id = edit_id)
    # 三、在頁面上展現原來出版社名字
    return render(request,"edit_publisher.html",{"publisher":obj})

3)查看出版社頁面publisher_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表頁面</title>
</head>
<body>
<h1>出版社列表</h1>
<p><a href="/add_publisher/">添加新出版社</a></p>
<table border="1">
    <thead>
    <tr>
        <th>序號</th>
        <th>出版社id</th>
        <th>出版社名稱</th>
        <th>操做</th>
    </tr>
    </thead>
    <tbody>
    <!-- 按照Django tempalte的特殊語法 寫特殊符號 用來替換數據-->
    {% for obj in data %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ obj.id }}</td>
            <td>{{ obj.name}}</td>
            <td>
                <a href="/edit_publisher/?id={{ obj.id }}">編輯</a>
                <a href="/delete_publisher/?id={{ obj.id }}">刪除</a>
            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

4)添加出版社頁面add_publisher.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加出版社</title>
</head>
<body>
<form action="/add_publisher/" method="post">
    <input type="text" name="publisher_name" placeholder="新出版社名字">
    <button type="submit">添加</button>
</form>
</body>
</html>

5)編輯出版社頁面edit_publisher.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>編輯出版社</title>
</head>
<body>
<form action="/edit_publisher/" method="post">
    <input type="text" name="id" value="{{ publisher.id }}" style="display: none">
    <input type="text" name="publisher_name" value="{{ publisher.name }}">
    <button type="submit">提交</button>
</form>
</body>
</html>
相關文章
相關標籤/搜索