在视图中,render()render_to_response()direct_to_template()有什么不同(在Python/Django新手能理解的语言上)?

e、 g.从Nathan Borror's basic apps examples开始

def comment_edit(request, object_id, template_name='comments/edit.html'):
    comment = get_object_or_404(Comment, pk=object_id, user=request.user)
    # ...
    return render(request, template_name, {
        'form': form,
        'comment': comment,
    })

但我也看到了

    return render_to_response(template_name, my_data_dictionary,
              context_instance=RequestContext(request))

    return direct_to_template(request, template_name, my_data_dictionary)

有什么区别,在任何特定情况下使用什么?

推荐答案

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

对于1.3中的render_to_response来说,render()是一个全新的快捷方式,它将自动使用RequestContext,从现在开始我肯定会使用它.


2020年编辑:需要注意的是,Django 3.0中删除了render_to_response()

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response

render_to_response(template[, dictionary][, context_instance][, mimetype])¶

render_to_response是教程等中使用的标准渲染函数.要使用RequestContext,您必须指定context_instance=RequestContext(request)


https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template

direct_to_template是我在视图中使用的通用视图(与我的URL相反),因为与新的render()函数一样,它自动使用RequestContext及其所有context_processor.

direct_to_template should be avoided作为基于函数的通用视图已被弃用.使用render或实际的类,参见https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/

我很高兴我很久很久没打RequestContext了.

Python相关问答推荐

如何使用scikit-learn Python库中的Agglomerative集群算法以及集群中声明的对象数量?

将词典写入Excel

如何从格式为note:{neighbor:weight}的字典中构建networkx图?

在两极中实施频率编码

绘制系列时如何反转轴?

在for循环中仅执行一次此操作

使用LineConnection动画1D数据

使用plotnine和Python构建地块

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

管道冻结和管道卸载

基于索引值的Pandas DataFrame条件填充

Pandas—在数据透视表中占总数的百分比

将JSON对象转换为Dataframe

Python中的变量每次增加超过1

需要帮助重新调整python fill_between与数据点

如何使用两个关键函数来排序一个多索引框架?

Python—转换日期:价目表到新行

替换现有列名中的字符,而不创建新列

将一个双框爆炸到另一个双框的范围内

在numpy数组中寻找楼梯状 struct