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>