Django Crispy表单-具有更新视图的内联Formsets'ManagementForm数据'错误

时间:2018-11-19 17:30:27

标签: django django-forms django-crispy-forms

晚上好

我在使用酥脆的表格inlineformset时遇到麻烦。我按照以下指南进行操作:

https://github.com/timhughes/django-cbv-inline-formset/blob/master/music/views.py https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_formsets.html#formsets

编辑 我认为问题与双重提交按钮有关。 devicemodel表单具有一个按钮,当按下该按钮时会产生此错误。但是作为资源帮助器的一部分,还有一个保存按钮,提交后,我收到一个空的模型表单错误。

我添加了当您操作每个按钮时会发生什么情况的屏幕截图

Error when resource save button pressed

error when update device button is pressed

并且在出现错误时我一定会丢失一些东西:

['ManagementForm data is missing or has been tampered with']

这是我的更新视图:

class EditDeviceModel(PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
    model = DeviceModel
    form_class = DeviceModelForm

    template_name = "app_settings/base_formset.html"
    permission_required = 'config.change_devicemodel'
    success_message = 'Device  Type "%(model)s" saved successfully'

    def get_success_url(self, **kwargs):         
        return '{}#device_models'.format(reverse("config:config_settings"))

    def get_success_message(self, cleaned_data):
        return self.success_message % dict(
            cleaned_data,
            model=self.object.model,
        )     

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title']='Edit Device Model'
        if self.request.POST:
            context['formset'] = DeviceFormSet(self.request.POST, instance=self.object)
        else:
            context['formset'] = DeviceFormSet(instance=self.object)
        context['helper'] = DeviceFormSetHelper()
        return context

    def form_valid(self, form):
        context = self.get_context_data()
        formset = context['formset']
        if formset.is_valid():
            self.object = form.save()
            formset.instance = self.object
            formset.save()
            return redirect(self.success_url)
        else:
            return self.render_to_response(self.get_context_data(form=form)) 

这是我的表格:

class MonitoredResourceForm(forms.ModelForm):
    class Meta:
        model = MonitoredResource
        fields = ['resource','model']

    def __init__(self, *args, **kwargs):
        self.is_add = kwargs.pop("is_add", False)
        super(MonitoredResourceForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_id = 'snmp_resource_form'
        self.helper.form_method = 'POST'
        self.helper.layout = Layout(
            Div(    
                Div(
                    Field('model'),
                    Field('resource', placeholder="Resource"),
                    css_class='col-lg-3'
                ),
            css_class='row'
            ),
            Div(
                Div(
                    HTML("""<input type="submit" name="submit" value="""),
                    HTML('"Add' if self.is_add else '"Update' ),
                    HTML(""" monitored resource" class="btn btn-primary"/>"""),
                    HTML("""<a href="{% url 'config:config_settings' %}#monitored_resources" class="btn btn-primary">Cancel</a>"""),
                    HTML("""{% if object %}
                            <a href="{% url 'config:delete_monitoredresource' object.id %}"
                            class="btn btn-danger">
                            Delete <i class="fa fa-trash-o" aria-hidden="true"></i></a>
                            {% endif %}"""),
                    css_class='col-lg-12'
                    ),
                css_class='row'
                ),
        ) 

class DeviceModelForm(forms.ModelForm):
    class Meta:
        model = DeviceModel
        fields = ['model','vendor','device_type','ports','uplink_speed']

    def __init__(self, *args, **kwargs):
        self.is_add = kwargs.pop("is_add", False)
        super(DeviceModelForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_id = 'device_type_form'
        self.helper.form_method = 'POST'
        self.helper.layout = Layout(
            Div(    
                Div(
                    Field('model', placeholder="Model"),
                    Field('vendor',),
                    Field('device_type',),
                    Field('ports', placeholder="Ports"),
                    Field('uplink_speed', placeholder="Uplink Speed"),
                    css_class='col-lg-6'
                ),
            css_class='row'
            ),
            Div(
                Div(
                    HTML("""<input type="submit" name="submit" value="""),
                    HTML('"Add' if self.is_add else '"Update' ),
                    HTML(""" Device Model" class="btn btn-primary"/>"""),
                    HTML("""<a href="{% url 'config:config_settings' %}#device_models" class="btn btn-primary">Cancel</a>"""),
                    HTML("""{% if object %}
                            <a href="{% url 'config:delete_device_model' object.id %}"
                            class="btn btn-danger">
                            Delete <i class="fa fa-trash-o" aria-hidden="true"></i></a>
                            {% endif %}"""),
                    css_class='col-lg-12'
                    ),
                css_class='row'
                ),
        )

DeviceFormSet = inlineformset_factory(DeviceModel, MonitoredResource, form=MonitoredResourceForm, extra=1)

class DeviceFormSetHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(DeviceFormSetHelper, self).__init__(*args, **kwargs)
        self.form_method = 'post'
        self.render_required_fields = True
        self.form_id = 'snmp_resource_form'
        self.form_method = 'POST'
        self.add_input(Submit("submit", "Save"))
        self.layout = Layout(
            Div(    
                Div(
                    Field('model'),
                    Field('resource', placeholder="Resource"),
                    css_class='col-lg-6'
                ),
            css_class='row'
            ),
        ) 

以及我渲染的模板中:

{% block content %} 
{% include "home/form_errors.html" %}
<div class="col-lg-6">
    {% crispy form %}
</div>
<div class="col-lg-6">
    {% crispy formset helper %}
</div>
<!-- /.row -->
{% endblock %}

有人能看到我想念的东西吗?

4 个答案:

答案 0 :(得分:1)

我认为您必须在模板explained here why you need that

中呈现管理表单 表单集使用

管理表单来管理表单集中包含的表单的集合。如果您不提供此管理数据,则会引发异常

将此添加到视图html

{{ DeviceFormSet.management_form }}

答案 1 :(得分:0)

您缺少标签,也{{format.management_form | crispy}} 我猜

答案 2 :(得分:0)

您的问题是,表单集中的每个表单都有自己的management_form。我没有专门处理脆皮,但是在一般模板中,这就是我遇到的问题。您必须通过迭代或硬编码手动拼出每个表单集,并确保每个表单都有其management_form

答案 3 :(得分:0)

我遇到了同样的问题,并在documentation中找到了答案:

{{ formset.management_form|crispy }}
{% for form in formset %}
    {% crispy form %}
{% endfor %}