Hello Django

主题

Django学习笔记之输出Hello Django

方法一

调用HttpResponse类向浏览器返回‘Hello Django’字符串

实现:

  1. 准备工作(cmd.exe)
# 创建一个Django项目
>> django-admin startproject helloDj
>> cd helloDj/helloDj/ # 进入helloDj/helloDj
# 创建django视图文件,控制前段显示内容
>> touch views.py 
  1. 配置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路由
]
  1. 定义index属性(views.py)
from django.http import HttpResponse

def hello(requeset):
    return HttpResponse('Hello Django !')
  1. 运行(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.
  1. 结果,ok!


    浏览器截图

方法二

使用HTML模板
在helloDj/目录下创建templates/index.html文件

文件路径

  1. index.html
<html>
<h1>Hello World !</h1>
</html>
  1. views.py
from django.shortcuts import render
def hello(request):
    return render(request, "hello.html")
  1. urls.py保持不变
  2. 配置setting.py
...
'DIRS': [BASE_DIR+"/templates", ], # 很重要,否则报TemplateDoesNotExist
...   
  1. 结果,ok!


    浏览器截图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容