2014-04-22 3 views
3

django-crispyforms의 bootstrap3 템플릿 팩에서 field.html 템플릿을 검사하면 추가 컨텍스트 변수 인 "tag"가 참조되었습니다. 템플릿의 line 12line 41에서 확인할 수 있습니다. 특정 양식 필드의 field.html 템플릿을 렌더링하는 데 사용되는 컨텍스트에서 "태그"에 대한 값을 지정하려면 어떻게해야합니까?django-crispy-forms 필드 템플릿에 추가 컨텍스트를 전달하는 방법은 무엇입니까?

답변

0

tag 컨텍스트 변수가보기가 아닌 템플리트에 설정됩니다. 내장 된 bootstrap3 템플릿 팩을 사용하는 경우 field.html을 포함한 템플릿에 템플릿 팩이 정의되어 있습니다. 포함 템플릿에 tag이 정의되어 있지 않으면 기본값은 div입니다.

예 : table_inline_formset.htmlline 41.

1

당신은 다음과 같은 표준 바삭한 필드를 재정의 할 수

class LinkField(Field): 
    def __init__(self, *args, **kwargs): 
     self.view_name = kwargs.pop('view_name') 
     super(LinkField, self).__init__(*args, **kwargs) 

    def render(self, form, form_style, context, template_pack=CRISPY_TEMPLATE_PACK): 
     if hasattr(self, 'wrapper_class'): 
      context['wrapper_class'] = self.wrapper_class 

     if hasattr(self, 'view_name'): 
      context['view_name'] = self.view_name 
     html = '' 

     for field in self.fields: 
      html += render_field(field, form, form_style, context, template=self.template, attrs=self.attrs, template_pack=template_pack) 
     return html 

가 그럼 그냥 오버라이드 (override) 템플릿에 추가 변수 ('VIEW_NAME')를 전달합니다.

레이아웃은 다음과 같이 표시됩니다

Layout(
    LinkField('field_name', template='path_to_overridden_template', 
         view_name='variable_to_pass') 
) 
1

나는 CustomCrispyField 더 일반적인를 구축 가이드로 palestamp의 응답을 사용했다. extra_contextkwarg에서 CustomCrispyField으로 전달할 수 있습니다. extra_contextcrispy_forms에서 복사 한 사용자 정의 템플릿에서 액세스하는 사전입니다.

from crispy_forms.layout import Field 
from crispy_forms.utils import TEMPLATE_PACK 


class CustomCrispyField(Field): 
    extra_context = {} 

    def __init__(self, *args, **kwargs): 
     self.extra_context = kwargs.pop('extra_context', self.extra_context) 
     super(CustomCrispyField, self).__init__(*args, **kwargs) 

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs): 
     if self.extra_context: 
      extra_context = extra_context.update(self.extra_context) if extra_context else self.extra_context 
     return super(CustomCrispyField, self).render(form, form_style, context, template_pack, extra_context, **kwargs) 

그리고처럼 사용하는 것이 나의 형태 :

self.helper.layout=Div(CustomCrispyField('my_model_field', css_class="col-xs-3", template='general/custom.html', extra_context={'css_class_extra': 'value1', 'caption': 'value2'}) 

그리고 내 템플릿은 다음과 유사한 코드 것이다 :

{% crispy_field field %} 
<button class="btn {{ css_class_extra }}">{{ caption }}</button> 
관련 문제