简体   繁体   English

渲染后如何在模板中插入数据? (django的)

[英]How to insert data to a template after render ? (django)

I am making a decorator to insert verification code into a template. 我正在做一个装饰器,以将验证代码插入模板。 The scenario is the following : 该方案如下:

@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

I use the following template: 我使用以下模板:

{% 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 %}

It seems I should render a template twice with different dictionary. 看来我应该用不同的字典两次渲染一个模板。 But I don't know how to do that. 但是我不知道该怎么做。

I think the better approach will be to implement your context processor to add verification context variable to the template contexts. 我认为更好的方法是实现您的上下文处理器,以将verification上下文变量添加到模板上下文中。

For example: 例如:

verification_context_processor.py 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

In settings.py, update 在settings.py中,更新

import django.conf.global_settings as DEFAULT_SETTINGS

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

You view should use RequestContext while rendering the response. 您认为在呈现响应时应使用RequestContext

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM