Skip to main content
 首页 » 编程设计

python之如何在渲染后将数据插入模板 ( Django )

2025年05月04日38Leo_wl

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

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

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

请您参考如下方法:

我认为更好的方法是实现您的 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', 
      ) 

您的 View 应使用 RequestContext在呈现响应时。

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