我正在製作一個裝飾器,將驗證碼插入到模板中。該方案如下:如何在渲染後將數據插入模板? (django)
@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 %}
看來我應該呈現模板,不同的字典兩次。但我不知道該怎麼做。
這不是表單驗證和django表單系統的全部要點嗎?你確定你不能把驗證放在forms.py乾淨的方法中嗎? – Private
你爲什麼需要檢查'if type(res)== HttpResponse:'。所有視圖必須返回一個HttpResponse,否則Django會拋出錯誤。對??? – suhailvs
@suhail哦,代碼被計劃在發生錯誤使用'insert_verification'函數時發生異常 – Mithril