代码之家  ›  专栏  ›  技术社区  ›  asdf_enel_hak

设置template和wrapper_类参数并呈现单个表单字段not form

  •  1
  • asdf_enel_hak  · 技术社区  · 6 年前

    相关的 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%} 两个领域都发生了。

    我的问题是:

    当渲染为单个场时,不可能给出这些参数吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Community CDub    5 年前

    我的问题是:

    当渲染为单个场时,不可能给出这些参数吗?

    helper.layout 仅在呈现整个窗体时使用,使用 {% crispy form %} 助手.布局 使用crispy单独渲染字段时不起任何作用。从 Fundamentals section of their docs on Layouts

    这允许您设置字段的顺序,将它们包装成div或其他结构,添加html,设置id、类或属性到您想要的任何东西,等等,而无需编写自定义表单模板,使用编程布局。

    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