【问题标题】:How to insert data to a template after render ? (django)渲染后如何将数据插入模板? (django)
【发布时间】:2013-08-03 05:06:31
【问题描述】:

我正在制作一个装饰器来将验证码插入到模板中。场景如下:

@insert_verification
def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {"foo": "bar"},
        content_type="application/xhtml+xml")


def insert_verification(func):
    def wrapped(request):
        res = func(request)
        if type(res) == HttpResponse:
            # add a verification code to the response
            # just something like this : res.add({"verification": 'xxxxx'})
            # and varification can fill in the template
        return res
    return wrapped

我使用以下模板:

{% block main %}
<fieldset>
    <legend>{{ title }}</legend>
    <form method="post"{% if form.is_multipart %} enctype="multipart/form-data"{% endif %}>

    {% fields_for form %}
    <input type="hidden" value="{{varification}}" >
    <div class="form-actions">
        <input class="btn btn-primary btn-large" type="submit" value="{{ title }}">
    </div>
    </form>
</fieldset>
{% endblock %}

看来我应该使用不同的字典两次渲染模板。但我不知道该怎么做。

【问题讨论】:

  • 这不是表单验证和 django 表单系统的重点吗?您确定不能只将验证放在 forms.py clean 方法中吗?
  • 你为什么需要检查if type(res) == HttpResponse:。所有视图都必须返回一个 HttpResponse 否则 django 会抛出错误。对吗???
  • @suhail 哦,代码计划在insert_verification函数发生误用时引发异常

标签: python django templates render


【解决方案1】:

我认为更好的方法是实现您的 context processor 以将 verification 上下文变量添加到模板上下文中。

例如:

verification_context_processor.py

def add_verification(request):
    #get verification code
    ctx = {'verification': 'xxxxx'}

    #you can also check what path it is like
    #if request.path.contains('/someparticularurl/'):
    #    add verification 

    return ctx

在settings.py中,更新

import django.conf.global_settings as DEFAULT_SETTINGS

TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
    'custom_context_processors.add_verification',
      )

您的视图应该在呈现响应时使用RequestContext

def my_view(request):
    # View code here...
    return render_to_response(request, 'myapp/index.html', {"foo": "bar"},
                 context_instance=RequestContext(request)
                 )

【讨论】:

  • 实际上render_to_response 是一种旧格式。使用render(request, 'myapp/index.html', {"foo": "bar"})
  • context processors 似乎是一个全局处理器。为什么我要使用装饰器是因为当新视图需要验证时,我可以添加一个验证而无需任何其他更改。
  • 如果使用context processors,每次添加新视图需要验证时我都应该更改add_verification函数,那么有没有可以降低复杂度的方法?
  • @Mithril 这取决于你如何获得验证码。如果它是什么视图无关紧要。它将被添加到每个视图的模板上下文中。如果模板想要或不需要使用它,它只会使用它。
猜你喜欢
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 2022-09-27
  • 2015-10-17
  • 2017-10-13
  • 2022-07-22
  • 2020-10-21
  • 2012-03-01
相关资源
最近更新 更多