Django 之必知必会三板斧

一、HttpResponse


在django.http 模块中定义了HttpResponse 对象的API,HttpRequest 对象由Django 自动创建,不调用模板,直接返回数据。

1 在 app/views.py 中导入模块,添加对应的函数

from django.shortcuts import HttpResponse, render, redirect

# Create your views here.

def index(request):

    return HttpResponse("index page")

2 在 mysite/urls.py 中导入存放视图函数的py文件

from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'index/', views.index) # 路由与视图函数对应关系
]

3 启动项目

python manage.py runserver

 

二、redirect


1 redirect 重定向,重定向到本地html 页面或者其他的网页,打开之后会自动跳转。

2 还可以写别名,别名需要参数的话,就必须使用reverse 解析。

from django.shortcuts import HttpResponse, render, redirect

# Create your views here.

def index(request):
    
    # return redirect('http://www.baidu.com')
    # return redirect('/home/')
    return redirect('home')    # 别名方式

def home(request):
    return HttpResponse('home page')

3 在 mysite/urls.py

from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'index/', views.index), # 路由与视图函数对应关系
    path(r'home/', views.home, name = 'home')
]

 

三、render


返回html 页面,并且返回给浏览器之前还可以给html 文件传值

1 render 返回一个html 页面

from django.shortcuts import HttpResponse, render, redirect

# Create your views here.

def index(request):
    """
    :param request: 请求相关的所有数据对象
    """
    # return render(request, 'index.html')
    
    data = "iyuyixyz"
    # 将数据对象展示到页面上
    return render(request, 'index.html', locals())

2 进入templates 文件夹下创建一个 templates/index.html 页面,并写入内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>index page</h3>
    <h3>{{data}}</h3>
</body>
</html>

视图函数必须要返回一个HttpResponse对象,研究三者的源码即可得处结论。

The view app.views.index didn't return an HttpResponse object. It returned None instead.

render 简单内部原理

from django.template import Template, Context
def index(request):
    res = Template('<h1>{{ info }}</h1>')
    context = Context({'info': {'nickname':'iyuyixyz', 'email':'iyuyi.xyz@gmail.com'}})
    result = res.render(context)
    print(result)
    return HttpResponse(result)

 

相关文章

注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有...
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供...
一、Django介绍Python下有许多款不同的 Web 框架。Django是重...
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小...
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的...