相关的Q&A。您可以考虑对此问题进行跟踪
我的表单类是:
class RoomForm(ModelForm):
room_in_type = forms.ChoiceField(choices = [(elem[0], elem[1]) for elem in filter(lambda x: x[2] == False, memcache.Client().get("room_in_type_choices"))], widget=forms.RadioSelect())
class Meta:
model = Room
def __init__(self, *args, **kwargs):
super(RoomForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_action = form_action
self.helper.label_class = 'col-md-8'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
InlineRadios('room_in_type', required=True, css_classes="col-md-8", template='some_template.html'),
Field('country', required=True, css_class="country-container", wrapper_class ='toto-class'),
Field('fb_user', type='hidden')
)
模板的相关部分是:
{{ form.country | as_crispy_field}}
{{ form.room_in_type | as_crispy_field}}
在这种情况下:
template='some_template.html'
和wrapper_class ='toto-class'
都不被考虑
但是如果我渲染{% crispy form%}
,两个字段都会发生。
我的问题是:
是否可以在渲染为单个字段时提供这些参数?
答案 0 :(得分:0)
我的问题是:
是否可以在渲染为单个字段时提供这些参数?
简短的回答:不是真的。之所以会看到这种差异,是因为仅当使用helper.layout
渲染整个表单时才使用表单对象的{% crispy form %}
-当您使用crispy渲染helper.layout
时,class RoomForm(ModelForm):
...
def __init__(...):
self.fields['room_form'].widget.template_name = 'path/to/your/template.html'
self.fields['room_form'].widget.attrs['class'] = 'my-custom-class'
不起作用个字段。从Fundamentals section of their docs on Layouts:
这使您可以设置字段的顺序,将它们包装在div或其他结构中,添加html,将id,类或属性设置为所需的内容,等等。所有这些都无需编写自定义表单模板,而使用程序化布局。
因此,您的选择是更改包含相关字段/表单的模板中的HTML(将代码放置在单独的模板中以包含在多个位置将是一个好主意),或者使用自定义模板用于您的小部件。后一条路线可能看起来像这样:
<!-- path/to/your/template.html -->
<div class="my-wrapper-class">{% include 'django/forms/widgets/radio.html' %}</div>
您的模板可能如下所示:
as_crispy_field
然后,当您使用add_subdirectory()
分别渲染字段时,将使用上面的代码。如果您选择该路线,则可能要参考内置模板: