应用,项目中的独立业务模块,可以保函自己的路由、视图、模板、模型。
python manage.py startapp [应用名]
在settings.py的INSTALLED_APPS中注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
主路由文件不处理用户具体路由,做请求分发,具体的请求由子路由进行处理。
from django.urls import path, include
from . import views
urlpatterns = [
path('music/', include(music.urls))
进入app文件见创建urls.py文件
from django.urls import path
from . import views
urlpatterns=[
path('index',views.index_view)
]
主路由新增两个music、sport
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('test_static', views.homepage),
path('music/', include('music.urls')),
path('sport/', include('sport.urls')),
]
创建两个APP后,在settings.py中注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'music',
'sport',
]
在music、sport文件夹中创建子路由文件urls.py
from django.urls import path
from . import views
urlpatterns = [
path('index', views.index_view)
]
完成sport/views.py视图层配置
from django.http import HttpResponse
# Create your views here.
def index_view(request):
return HttpResponse('这是体育频道')
调用应用下的模板