我可以从另一个视图中调用一个视图吗? [英] Can I call a view from within another view?

查看:33
本文介绍了我可以从另一个视图中调用一个视图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个视图需要添加一个项目以及其他功能,但我已经有另一个视图专门添加了一个项目.

One of my view needs to add an item, along with other functionality, but I already have another view which specifically adds an item.

我可以这样做吗:

def specific_add_item_view(request):
    item = Item.objects.create(foo=request.bar)

def big_view(request):
    # ...
    specific_add_item_view(request)

推荐答案

视图函数应该将呈现的 HTML 返回给浏览器(在 HttpResponse 中).在视图中调用视图意味着您(可能)进行了两次渲染.相反,只需将添加"分解为另一个不是视图的函数,并让两个视图都调用它.

View functions should return a rendered HTML back to the browser (in an HttpResponse). Calling a view within a view means that you're (potentially) doing the rendering twice. Instead, just factor out the "add" into another function that's not a view, and have both views call it.

def add_stuff(bar):
    item = Item.objects.create(foo=bar)
    return item

def specific_add_item_view(request):
    item = add_stuff(bar)
    ...

def big_view(request): 
    item = add_stuff(bar)
    ...

这篇关于我可以从另一个视图中调用一个视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆