Django formset错误

时间:2018-02-24 01:20:21

标签: python django django-forms

我正在尝试将订单项设置为django(费用)中的一个formset,以添加到工作订单中。我已经尝试将字段直接添加到ChargesCreateView中的modelformset_factory中,但仍然没有(尽管我已经在forms.py中设置了字段)。

错误是

ImproperlyConfigured at /workorders/charges/create/1219/
Using ModelFormMixin (base class of ChargesCreateView) without the 'fields' attribute is prohibited.

view.py

class ChargesCreateView(generic.CreateView):
    # form_class = LineitemForm
    LineitemFormSet = modelformset_factory(Lineitem,form=LineitemForm)
    formset = LineitemFormSet()
    template_name = 'workorders/form_create_charges.html'
    success_url   = '/workorders/'

    def get_initial(self):
       return { 'workorder': self.kwargs.get('pk'),}

    def get_queryset(self):
        workorders = Workorder.objects.all().values()
        return workorders

model.py

class Lineitem(models.Model):
    workorder       = models.ForeignKey('Workorder', null=False, on_delete=models.CASCADE)
    sku             = models.CharField(max_length=20)
    description     = models.CharField(max_length=100)
    qty             = models.IntegerField(null=True)
    unit_price      = models.IntegerField(null=True)
    discount        = models.IntegerField(null=True)
    amount          = models.IntegerField(null=True)

    def __str__(self):
        return self.sku

forms.py

class LineitemForm(forms.ModelForm):

    class Meta:
        model = Lineitem
        fields = [
            'workorder',
            'sku'
        ]
        widgets = {
            'workorder': forms.HiddenInput(),
        }

form_create_charges.html

<form method="post" novalidate>
                {% csrf_token %}
                <table border="0">
                    {{ formset.management_form }}
                    {{formset}}
                </table>
                <button type="submit" class="btn btn-primary">Submit</button> | <a href="{% url 'workorders:index' %}">Cancel</a>
            </form>

1 个答案:

答案 0 :(得分:0)

可能只使用FormView,而不是使用generic.CreateView。 CreateView根据指定的模型和字段创建表单对象,这就是为什么它希望您添加字段变量。