1. 程式人生 > >轉發和重定向(python)

轉發和重定向(python)

轉發和重定向


轉發:只有一次請求和響應

重定向:兩對以上的請求和響應

在這裡插入圖片描述


使用:

render

render(request, template_name[, context])
結合一個給定的模板和一個給定的上下文字典,並返回一個渲染後的HttpResponse物件
request:該request用於生成response
template_name:要使用的模板的完整名稱
context:新增到模板上下文的一個字典,檢視將在渲染模板之前呼叫它

from django.shortcuts import render

def index(request):
    return render(request, 'booktest/index.html', {'h1': 'hello'})

redirect

redirect(to)
為傳遞進來的引數返回HttpResponseRedirect
to推薦使用反向解析

from django.shortcuts import redirect
from django.core.urlresolvers import reverse

def index(request):
    return redirect(reverse('booktest:index2'))

注意:
 redirect(reverse(-----這裡面寫的是一個url ------))

在這裡插入圖片描述


下面這兩個程式碼的結果一樣
        return redirect(reverse('user:login'))
        return render(request,"login.html")