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:任何场合不要忘记说谢谢|谢谢你!

第2章 课前准备

2-1 课前准备

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

第3章 开发环境搭建

3-1 开发环境搭建

  • pip install(推荐)l;
  • 源码安装;

安装Django:

    url:www.djangoproject.com

1、pip install Django==1.10.2

2、下载源码,进入根目录执行python setup.py install

判断是否安装成功:python -m django --version

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

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

1、直接写在urls.py的弊端;

2、在应用下新增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的配置文件中,不能出现中文,注释#后面有汉字也不行! 

 

1、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增强-开始吧!崔工,加油!!!

 

转载于:https://www.cnblogs.com/tqtl911/p/9459253.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值