2

Django的view中常用return方法

 2 years ago
source link: https://www.hi-roy.com/posts/django%E7%9A%84view%E4%B8%AD%E5%B8%B8%E7%94%A8return%E6%96%B9%E6%B3%95/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Django的view中常用return方法

2014-03-25

第一种HttpResponse,最基本的返回方式,可以直接返回字符:

from django.http import HttpResponse
def index(request):
    return HttpResponse(“a test”)

或者结合contextloder返回网页:

from django.template import Context, loader  
from polls.models import Poll
def index(request):  
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]  
    template = loader.get_template('polls/index.html')
    context = Context({ 'latest_poll_list': latest_poll_list, })  
    return HttpResponse(template.render(context))

第二种,可以说是上一种的精简版:

from django.shortcuts import render_to_response
from django.template import RequestContext
def search_view_bak(request, template="shop/search.html"):
    context = RequestContext(request, {
            'results': results,
            'category' : category,
            'keywords' : keywords})
    return render_to_response(template, context)

第三种,最最精简版:

from django.shortcuts import render
def index(request):
    return render(request, "search/search.html", {})

第四中,直接返回其他url:

from django.http import  HttpResponseRedirect
def index(request):
    return HttpResponseRedirect('/home/')
Roy avatar
About Roy
野生程序猿,略懂Python,略懂Golang,略懂云计算,略懂大数据,略懂拳击游泳钓鱼,略懂钢琴吉他摄影。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK