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

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

问题描述

我的一个视图需要添加一个项目以及其他功能,但是我已经有另一个视图,它特别添加了一个项目。

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天全站免登陆