数据未在formset django中验证。错误“无法创建NameOfModel,因为数据未验证。”

时间:2017-03-19 00:46:24

标签: python django formset

我正在构建一个formset,但是当我尝试保存数据时,出现错误“无法创建字段,因为数据未验证。”

我的forms.py

class Formulario(ModelForm):
    class Meta:
        model = Fields
        fields = ['name','type']

FieldsFormSet = formset_factory(Formulario)

我的views.py

class BuildForm(CreateView):
    template_name = 'formulario.html'
    model = Fields
    form_class = Formulario
    success_url = 'success/'

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        fields_form = FieldsFormSet(self.request.POST,self.request.FILES)
        if fields_form.is_valid():
            return self.form_valid(form, fields_form)
        else:
            return self.form_invalid(form, fields_form)

    def form_valid(self, form, fields_form):
        self.object = form.save()
        fields_form.instance = self.object
        fields_form.save()

    def form_invalid(self, form, fields_form):
        return self.render_to_response(self.get_context_data(form=form,fields_form=fields_form))

template.html

<form action="." method="POST">{% csrf_token %}
    <div class="section">
    </div>
    <h2>Todo Items</h2>
    {{ fields_form.management_form }}
    {% for form in fields_form.forms %}
    <div class="item">
      {{ form.as_p }}
      <p style=""><a class="delete" href="#">Delete</a></p>
    </div>
    {% endfor %}
    <p><a id="add" href="#">Add another item</a></p>
    <input type="submit" value=" Submit " />
</form>

奇怪的是,它确实会在form_valid()

之前进行验证

0 个答案:

没有答案