在根urls.py中引入include;
根urls.py中url函数第二个参数改为:include("blog.urls")
具体:修改myblog/myblog/urls.py文件为
"""myblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')), # 引入'blog/urls'模块
]
在app目录下创建urls.py文件,格式与根urls.py相同 ;
具体:blog文件夹下增加urls.py文件
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.index),
]
启动服务器:
python manage.py runserver 8080
在浏览器地址栏中输入localhost:8080/blog/index/即可浏览。
注意:
根urls.py针对APP配置的URL名称,是该APP所有URL的总路径;
开发第一个template:
步骤:
1、在app目录下创建 名为templates的目录;
2、在该目录下创建html文件;
3、在views.py中返回render()。
myblog/blog/views.py:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
#return HttpResponse("Hello world!")
return render(request, 'index.html', {'hello': 'hello, blog!'})
myblog/blog/templates/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{hello}}</h1>
</body>
</html>
DTL初步使用:
render()函数中支持dict类型参数;
该字典是后台传递到模板的参数,键为参数名;
在模板中使用{{参数名}}来直接使用
Django查找查找Template:
Django按照INSTALLED_APPS中添加的顺序查找TEMPLATES;
不同APP下TEMPLATES目录中的同名.html文件会造成冲突。
解决TEMPLATES冲突的方案:
在APP的TEMPLATES目录下创建以APP为名称的目录;
将html文件放入新创建的目录下。