Django入門與實戰

第1章 介紹課程目標及學習內容

  • 1-1 課程介紹;

第2章 課前準備

  • 2-1 課前準備;

第3章 開發環境搭建

  • 3-1 開發環境搭建;

第4章 建立項目及應用

  • 4-1 建立項目,並瞭解項目目錄下的部分文件的做用;
  • 4-2 settings.py配置文件詳解
  • 4-3 建立應用,並瞭解應用目錄下各個文件的做用,同時建立一個頁面響應;

第5章 第一個Template

  • 5-1 配置URL;
  • 5-2 開發第一個Template;

第6章 Models

  • 6-1 Models;

第7章 Admin

  • 7-1 Admin;

第8章 完善博客

  • 8-1 博主頁面開;
  • 8-2 博客文章頁面開發;
  • 8-3 Django模板中的超連接配置;
  • 8-4 博客撰寫頁面開發(一);
  • 8-5 博客撰寫頁面開發(二);

第9章 補充內容

  • 9-1 Templates過濾器;
  • 9-2 Django shell;
  • 9-3 Admin加強;

第10章 課程總結

  • 10-1 課程總結;

第1章 介紹課程目標及學習內容

1-1 課程介紹

PS:任何場合不要忘記說謝謝|謝謝你!css

第2章 課前準備

2-1 課前準備

Django的官方網站;https://www.djangoproject.com/html

第3章 開發環境搭建

3-1 開發環境搭建

  • pip install(推薦)l;
  • 源碼安裝;

安裝Django:前端

    url:www.djangoproject.compython

一、pip install Django==1.10.2程序員

二、下載源碼,進入根目錄執行python setup.py installweb

判斷是否安裝成功:python -m django --versionsql

https://www.djangoproject.com/download/shell

Python官網:www.python.org數據庫

Microsoft Windows [Version 10.0.17134.1]
(c) 2018 Microsoft Corporation. All rights reserved.

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>django-admin

Type 'django-admin help <subcommand>' for help on a specific subcommand.


Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver
Note that only Django core commands are listed as settings are not prope
rly configured (error: Requested setting INSTALLED_APPS, but settings ar
e not configured. You must either define the environment variable DJANGO
_SETTINGS_MODULE or call settings.configure() before accessing settings.
).

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>clear
'clear' is not recognized as an internal or external command,
operable program or batch file.

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>django-admin

Type 'django-admin help <subcommand>' for help on a specific subcommand.


Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver
Note that only Django core commands are listed as settings are not prope
rly configured (error: Requested setting INSTALLED_APPS, but settings ar
e not configured. You must either define the environment variable DJANGO
_SETTINGS_MODULE or call settings.configure() before accessing settings.
).

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>
Django2.1安裝日誌

第4章 建立項目及應用

4-1 建立項目,並瞭解項目目錄下的部分文件的做用;

Django的啓動操做日誌;

Microsoft Windows [Version 10.0.17134.1]
(c) 2018 Microsoft Corporation. All rights reserved.

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>django-admin

Type 'django-admin help <subcommand>' for help on a specific subcommand.


Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver
Note that only Django core commands are listed as settings are not prope
rly configured (error: Requested setting INSTALLED_APPS, but settings ar
e not configured. You must either define the environment variable DJANGO
_SETTINGS_MODULE or call settings.configure() before accessing settings.
).

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>django-admin startproje
ct myblog

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>cd myblog

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>dir
 Volume in drive C has no label.
 Volume Serial Number is B2D2-AA19

 Directory of C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog

08/11/2018  12:45 PM    <DIR>          .
08/11/2018  12:45 PM    <DIR>          ..
08/11/2018  12:45 PM               553 manage.py
08/11/2018  12:45 PM    <DIR>          myblog
               1 File(s)            553 bytes
               3 Dir(s)  91,029,090,304 bytes free

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py


Type 'manage.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[auth]
    changepassword
    createsuperuser

[contenttypes]
    remove_stale_contenttypes

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
 runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly u
ntil you apply the migrations for app(s): admin, auth, contenttypes, ses
sions.
Run 'python manage.py migrate' to apply them.
August 11, 2018 - 12:47:54
Django version 2.1, using settings 'myblog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[11/Aug/2018 12:48:02] "GET / HTTP/1.1" 200 16348
[11/Aug/2018 12:48:02] "GET /static/admin/css/fonts.css HTTP/1.1" 200 42
3
[11/Aug/2018 12:48:02] "GET /static/admin/fonts/Roboto-Bold-webfont.woff
 HTTP/1.1" 200 82564
[11/Aug/2018 12:48:02] "GET /static/admin/fonts/Roboto-Regular-webfont.w
off HTTP/1.1" 200 80304
[11/Aug/2018 12:48:02] "GET /static/admin/fonts/Roboto-Light-webfont.wof
f HTTP/1.1" 200 81348
Not Found: /favicon.ico
[11/Aug/2018 12:48:02] "GET /favicon.ico HTTP/1.1" 404 1972
[11/Aug/2018 12:48:15] "GET / HTTP/1.1" 200 16348
[11/Aug/2018 12:48:15] "GET /static/admin/css/fonts.css HTTP/1.1" 200 42
3
[11/Aug/2018 12:48:15] "GET /static/admin/fonts/Roboto-Regular-webfont.w
off HTTP/1.1" 200 80304
[11/Aug/2018 12:48:15] "GET /static/admin/fonts/Roboto-Bold-webfont.woff
 HTTP/1.1" 200 82564
[11/Aug/2018 12:48:15] "GET /static/admin/fonts/Roboto-Light-webfont.wof
f HTTP/1.1" 200 81348
Not Found: /favicon.ico
[11/Aug/2018 12:48:15] "GET /favicon.ico HTTP/1.1" 404 1972

4-2 settings.py配置文件詳解,最核心最重要的配置;

"""
Django settings for myblog project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%k5h1y7r%0qg^fez_a+t3qzuibs51jo3=0c6j-w&445en(f0&u'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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 = 'myblog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'myblog.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/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/2.1/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/2.1/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/2.1/howto/static-files/

STATIC_URL = '/static/'

4-3 建立應用,並瞭解應用目錄下各個文件的做用,同時建立一個頁面響應;

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
 startapp os
CommandError: 'os' conflicts with the name of an existing Python module
and cannot be used as an app name. Please try another name.

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>

view.py;

from django.shortcuts import render
#引入Django的類
from django.http import HttpResponse
# Create your views here.
def index(request):
    return HttpResponse('Hello,World!')

urls.py;

"""myblog URL Configuration

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


#引入函數
import blog.views as bv
urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', bv.index),
]

Microsoft Windows [Version 10.0.17134.1]
(c) 2018 Microsoft Corporation. All rights reserved.

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>cd myblog

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>dir
 Volume in drive C has no label.
 Volume Serial Number is B2D2-AA19

 Directory of C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog

08/11/2018  12:47 PM    <DIR>          .
08/11/2018  12:47 PM    <DIR>          ..
08/11/2018  12:47 PM                 0 db.sqlite3
08/11/2018  12:45 PM               553 manage.py
08/11/2018  12:58 PM    <DIR>          myblog
               2 File(s)            553 bytes
               3 Dir(s)  91,055,931,392 bytes free

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
startapp blog
python: can't open file 'manage.pystartapp': [Errno 2] No such file or d
irectory

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
 startapp blog

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>dir
 Volume in drive C has no label.
 Volume Serial Number is B2D2-AA19

 Directory of C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog

08/11/2018  01:01 PM    <DIR>          .
08/11/2018  01:01 PM    <DIR>          ..
08/11/2018  01:01 PM    <DIR>          blog
08/11/2018  12:47 PM                 0 db.sqlite3
08/11/2018  12:45 PM               553 manage.py
08/11/2018  12:58 PM    <DIR>          myblog
               2 File(s)            553 bytes
               4 Dir(s)  91,055,730,688 bytes free

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
 startapp os
CommandError: 'os' conflicts with the name of an existing Python module
and cannot be used as an app name. Please try another name.

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
runserver
python: can't open file 'manage.pyrunserver': [Errno 2] No such file or
directory

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
 runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly u
ntil you apply the migrations for app(s): admin, auth, contenttypes, ses
sions.
Run 'python manage.py migrate' to apply them.
August 11, 2018 - 13:13:27
Django version 2.1, using settings 'myblog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[11/Aug/2018 13:13:45] "GET /index.html HTTP/1.1" 400 26
[11/Aug/2018 13:13:48] "GET /index HTTP/1.1" 400 26
[11/Aug/2018 13:13:50] "GET /index HTTP/1.1" 400 26
[11/Aug/2018 13:13:51] "GET /index HTTP/1.1" 400 26
[11/Aug/2018 13:13:52] "GET /index HTTP/1.1" 400 26
[11/Aug/2018 13:13:58] "GET /index/ HTTP/1.1" 400 26
[11/Aug/2018 13:14:01] "GET /index/ HTTP/1.1" 400 26
[11/Aug/2018 13:14:02] "GET /index/ HTTP/1.1" 400 26
[11/Aug/2018 13:14:02] "GET /index/ HTTP/1.1" 400 26
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly u
ntil you apply the migrations for app(s): admin, auth, contenttypes, ses
sions.
Run 'python manage.py migrate' to apply them.
August 11, 2018 - 13:16:38
Django version 2.1, using settings 'myblog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>python manage.py
 runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly u
ntil you apply the migrations for app(s): admin, auth, contenttypes, ses
sions.
Run 'python manage.py migrate' to apply them.
August 11, 2018 - 13:16:44
Django version 2.1, using settings 'myblog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[11/Aug/2018 13:16:47] "GET /index/ HTTP/1.1" 200 12

第5章 第一個Template

5-1 配置URL

一、直接寫在urls.py的弊端;django

二、在應用下新增urls.py,而後經過主urls.py進行include引入(相似於Nginx.conf的用法);

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/13 16:10
"""myblog URL Configuration

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

from . import views
urlpatterns = [
    #path(r'^index$/',views.index),
    path(r'index/',views.index),
]
blog-urls.py
"""myblog URL Configuration

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/',include('blog.urls')),
]
myblog-urls.py

5-2 開發第一個Template(Django模板語言-DTL)

"""
Django settings for myblog project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%k5h1y7r%0qg^fez_a+t3qzuibs51jo3=0c6j-w&445en(f0&u'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'blog2'
]

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 = 'myblog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'myblog.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/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/2.1/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/2.1/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/2.1/howto/static-files/

STATIC_URL = '/static/'
settings.py
"""myblog URL Configuration

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/',include('blog.urls')),
    path('blog2/',include('blog2.urls')),
]
myblog-urls.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/13 16:10
"""myblog URL Configuration

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

from . import views
urlpatterns = [
    #path(r'^index$/',views.index),
    path(r'index/',views.index),
]
from django.shortcuts import render
#引入Django的類
from django.http import HttpResponse
# Create your views here.
def index(request):
    # return HttpResponse('Hello,World!')
    return  render(request,'blog/index.html')
blog-view.py
from django.shortcuts import render

# Create your views here.
def index(request):
    return  render(request,'blog2/index.html')
blog2-view.py

第6章 Models

6-1 Models

 

 0001_inital.py;

# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-09-24 04:23
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Article',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(default='Title', max_length=32)),
                ('content', models.TextField(null=True)),
            ],
        ),
    ]

使用Python mange.py sqlmigrate blog 001查看「原生SQL語句」;

(venv) cuixiaozhaodeMacBook-Pro:myblog cuixiaozhao$ python manage.py sqlmigrate blog  0001
BEGIN;
--
-- Create model Article
--
CREATE TABLE "blog_article" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(32) NOT NULL, "content" text NULL);
COMMIT;
(venv) cuixiaozhaodeMacBook-Pro:myblog cuixiaozhao$ 

 

# Generated by Django 2.1 on 2018-08-13 09:07

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Article',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(default='Title', max_length=32)),
                ('content', models.TextField(null=True)),
            ],
        ),
    ]

日誌輸出: 

Microsoft Windows [版本 10.0.17134.1]
(c) 2018 Microsoft Corporation。保留全部權利。

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>cd myblog

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>pytho
n manage.py makemigrations
Migrations for 'blog':
  blog\migrations\0001_initial.py
    - Create model Article

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>pytho
n manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sess
ions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... O
K
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>pytho
n manage.py sqlmigrate blog 001
CommandError: Cannot find a migration matching '001' from app
 'blog'. Is it in INSTALLED_APPS?

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>pytho
n manage.py sqlmigrate blog 0001
BEGIN;
--
-- Create model Article
--
CREATE TABLE "blog_article" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(32) NOT NULL, "content" text NULL);
COMMIT;

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018\myblog>

 

數據插入數據時候生成的操做日誌;

[2018-09-24 12:28:56] Connected
sql> SELECT t.* FROM blog_article t
     LIMIT 501
[2018-09-24 12:28:56] 0 rows retrieved in 111 ms (execution: 18 ms, fetching: 93 ms)
sql> INSERT INTO "blog_article" ("title", "content") VALUES ('崔曉昭', '一名優秀的Python程序員!')
[2018-09-24 12:29:37] 1 row affected in 31 ms
sql> SELECT t.* FROM blog_article t
     LIMIT 501
[2018-09-24 12:29:37] 1 row retrieved starting from 1 in 31 ms (execution: 9 ms, fetching: 22 ms)

第7章 Admin

7-1 Admin

建立超級用戶的日誌;

manage.py@myblog > makemigrations
bash -cl "/Users/cuixiaozhao/PycharmProjects/imooc/myblog/venv/bin/python /Users/cuixiaozhao/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/183.2407.3/PyCharm\ 2018.3\ EAP.app/Contents/helpers/pycharm/django_manage.py makemigrations /Users/cuixiaozhao/PycharmProjects/imooc/myblog"
('Tracking file by folder pattern: ', 'migrations')
Migrations for 'blog':
  blog/migrations/0001_initial.py
    - Create model Article

Following files were affected 
 /Users/cuixiaozhao/PycharmProjects/imooc/myblog/blog/migrations/0001_initial.py
Process finished with exit code 0
manage.py@myblog > migrate
bash -cl "/Users/cuixiaozhao/PycharmProjects/imooc/myblog/venv/bin/python /Users/cuixiaozhao/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/183.2407.3/PyCharm\ 2018.3\ EAP.app/Contents/helpers/pycharm/django_manage.py migrate /Users/cuixiaozhao/PycharmProjects/imooc/myblog"
('Tracking file by folder pattern: ', 'migrations')
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK

Process finished with exit code 0
manage.py@myblog > createsuperuser cuixiaozhao
bash -cl "/Users/cuixiaozhao/PycharmProjects/imooc/myblog/venv/bin/python /Users/cuixiaozhao/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/183.2407.3/PyCharm\ 2018.3\ EAP.app/Contents/helpers/pycharm/django_manage.py createsuperuser cuixiaozhao /Users/cuixiaozhao/PycharmProjects/imooc/myblog"
('Tracking file by folder pattern: ', 'migrations')
usage: manage.py createsuperuser [-h] [--version] [-v {0,1,2,3}]
                                 [--settings SETTINGS]
                                 [--pythonpath PYTHONPATH] [--traceback]
                                 [--no-color] [--username USERNAME]
                                 [--noinput] [--database DATABASE]
                                 [--email EMAIL]
manage.py createsuperuser: error: unrecognized arguments: cuixiaozhao

Process finished with exit code 2
manage.py@myblog > createsuperuser
bash -cl "/Users/cuixiaozhao/PycharmProjects/imooc/myblog/venv/bin/python /Users/cuixiaozhao/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/183.2407.3/PyCharm\ 2018.3\ EAP.app/Contents/helpers/pycharm/django_manage.py createsuperuser /Users/cuixiaozhao/PycharmProjects/imooc/myblog"
('Tracking file by folder pattern: ', 'migrations')
Username (leave blank to use 'cuixiaozhao'):  cuixiaozhao
Email address:  tqtl@tqtl.org
Warning: Password input may be echoed.
Password:  Ab123456.
Warning: Password input may be echoed.
Password (again):  Ab123456.
Superuser created successfully.

Process finished with exit code 0

注意Django的配置文件中,不能出現中文,註釋#後面有漢字也不行! 

 

一、http://127.0.0.1:8000/admin/blog/article/

models.py;

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models


# Create your models here.

class Article(models.Model):
    title = models.CharField(max_length=32, default='Title')
    content = models.TextField(null=True)

    def __unicode__(self):  # Python2的用法;
        # def __str__(self): Python的用法;
        return self.title

第8章 完善博客

8-1 博主頁面開發

8.1.1 列表編寫思路:

  • 取出數據庫中全部的文檔對象;(Python中一切皆對象!)
  • 將文章對象們打包成列表,傳遞到前端頁面;
  • 前端頁面把文章以標題超連接的形式逐個列出;

 

 models.py文件修改;

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from blog import models


# Create your views here.

def index(request):
    # return HttpResponse('Hello World!cuixiaozhao')
    # return render(request, 'blog/index.html', {'hello': 'Hello,Django Blog!'})
    # article = models.Article.objects.get(pk=3)
    articles = models.Article.objects.all()
    print(articles)
    return render(request, 'blog/index.html', {'articles': articles})

index.html模板文件修改;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DjangoTemplates</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>
    <a href="">新文章</a>
</h1>
{% for article in articles %}
    <a href="">{{ article.title }}</a>
    <br>
{% endfor %}

</body>
</html>

8-2 博客文章頁面開發

8.2.1 文章標題;

8.2.2 文章內容

8.2.3 修改文章按鈕(超連接)

blog/views.py;

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from blog import models


# Create your views here.

def index(request):
    # return HttpResponse('Hello World!cuixiaozhao')
    # return render(request, 'blog/index.html', {'hello': 'Hello,Django Blog!'})
    # article = models.Article.objects.get(pk=3)
    articles = models.Article.objects.all()
    # print(articles)
    return render(request, 'blog/index.html', {'articles': articles})


def article_page(request, article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/artile_page.html', {'article': article})

blog/urls.py;

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Project: myblog 
# Software: PyCharm
# Time    : 2018-09-24 11:37
# File    : urls.py
# Author  : 天晴天朗
# Email   : tqtl@tqtl.org
from django.conf.urls import url
from django.contrib import admin
from . import views

# from blog import views
# import blog.views as bv

urlpatterns = [
    url(r'^index/$', views.index),
    url(r'^article/(?P<article_id>[0-9]+)$', views.article_page),
]

blog/article_page.html; 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ArticlePages</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>{{ article.title  }}</h1>
<br></br>
<h3>{{ article.content }}</h3>
<br>
<br>
<a href="">修改文章</a>
</body>
</html>

 

8-3 Django模板中的超連接配置

8.3.1 在urls.py中添加namespace = ''

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^blog/', include('blog.urls', namespace='blog')),
    url(r'^content/', include('content.urls')),
]

8.3.2 修改blog/urls.py中參數的傳遞;

urlpatterns = [
    url(r'^index/$', views.index),
    url(r'^article/(?P<article_id>[0-9]+)$', views.article_page, name='article_page'),
]

8.3.3 修改templates文件index.html中的href參數地址指向; 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DjangoTemplates</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>
    <a href="">新文章</a>
</h1>
{% for article in articles %}
    <a href="{% url 'blog:article_page' article.id %} ">{{ article.title }}</a>
    <br>
{% endfor %}

</body>
</html>

 

8-4 博客撰寫頁面開發(一)

8.4.1 標題編輯欄;

views.py;

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from blog import models


# Create your views here.

def index(request):
    # return HttpResponse('Hello World!cuixiaozhao')
    # return render(request, 'blog/index.html', {'hello': 'Hello,Django Blog!'})
    # article = models.Article.objects.get(pk=3)
    articles = models.Article.objects.all()
    # print(articles)
    return render(request, 'blog/index.html', {'articles': articles})


def article_page(request, article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/artile_page.html', {'article': article})


def edit_pages(request):
    return render(request,'blog/edit_page.html')


def edit_action(request):
    title = request.POST.get('title','TITLE')
    content = request.POST.get('content','CONTENT')
    models.Article.objects.create(title=title,content=content)
    articles = models.Article.objects.all()
    return render(request,'blog/index.html',{'articles':articles})

8.4.2 文章內容編輯區域;

8.4.3 提交按鈕;

8-5 博客撰寫頁面開發(二)

8.5.1 編輯頁面開發思路;

  • 新文章爲空,修改文章有內容;
  • 修改文章頁面有文章對象;
  • 文章的ID;

urls.py;

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Project: myblog 
# Software: PyCharm
# Time    : 2018-09-24 11:37
# File    : urls.py
# Author  : 天晴天朗
# Email   : tqtl@tqtl.org
from django.conf.urls import url
from django.contrib import admin
from . import views

# from blog import views
# import blog.views as bv

urlpatterns = [
    url(r'^index/$', views.index),
    url(r'^article/(?P<article_id>[0-9]+)$', views.article_page, name='article_page'),
    url(r'^edit/(?P<article_id>[0-9]+)$', views.edit_pages, name='edit_page'),
    url(r'^edit/action$', views.edit_action, name='edit_action'),
]

views.py;

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from blog import models


# Create your views here.

def index(request):
    # return HttpResponse('Hello World!cuixiaozhao')
    # return render(request, 'blog/index.html', {'hello': 'Hello,Django Blog!'})
    # article = models.Article.objects.get(pk=3)
    articles = models.Article.objects.all()
    # print(articles)
    return render(request, 'blog/index.html', {'articles': articles})


def article_page(request, article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/article_page.html', {'article': article})


def edit_pages(request, article_id):
    if str(article_id) == '0':
        return render(request, 'blog/edit_page.html')
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/edit_page.html', {'article': article})


def edit_action(request):
    title = request.POST.get('title', 'TITLE')
    content = request.POST.get('content', 'CONTENT')
    article_id = request.POST.get('article_id', '0 ')
    if article_id == '0':
        models.Article.objects.create(title=title, content=content)
        articles = models.Article.objects.all()
        return render(request, 'blog/index.html', {'articles': articles})
    article = models.Article.objects.get(pk=article_id)
    article.title = title
    article.content = content
    article.save()
    return render(request,'blog/article_page.html',{'article':article})

index.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DjangoTemplates</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>
    <a href="{% url 'blog:edit_page' 0 %}">新文章</a>
</h1>
{% for article in articles %}
    <a href="{% url 'blog:article_page' article.id %} ">{{ article.title }}</a>
    <br>
{% endfor %}

</body>
</html>

edit_page.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>EditPages</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="{% url 'blog:edit_action' %}" method="post">
    {% csrf_token %}
    {% if article %}
        <input type="hidden" name="article_id" value="{{ article.id }}">
        <label for="">文章標題
            <input type="text" name="title" value="{{ article.title }}">
        </label>
        <br>
        <label for="">文章內容
            <input type="text" name="content" value="{{ article.content }}">
        </label>
        <br>
    {% else %}
        <input type="hidden" name="article_id" value="0">
        <label for="">文章標題
            <input type="text" name="title">
        </label>
        <br>
        <label for="">文章內容 
            <input type="text" name="content">
        </label>
        <br>
    {% endif %}
    <input type="submit" value="提交">
</form>
</body>
</html>

article_page.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ArticlePages</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>{{ article.title  }}</h1>
<br></br>
<h3>{{ article.content }}</h3>
<br>
<br>
<a href="{% url 'blog:edit_page' article.id %}">修改文章</a>
</body>
</html>

第9章 補充內容

9-1 Templates過濾器

9.1.1 什麼是過濾器;

9.1.2 怎麼使用過濾器?

edit_page.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>EditPages</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="{% url 'blog:edit_action' %}" method="post">
    {% csrf_token %}
        <input type="hidden" name="article_id" value="{{ article.id | default:'0' }}">
        <label for="">文章標題
            <input type="text" name="title" value="{{ article.title }}">
        </label>
        <br>
        <label for="">文章內容
            <input type="text" name="content" value="{{ article.content }}">
        </label>
        <br>
    <input type="submit" value="提交">
</form>
</body>
</html>

9-2 Django shell

9.2.1 什麼是Django shell?

9.2.2 如何使用Django shell?

 

(venv) cuixiaozhaodeMacBook-Pro:myblog cuixiaozhao$ python manage.py shell
Python 2.7.10 (default, Oct  6 2017, 22:29:07) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from blog.models import Article
>>> Article.objects.all()
<QuerySet [<Article: 崔曉昭>, <Article: cuixiaozhao>, <Article: 小書包>, <Article: 1>, <Article: TITLE>, <Article: TITLE>,cle: TITLE>, <Article: TITLE>, <Article: 1>, <Article: 3>, <Article: 3>, <Article: 4>, <Article: 4>, <Article: 4>, <Article: 4>, <Article: 4>, <Article: 4>, <Article: 4>, <Article: 4>, <Article: 4>, '...(remaining elements truncated)...']>
>>> Article.objects.all().values()
<QuerySet [{'content': u'\u4e00\u540d\u4f18\u79c0\u7684Python\u7a0b\u5e8f\u5458\uff01', u'id': 1, 'title': u'\u5d14\u6653\u662d'}, {'content': u'cnstacks Pythoner!', u'id': 2, 'title': u'cuixiaozhao'}, {'content': u'\u592a\u9633\u5f53\u7a7a\u7167\uff0c\u82b1\u513f\u5bf9\u6211\u7b11\uff0c\u5c0f\u9e1f\u8bf4\u65e9\u65e9\u65e9\uff0c\u4f60\u4e3a\u4ec0\u4e48\u80cc\u4e0a\u5c0f\u4e66\u5305\uff01', u'id': 3, 'title': u'\u5c0f\u4e66\u5305'}, {'content': u'2', u'id': 4, 'title': u'1'}, {'content': u'CONTENT', u'id': 5, 'title': u'TITLE'}, {'content': u'CONTENT', u'id': 6, 'title': u'TITLE'}, {'content': u'CONTENT', u'id': 7, 'title': u'TITLE'}, {'content': u'CONTENT', u'id': 8, 'title': u'TITLE'}, {'content': u'2', u'id': 9, 'title': u'1'}, {'content': u'4', u'id': 10, 'title': u'3'}, {'content': u'4', u'id': 11, 'title': u'3'}, {'content': u'5', u'id': 12, 'title': u'4'}, {'content': u'5', u'id': 13, 'title': u'4'}, {'content': u'5', u'id': 14, 'title': u'4'}, {'content': u'5', u'id': 15, 'title': u'4'}, {'content': u'5', u'id': 16, 'title': u'4'}, {'content': u'5', u'id': 17, 'title': u'4'}, {'content': u'5', u'id': 18, 'title': u'4'}, {'content': u'5', u'id': 19, 'title': u'4'}, {'content': u'5', u'id': 20, 'title': u'4'}, '...(remaining elements truncated)...']>
>>> 

9-3 Admin加強

9.3.1 建立admin配置類;

9.3.2 Django-admin過濾器;list_filter = ('pub_time',)

 

models.py;

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models


# Create your models here.

class Article(models.Model):
    title = models.CharField(max_length=32, default='Title')
    content = models.TextField(null=True)
    # pub_time = models.DateField(auto_now=True)
    pub_time = models.DateTimeField(null=True)

    def __unicode__(self):  # Python2的用法;
        # def __str__(self):   Python3的用法;
        return self.title

admin.py;

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from models import Article


# Register your models here.
class ArticlAdmin(admin.ModelAdmin):
    list_display = ('title', 'content', 'pub_time',)
    list_filter = ('pub_time',)


admin.site.register(Article, ArticlAdmin)

 

每次修改models.py文件後,先執行makemigrations以及migrate;元組記得加逗號!!!

第10章 課程總結

10-1 課程總結

10.1.1 學習目標和內容以及課程基礎知識等要求;

10.1.2 介紹Django以及經過瀏覽器瀏覽網頁的基本原理;

10.1.3 開發工具的介紹;Python2.7.15 + Django1.11.15

10.1.4 建立Django項目以及建立Django應用以及Django相應頁面;

10.1.5 開發第一個Template,從新配置URL、介紹Templates;

10.1.6 models之介紹ORM、編寫博客的Models,將數據呈如今頁面上;

10.1.7 Django-admin之createsuperuser、配置admin以及使用admin修改數據庫;

10.1.8 完善博客系統開發之-博客主頁面、博客內容頁面、博客編寫頁面;

10.1.9 補充內容:Templates過濾器、Django shell、Admin加強(設置zh_Hans);

10.1.10 Django加強-開始吧!崔工,加油!!!

相關文章
相關標籤/搜索