1. django安裝
pip3 install django
2. django項目構建
django-admin startproject myapp # 創建項目
cd myapp
python manage.py startapp myweb # 創建應用
如果django-admin命令不可用,請把python安裝目錄下的Scripts文件加入環境變量,然后重啟終端

目錄結構

3. django模型搭建
配置數據庫
/myapp/myapp/settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 使用的數據庫類型,這里使用的是mysql 'NAME': 'test', # 數據庫名稱 'USER': 'root', # 賬號 'PASSWORD': '', # 密碼 'HOST': 'localhost', # 數據庫地址 'PORT': '3306', # 數據庫使用的端口 } }
/myapp/myweb/models.py
from django.db import models # Create your models here. # 創建一個user表 class Users(models.Model): name = models.CharField(max_length=30) # 創建一個長度最大為30的字符字段 字段名:name age = models.IntegerField() # 創建一個整型字段 字段名:age
# 構建數據庫
python manage.py migrate
# 模型發生改變時需要執行該命令重新構建
python manage.py makemigrations
# 錯誤
RuntimeError: Model class myweb.models.Users doesn't declare an explicit app_lab el and isn't in an application in INSTALLED_APPS.
# 解決方式
/myapp/myapp/settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myweb', # 添加應用接口 ]
# 重新構建
python manage.py makemigrations
python manage.py migrate
4. django 模板
/myapp/myapp/settings.py
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['myweb/templates'], # 添加模板文件目錄路徑 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
模板文件
/myapp/myweb/templates/index.html
<html> <head> <title>test</title> <meta charset="utf-8" /> </head> <body> <h1>{{content}}</h1> </body> </html>
5. django 視圖邏輯
/myapp/myweb/views.py
from django.shortcuts import render from myweb.models import Users from django.core import serializers # Create your views here. def index(request): results = serializers.serialize('json',Users.objects.all()) # 查詢users表的所有數據且把數據轉換成json字符串輸出到頁面 return render( request,'index.html',{'content':results} )
6. djangos urls配置
/myapp/myapp/urls.py
from django.conf.urls import url from django.contrib import admin from myweb import views as indexs urlpatterns = [ url(r'', indexs.index), # 映射路由與視圖關系 ]
7. 啟動服務器
python manage.py runserver
