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!


    Hello Django_第1张图片
    浏览器截图

方法二

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

Hello Django_第2张图片
文件路径

  1. index.html

Hello World !

  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!


    Hello Django_第3张图片
    浏览器截图

你可能感兴趣的:(Hello Django)