我正在制作装饰器以将验证码插入模板中。方案如下:
@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 %}
看来我应该用不同的字典渲染两次模板。但我不知道该怎么做。
答案 0 :(得分: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)
)