【问题标题】:Django inline formsets updating a modelDjango 内联表单集更新模型
【发布时间】:2018-09-08 16:27:12
【问题描述】:

我正在努力让 Django 的表单集在更新模型时正常工作。

我有 2 个模型,ProductProductSize。在添加或编辑Product 时,我使用内联表单集将我的ProductSizes 链接到Products。添加对象很好,但是当我尝试编辑Product 时,我无法提交表单。我在下面的print 中得到[{'id': ['This field is required.']}] 输出。

以下是我的观点:

class ProductAdd(AddModelView):
    model = Product
    form_class = UpdateProductForm
    template_name = 'intake_goods_form.jinja'
    title = 'Add Product Type'
    formset_class = ProductSizesFormSet

    def form_valid(self, form):
        obj = form.save()
        formset = self.formset_class(self.request.POST)
        if formset.is_valid():
            formset.instance = obj
            formset.save()
        else:
            print(formset.errors)
            return self.form_invalid(form)
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        if self.request.POST:
            formset = self.formset_class(self.request.POST, instance=self.object)
        else:
            formset = self.formset_class(instance=self.object)
        return super().get_context_data(formsets=formset, **kwargs)


product_type_add = ProductAdd.as_view()


class ProductEdit(ProductAdd, UpdateModelView):
    model = Product
    form_class = UpdateProductForm


product_type_edit = ProductEdit.as_view()

这是我的表格:

class UpdateProductForm(SVModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    class Meta:
        model = Product
        exclude = {'material'}


class ProductSizeForm(SVModelForm):
    title = 'Product Type Sizes'

    class Meta:
        model = ProductSize
        fields = ['sku_code', 'bar_code', 'size']


ProductSizesFormSet = forms.inlineformset_factory(Product, ProductSize, ProductSizeForm, extra=1, can_delete=False)

谁能帮忙?

谢谢

【问题讨论】:

  • ProductEdit 不应继承自 ProductAdd。这就是为什么 python MRO 执行来自 ProductAdd 的错误方法但忽略来自 UpdateModelView 的正确方法的原因。
  • 这不是解决方案,但无论如何谢谢:)

标签: django inline-formset


【解决方案1】:

好的,所以我找到了解决方案,但从我发布的问题中无法弄清楚,抱歉。

在模板中,我只是在表单集的可见字段中循环。所以当然不包括 ID。

如果需要,请确保在模板中包含 formset.id 字段。

【讨论】:

    猜你喜欢
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2010-09-30
    • 2011-06-10
    • 2013-11-10
    • 2010-10-12
    相关资源
    最近更新 更多