zoukankan      html  css  js  c++  java
  • <django中render_to_response的可选参数和使用方法>

    在django官方文档中有比较详细的介绍,在此我按照自己的理解适当的阐述一下:

    return render_to_response(①'my_template.html',
                              ②my_data_dictionary,
                              ③context_instance=RequestContext(request)
                   )
    template_name
      毫无疑问这个就是你要渲染的模板的路径下的模板名,(一个.html文件),注意:这个参数是必须要求有的,假如没有的话是会报错的。
    (官方文档阐述:The full name of a template to use or sequence of template names. If a sequence is given, the first templa
    te that exists will be used)
    my_data_dictionary
      这是一个字典(python dict),字典中的值添加到模板上下文,默认情况下这个字典是空的,如果调用这个模板中的值,你的模板将会
    被视图函数渲染。
    context_instance=RequestContext(request)
      
    在使用render_to_response,render_to_string等shortcut的时候,可以附带context_instance参数
    来使用RequestContext:
    1. def some_view(request):   
    2.  ... return render_to_response('my_template.html',  
    3. my_data_dictionary, context_instance=RequestContext(request))
    或者

    1. def view(request):  
    2.     #...  
    3.     return render_to_response('template1.html',  
    4.         {'message':'I am the view.'},  
    5.         context_instance=RequestContext(request,processors=[custom_proc])) 

      其中custom_proc为自定义变量的视图,当然也可以在TEMPLATE_CONEXT_PROCESSORS中直接定义一个可

      调用的函数元组,然后在processors中直接来使用。

      由于加载模板、填充 context 、将经解析的模板结果返回为 HttpResponse 对象这一系列操
    作实在太常用了,Django 提供了一条仅用一行代码就完成所有这些工作的捷径。该捷径就是
    位于 django.shortcuts 模块中名为 render_to_response() 的函数。大多数时候,你将使
    用 render_to_response() ,而不是手动加载模板、创建 Context 和 HttpResponse 对象。
    下面就是使用 render_to_response() 重新编写过的 current_datetime 范例。
    from django.shortcuts import render_to_response
    import datetime
    def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('current_datetime.html', {'current_date': now})
    大变样了!让我们逐句看看代码发生的变化:我们不再需要导入 get_template 、 Template 、 Context 和

    HttpResponse 。相反, 我们导入 django.shortcuts.render_to_response 。import datetime 继续保留

    .在 current_datetime 函数中,我们仍然进行 now 计算,但模板加载、上下文创建、模板解析和 HttpResponse

    创建工作均在对 render_to_response() 的调用中完成了。由于 render_to_response() 返回 HttpResponse

    对象,因此我们仅需在视图中return 该值。
    render_to_response() 的第一个参数必须是要使用的模板名称。如果要给定第二个参数,那么该参数

    必须是为该模板创建 Context 时所使用的字典。如果不提供第二个参数,render_to_response() 使用一个空字典。

     

     

    只有你使用了render_to_response之后,你就不用使用Django模板系统的基本规则: 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。

      django官方文档:https://docs.djangoproject.com/en/1.7/topics/http/shortcuts/



     



    你没有做到,你保证你确实用心了吗?
  • 相关阅读:
    Qt读取JSON和XML数据
    IOS设计模式学习(19)策略
    Android学习笔记(二)之异步加载图片
    ETL-Career RoadMap
    HDU 1501 & POJ 2192 Zipper(dp记忆化搜索)
    CodeForces 242E
    推荐:室内定位API
    基于单片机的电子密码锁的实现
    [nagios监控] NRPE: Unable to read output 的原因及排除
    (ubuntu)在andorid andk工程中使用ccache加速编译速度
  • 原文地址:https://www.cnblogs.com/blogofwyl/p/4273417.html
Copyright © 2011-2022 走看看