相关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'
均不被考虑
但是如果我渲染 {%脆皮形式%}
两个字段都会发生。
我的问题是:
是否可以在渲染为单个字段时给出这些参数?
最佳答案
My question is:
Isn't it possible, to give those parameters while rendering as single field?
简短回答:并非如此。您看到这种差异的原因是表单对象的 helper.layout
仅在渲染整个表单时使用,使用 {% Crispy form %}
- helper.layout 不起作用。来自 Fundamentals section of their docs on Layouts :
This allows you to set the order of the fields, wrap them in divs or other structures, add html, set ids, classes or attributes to whatever you want, etc. And all that without writing a custom form template, using programmatic layouts.
因此,您的选择是更改包含相关字段/表单的模板中的 HTML(将此代码放入单独的模板中以便包含在多个位置中是一个好主意),或者使用自定义模板对于您的小部件。后一条路线可能如下所示:
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'
您的模板可能如下所示:
<!-- path/to/your/template.html -->
<div class="my-wrapper-class">{% include 'django/forms/widgets/radio.html' %}</div>
然后,当您使用 as_crispy_field
单独渲染字段时,将使用上述代码。如果您选择该路线,您可能需要引用内置模板:
关于python - 设置 template 和wrapper_class 参数并渲染单个表单字段而不是表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53477261/