PS:任何場合不要忘記說謝謝|謝謝你!css
Django的官方網站;https://www.djangoproject.com/html
安裝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>
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
""" 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/'
(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>
from django.shortcuts import render #引入Django的類 from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('Hello,World!')
"""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
一、直接寫在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), ]
"""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')), ]
""" 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/'
"""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')), ]
#!/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')
from django.shortcuts import render # Create your views here. def index(request): return render(request,'blog2/index.html')
# -*- 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)), ], ), ]
(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)
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
一、http://127.0.0.1:8000/admin/blog/article/
# -*- 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
# -*- 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})
<!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>
# -*- 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})
#!/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), ]
<!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>
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog')), url(r'^content/', include('content.urls')), ]
urlpatterns = [ url(r'^index/$', views.index), url(r'^article/(?P<article_id>[0-9]+)$', views.article_page, name='article_page'), ]
<!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>
# -*- 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.5.1 編輯頁面開發思路;
#!/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'), ]
# -*- 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})
<!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>
<!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>
<!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>
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>
(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)...']> >>>
# -*- 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
# -*- 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)