2013-08-02 2 views
2

템플릿에 인증 코드를 삽입하는 데코 데코를 만들고 있습니다.렌더링 후 템플릿에 데이터를 삽입하는 방법은 무엇입니까? (django)

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

내가 다른 사전으로 두 번 템플릿을 렌더링 해봐야 할 것 같습니다 : 나는 다음과 같은 템플릿을 사용

@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 

:이 시나리오는 다음과 같다. 하지만 어떻게해야할지 모르겠다.

+0

이 양식의 유효성 검사 및 django 양식 시스템이 아닌가요? 검증을 form.py clean 메소드에 넣을 수는 없습니까? – Private

+0

'if type (res) == HttpResponse :'를 확인해야하는 이유는 무엇입니까? 모든보기는 HttpResponse를 반환해야합니다. 그렇지 않으면 django가 오류를 발생시킵니다. 권리??? – suhailvs

+0

@suhail 오, 코드는'insert_verification' 함수의 오용이 발생하면 예외를 발생시킬 계획입니다. – Mithril

답변

1

더 나은 방법은 을 구현하여 verification 컨텍스트 변수를 템플릿 컨텍스트에 추가하는 것입니다. 예를 들어

:

settings.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 

verification_context_processor.py, 응답을 렌더링하는 동안 RequestContext를 사용해야합니다

import django.conf.global_settings as DEFAULT_SETTINGS 

TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
    'custom_context_processors.add_verification', 
    ) 

당신이보기를 업데이트합니다.

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

'컨텍스트 프로세서 '는 글로벌 프로세서처럼 보입니다. 왜 내가 장식자를 사용하고 싶은지, 새보기에 확인이 필요할 때 다른 변경. – Mithril

+0

'context processor'를 사용한다면, 새로운 뷰를 추가 할 때마다 매번'add_verification' 함수를 변경해야합니다. 어쨌든 복잡성을 줄일 수 있습니까? – Mithril

관련 문제