使用 django 脆皮形式,如何在布局对象的 Field 方法中设置extra_context



我正在使用脆皮形式1.6与django 1.9和python 3.4。

在使用带有布局的字段类时,我无法使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>

我无法找到一种内置的方法,所以我只是创建了一个泛型类并使用它。 您可以将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>

相关内容

最新更新