微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 页面,并写入内容

@H_404_107@<!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':'[email protected]'}})
    result = res.render(context)
    print(result)
    return HttpResponse(result)

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐