Django中调用html
一、使用HttpResponse 来把内容显示到网页上
首先在项目中创建一个APP,执行以下命令发现有多了一个webApp
文件夹
python manage.py startapp webApp
在生成的webApp
目录下的views.py
文件中加入以下语句:
from django.http import HttpResponse
def index(request):
return HttpResponse("欢迎光临")
然后在myweb
目录下的urls.py
中加入以下语句:
from webApp import views as webApp_views
path("", webApp_views.index),
结果如下图所示:
在myweb
目录下的settings.py
中的INSTALLED_APPS
加入你新创建的App的名字:
在项目目录中执行python manage.py runserver 8000
,运行程序,再到浏览器中访问本机的80
端口,可以看到返回成功。
二、使用HTML来把内容显示到网页上
在生成的webApp
目录下创建templates目录
,并在templates目录下创建一个home.html文件
在home.html
中添加以下内容:
<!DOCTYPE html>
<html>
<head>
<title>home</title>
</head>
<body>
this is my html
</body>
</html>
在webApp
目录下的views.py
文件中加入以下语句:
def home(request):
return render(request, 'home.html')
然后在myweb
目录下的urls.py
中的urlpatterns
加入以下语句:
path("home/", webApp_views.home),
在项目目录中执行python manage.py runserver 8000
,运行程序,再到浏览器中访问本机的80
端口。