2013-08-02 39 views
2

我正在製作一個裝飾器,將驗證碼插入到模板中。該方案如下:如何在渲染後將數據插入模板? (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 %} 

看來我應該呈現模板,不同的字典兩次。但我不知道該怎麼做。

+0

這不是表單驗證和django表單系統的全部要點嗎?你確定你不能把驗證放在forms.py乾淨的方法中嗎? – Private

+0

你爲什麼需要檢查'if type(res)== HttpResponse:'。所有視圖必須返回一個HttpResponse,否則Django會拋出錯誤。對??? – suhailvs

+0

@suhail哦,代碼被計劃在發生錯誤使用'insert_verification'函數時發生異常 – Mithril

回答

1

我認爲更好的方法是實施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', 
    ) 

查看應該使用RequestContext而呈現響應。

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

實際上'render_to_response'是一種舊格式。使用'render(request,'myapp/index.html',{「foo」:「bar」})' – suhailvs

+0

'context processor'似乎是一個全局處理器。爲什麼我想使用裝飾器是我可以直接添加驗證新視圖需要驗證時的任何其他更改。 – Mithril

+0

如果使用'context processor',每次添加新視圖需要驗證時,我應該改變'add_verification'函數,那麼反正可以降低複雜度嗎? – Mithril