目录
-
搭建环境
python版本:>=3.5 Django版本:2.2 先建个虚拟开发环境(python3) pip install django==2.2 创建一个项目 settings.py ALLOWED_HOSTS = ['*'] LANGUAGE_CODE = 'zh-hans' #语言编码 TIME_ZONE = 'Asia/Shanghai' #时区 命令行启动 #命令:python manage.py runserver [ip:port] python manage.py runserver python manage.py runserver 0.0.0.0:9000 本地测试: http://localhost:8000 #或者 http://127.0.0.1:800 1个django项目中可以包含多个应用: #命令: python manager.py startapp 应用名称 实例: python manager.py startapp app
-
简介
# 视图函数views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello Django") #路由urls.py from django.conf.urls import path from django.contrib import admin from App import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index) ] # 模板 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>搜狐</title> </head> <body> 写点什么 </body> </html> views.py from django.shortcuts import render def index(request): return render(request,'index.html') # 数据模型 settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', #数据库引擎 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), #数据库⽂件路径 } } models.py class User(models.Model): uname = models.CharField(max_length=20) password = models.CharField(max_length=32) 命令行 python manage.py makemigrations #生成数据库迁移文件 python manage.py migrate #生成数据库表