Django的入门仪式

创建项目,并输出Hello,World!!

创建项目

  1. 创建项目命令
# django-admin startproject <项目名>
  1. 目录结构
# django-admin startproject mysite

mysite --------------> 项目根目录
|-mysite --------------> Python 包
|--__init__.py
|--settings.py --> 全局设置文件
|--urls.py --> 全局路由控制
|--wsgi.py --> 服务器使用wsgi部署文件
|-manage.py --> Django项目管理
  1. 响应请求
  2. views
    ​首次需要创建views.py​​,请切换到mysite与urls.py同级目录下
# cd mysite\mysite
# vim views.py
from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world!!")
  1. urls
    配置url路由
from django.contrib import admin
from django.urls import path
from . import views # 同级目录可直接引用

urlpatterns = [
path('admin/', admin.site.urls),
path("", views.index), # url配置views
]
  1. 启动django
# python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 09, 2021 - 14:49:50
Django version 2.0, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
  1. 测试
    通过浏览器访问:http://127.0.0.1:8000
  2. 初始化sqlite3数据库
# python manage.py migrate

将在根目录生成db.sqlite3的文件,可通过navicat直接打开

  1. django后台管理
    创建管理员
# python manage.py createsuperuser
Username (leave blank to use 'jerry'): admin
Email address: admin@mail.com
Password:
Password (again):
Superuser created successfully.

使用管理登录后台