注意
⭐前提:将上节的项目导入到pycharm中
操作步骤总结:
1、HelloDjango/HelloDjango目录下,新建一个views.py
2、HelloDjango/HelloDjango/urls.py 文件中,配置url路由信息
3、新建终端,执行运行命令python manage.py runserver
4、输入网址查看效果:http://127.0.0.1:8000/hello/
5、问题探讨:为什么输入http://127.0.0.1:8000/ 网址后报错了?
6、深究:参考django源码
操作步骤
1、HelloDjango/HelloDjango目录下,新建一个views.py,内容如下:
from django.http import HttpResponse
def say_hello(request):
return HttpResponse('Hello Django!')
2、HelloDjango/HelloDjango/urls.py 文件中,配置url路由信息,内容如下:
"""HelloDjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
-----------------翻译如下↓---------------------
HelloDjango URL 配置
`urlpatterns` 列表将 URL 路由映射到视图。有关更多信息,请参阅:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
示例:
函数视图
1. 添加导入:from my_app import views
2. 将 URL 添加到 urlpatterns:path('', views.home, name='home')
基于类的视图
1. 添加导入:from other_app.views import Home
2. 将 URL 添加到 urlpatterns:path('', Home.as_view(), name='home')
包含其他 URL 配置
1. 导入 include() 函数:from django.urls import include, path
2. 将 URL 添加到 urlpatterns:path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from HelloDjango import views # 导入 HelloDjango模块的views.py文件 ↓
urlpatterns = [
path("admin/", admin.site.urls),
path("hello/", views.say_hello), # 配置路由,当用户访问 http://localhost:8000/hello/ 时,Django 会调用 say_hello 视图函数
]
3、新建终端,执行运行命令python manage.py runserver
(django_study_3_11) PS E:\notes\django\django项目学习\03添加一个视图界面\HelloDjango> python 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.
October 21, 2024 - 21:43:34
Django version 4.1, using settings 'HelloDjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
4、输入网址查看效果:http://127.0.0.1:8000/hello/
5、问题探讨:为什么输入http://127.0.0.1:8000/ 网址后报错了?
翻译一下:
屏蔽一下新加的路由
发现界面正常了
现在翻译一下:
是不是比较理解了,admin 属于默认配置的URL,所以urlpatterns为空列表或仅配置admin路由时,才会显示默认欢迎界面;
6、深究:为什么这样显示?
请参考研究django源码: