主题
Django学习笔记之输出Hello Django
方法一
调用HttpResponse类向浏览器返回‘Hello Django’字符串
实现:
- 准备工作(cmd.exe)
# 创建一个Django项目
>> django-admin startproject helloDj
>> cd helloDj/helloDj/ # 进入helloDj/helloDj
# 创建django视图文件,控制前段显示内容
>> touch views.py
- 配置url(urls.py)
from django.contrib import admin
from django.urls import path
from . import views # 导入views模块
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.hello), # 配置inde路由
]
- 定义index属性(views.py)
from django.http import HttpResponse
def hello(requeset):
return HttpResponse('Hello Django !')
- 运行(cmd.exe)
>> python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
April 25, 2018 - 22:53:31
Django version 2.0.4, using settings 'helloDj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
-
结果,ok!
浏览器截图
方法二
使用HTML模板
在helloDj/目录下创建templates/index.html文件
- index.html
<html>
<h1>Hello World !</h1>
</html>
- views.py
from django.shortcuts import render
def hello(request):
return render(request, "hello.html")
- urls.py保持不变
- 配置setting.py
...
'DIRS': [BASE_DIR+"/templates", ], # 很重要,否则报TemplateDoesNotExist
...
-
结果,ok!
浏览器截图
网友评论