构建第二个应用程序
1.打开visual studio code
左上角 点击fike 点击open folder
2.打开上次的django项目
并按图示点击进入终端
3.在下方终端输入创建app01项目的命令
接着在左上方会出现一个app01的项目
ps e:\python\hellodjango> python manage.py startapp app01
4.接着在hellodjango的项目里
settings.py中定义应用 找到图示的行 在末尾添加 app01
installed_apps = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01' ]
5.定义app01应用中的views.py视图文件
无则创建 代码如下
from django.shortcuts import render from django.http import httpresponse def sayhello(request): return httpresponse("app01 hello, world!")
6.定义app01中的urls.py
from django.urls import path from . import views urlpatterns = [ path('hello/', views.sayhello) ]
7.定义hellodjango的urls.py
from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path("admin/", admin.site.urls), path('hello/', views.sayhello), path('app01/', include('app01.urls')) ]
注意:
- 有些代码已存在 只需添加没有的代码即可
- 注意格式问题 空格 逗号等
8.在终端输入启动web服务的命令
在浏览器输入127.0.0.1:8000/app01/hello/ 进行验证 效果出现下图即可
ps e:\python\hellodjango> python.exe .\manage.py runserver
watching for file changes with statreloader
performing system checks...system check identified no issues (0 silenced).
you have 18 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.
march 17, 2025 - 11:05:37
django version 5.1.7, using settings 'hellodjango.settings'
starting development server at http://127.0.0.1:8000/
quit the server with ctrl-break.
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论