python-django官方教程手把手(一)

169 阅读1分钟

python-django官方教程手把手(一)

1 安装django, 附上参考地址: Quick install guide

2 创建项目

django-admin startproject mysite

创建后的目录如下

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

3 启动项目

py manage.py runserver

类似如下的信息就说明成功了

Performing system checks...

System check identified no issues (0 silenced).

You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.

July 04, 2022 - 15:50:53
Django version 4.0, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000
Quit the server with CONTROL-C.

4 创建应用app, 可以理解为创建模块

py manage.py startapp polls

创建后的结构

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

4.1 写第一个view(视图)

path: polls/views.py

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

polls的目录结构

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    urls.py
    views.py

4.2 撰写 polls/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

4.3 设置主站路由, 请注意这里,容易混淆

path: mysite/urls.p

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

5 运行, 运行地址: http://localhost:8000/polls/

py manage.py runserver

运行结果

image.png