Django Crispy Form显示{'id':['此字段为必填。']}

问题描述 投票:0回答:1

当我使用Crispy Forms单击嵌入式表单集上的保存按钮时收到以下错误:

[{'id':['此字段为必填。']},{'id':['此字段为必填。']},{'id':['此字段为必填。']} ,{},​​{}]

由于缺少ID,该表单集已绑定但无效,但是我不确定如何设置ID。

#views.py
    class View(LoginRequiredMixin, TemplateView):
        template_name = "example.html"
        MyFormSet = modelformset_factory(
            model=MyModel,
            form=MyModelForm,
            formset=MyModelFormset,
            can_delete=True,
            extra=1,
            fields=('field_1','field_2', ))

        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            my_formset = self.MyFormSet()
            context['my_formset'] = MyModel.objects.all().order_by('field_1')
            return context

        def post(self, request, *args, **kwargs):
            my_formset = self.MyFormSet(request.POST, request.FILES)
            if my_formset.is_valid():
                try:
                    my_formset.save()
                except:
                    messages.add_message(request, messages.ERROR, 'Cannot delete: this parent has a child 1 !')
            else:
                context = self.get_context_data()
                context['my_formset'] = my_formset
                return render(request, self.template_name, context)
            return HttpResponseRedirect(reverse_lazy("example"))

#forms.py
    class MyForm(forms.ModelForm):
        class Meta:
            model = MyModel
            fields = ['field_1', 'field_2']


        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.helper = FormHelper()
            self.helper.form_tag = False
            self.helper.layout = Layout(
                Row(
                    Column('field_1'),
                    Column('field_2'),
                    Column('DELETE'),
                )
            )



#template
    <form action="" enctype="multipart/form-data" method="post">{% csrf_token %}        
        {{ my_formset.management_form|crispy }}
        {% for form in my_formset.forms %}
            {% crispy form form.helper %}                            
        {% endfor %}
        <button class="btn btn-success" type="submit">Save</button>
    </form>
django django-crispy-forms inline-formset
1个回答
0
投票

[使用布局作为表单集的一部分来呈现表单时,必须设置render_hidden_​​fields = true。请参阅文档中的更多说明。

https://django-crispy-forms.readthedocs.io/en/latest/form_helper.html

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.