通过前三篇的了解,大概知道了django是干嘛的,现在可以开始操作了
首先在Helloworld目录下新建一个view.py文件
from django.http import HttpResponse
def hello(request):
return HttpResponse("This is my first project")
然后在url.py文件下需要配置
from django.urls import path
from . import view
urlpatterns = [
path('admin/', admin.site.urls),
path(r'',view.hello)
]
【踩坑】需要把view引入,要不会报错
运行起来,页面上就会加载
上面还没有涉及到template
OK,可以直接分离页面和数据了,下面添加templates部分
(1)在项目下新建文件夹templates
【备注】此处踩坑把templates文件夹建到2里面,导致运行的时候怎么都找不到hello.html
修改view.py文件
from django.shortcuts import render
def hello(request):
context = {}
context['hello'] = "hello world"
print("ddd")#此处是为了查服务器一直异常的问题,定位到是问题是找不到hello.html
return render(request, 'hello.html', context)
添加hello.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>djangoTest</title>
</head>
<body>
<h1>{{hello}}</h1>
<p>Django 测试</p>
</body>
</html>
刷新页面http://127.0.0.1:8000/hello/