2016-03-19 14 views
1

我用的是django 1.9和python 3.4的香脆形式1.6。如何使用django香脆形式,如何在Layout对象的Field方法中设置extra_context?

在布局中使用Field类时,我无法使extra_context正常工作。这些值不会被注入到上下文中。

下面的模板无法输出“阈值”值。

这是我的表单代码。

# project_edit_form.py 
from django import forms 
from django.contrib.auth.models import Group 
from .models import Projects 
from crispy_forms.helper import FormHelper 
from crispy_forms.layout import Layout, HTML 

class ProjectEditForm(forms.ModelForm): 

    class Meta: 
     model = Projects 
     fields = ('project_description', 'location', 'days_elapsed',) 

    def __init__(self, *args, **kwargs): 
     self.helper = FormHelper() 
     # ... 
     self.helper.layout = Layout(
     Fieldset(
      'Project', 
      'project_description', 
      'location', 
      Field('days_pge_first_responded', template="days_elapsed_field.html", extra_context={"threshold":15})%}"), 
     ), 
    ) 
    super(ProjectEditForm, self).__init__(*args, **kwargs) 

这里是战场上的HTML模板:

# days_elapsed_field.html 
extra_context.threshold: {{ extra_context.threshold }} 
threshold: {{ threshold }} 
field.threshold: {{ field.threshold }} 

<div id="div_id_{{ field_name }}" class="form-group"> 
    <label for="{{ field.id_for_label }}" class="control-label"> {{ field.label }} </label> 
    <div > 
     <input 
      style="{% if field.value > threshold %} background-color:#FFE8E8; {% else %} background-color:#e3e3e3 {% endif %}" 
      class="textinput textInput form-control" id="{{ field.id}}" name="{{ field.name}}" readonly="True" type="text" value="{{ field.value }}" /> 
    </div> 
</div> 

这里是主要的HTML模板:

{% load crispy_forms_tags %} 
<!doctype html> 
<html> 
    <head>...</head> 
    <body> 
     <form action="" method="post" class="form-horizontal" > 
      {% crispy form %} 
     </form> 
    </body> 
</html> 

回答

0

我无法找出一个内置的方式做它,所以我只是创建了一个泛型类,并用它来代替。您可以将extra_context作为kwarg传递给CustomCrispyFieldextra_context只是我从我的自定义模板中访问的字典,我从crispy_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> 
相关问题