gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:20 25 4
gpt4 key购买 nike

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

@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 processorverification 上下文变量添加到模板上下文中。

例如:

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)
)

关于python - 如何在渲染后将数据插入模板? ( Django ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18008232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com