为什么我的脆弱的formset布局被忽略了?

时间:2014-09-04 02:41:52

标签: django django-crispy-forms

我正在为一个相当复杂的模型开发一个前端表单,而且我还是新的脆弱表单。

My Proposal模型使用两个m2m字段作为部分和要求,每个字段都有自定义的表格。我正在使用带有此模板的formset来提交提案表单:

    <div class="tab-content panel-body">
        <div id="basic-information"
             class="tab-pane active" >
            {% crispy form %}
        </div>
        <div id="sections"
             class="tab-pane" >
            {% crispy sectionmap_formset sectionmap_formset_helper %}
        </div>
        <div id="requirements"
             class="tab-pane" >
            {% crispy requirementmap_formset requirementmap_formset_helper %}
        </div>
    </div>

帮助者如此设置:

class MapFormSetHelper(FormHelper):
    template = 'bootstrap/table_inline_formset.html'

    def __init__(self, form=None):
        super(MapFormSetHelper, self).__init__(form)
        self.disable_csrf = True
        self.form_method = 'post'
        self.form_tag = False


class SectionMapFormSetHelper(MapFormSetHelper):
    def __init__(self, form=None):
        super(SectionMapFormSetHelper, self).__init__(form)
        self.layout = Layout('order', 'section', 'placement')


class RequirementMapFormSetHelper(MapFormSetHelper):
    def __init__(self, form=None):
        super(RequirementMapFormSetHelper, self).__init__(form)
        self.layout = Layout('order', 'requirement', 'selected_option')

并添加到上下文中:

def get_context_data(self, **kwargs):
    context = super(ProposalUpdateView, self).get_context_data(**kwargs)
    proposal = context['proposal']

    # Add formsets
    for model_class, context_key, formset_class in (
            (pm.ProposalSectionMap, 'sectionmap_formset', forms.SectionMapFormSet),
            (pm.ProposalRequirementMap, 'requirementmap_formset', forms.RequirementMapFormSet)):
        qs = model_class.objects.filter(proposal=proposal)
        context[context_key] = formset_class(queryset=qs)

    # Add helpers
    context['sectionmap_formset_helper'] = forms.SectionMapFormSetHelper()
    context['requirementmap_formset_helper'] = forms.RequirementMapFormSetHelper()

    return context

表格布局和form_tag位被正确拾取(结果看起来不错)但是self.layout设置没有效果。

问题是所有的formset字段仍在显示 - 虽然调用了行并且正确的帮助器就位,但就好像布局被忽略了(我尝试将html添加到布局中)它没有显示。)

谁能告诉我我做错了什么?随意指出我正确的文档 - 我已经仔细考虑它无济于事,我可能会遗漏一些明显的东西。

1 个答案:

答案 0 :(得分:2)

好的,答案是因为我使用了bootstrap / table_inline_formset.html。仔细观察它,我发现它直接通过表单字段工作,从而忽略了脆弱的布局。 -1在这方面是脆的。

要指定我的字段,我为formset创建了一个自定义的模型表单,并将字段添加到Meta中:

class SectionMapForm(forms.ModelForm):
    class Meta:
        model = pm.ProposalSectionMap
        fields = ('order', 'section', 'placement')

SectionMapFormSet = modelformset_factory(pm.ProposalSectionMap, form=SectionMapForm, extra=1)


class RequirementMapForm(forms.ModelForm):
    class Meta:
        model = pm.ProposalRequirementMap
        fields = ('order', 'requirement', 'selected_option')

RequirementMapFormSet = modelformset_factory(pm.ProposalRequirementMap, form=RequirementMapForm, extra=1)

我希望这有助于某人。