2

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

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

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

4

1 回答 1

1

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

例如:

验证上下文处理器.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)
                 )
于 2013-08-02T05:23:14.080 回答