修改URL配置:
1. 在helloworld/helloworld目/录下的urls.py中中修改url配置
url第二种写法,第二个参数为include的文件
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', include('blog.urls')), ]
2.在helloworld/blog目录下新建urls.py文件,并编辑代码
from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^index/$', views.index), ]
3.通过http://127.0.0.1:8000/index/index/进行访问
开发第一个template
1. 在helloworld/blog/目录(即APP根目录)下新建Templates目录,添加index.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>hello liynhong</h1>> </body> </html>
2. 在blog下的view.py中return render()
第一个参数为request,第二个参数为模板文件, 第三个参数为后端向前端返回的数据
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return render(request,'index.html')
3.输入http://127.0.0.1:8000/index/index/ 访问
使用键值对传递数据
1.在上述render()中添加字典键值对
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return render(request,'index.html',{'hello':'hello baidu'})
2.修改html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ hello }}</h1>> </body> </html>
3.通过http://127.0.0.1:8000/index/index/进行访问
注意事项:
编译器是根据在INSTALLED_APP中添加的顺序查找Templates的,所以如果两个不同的APP中相同名字的Templates的话,会导致第二个APP的Templates被第一个覆盖,从而无法访问。
解决方法:在两个APP的Templates目录下新建一个与所在APP名称相同的目录,将html文件放入目录下,然后修改views.py文件里html代码目录,就ok