如何在我们使用inlineformset_factory函数的formset字段中添加类属性

时间:2019-03-28 06:54:47

标签: django django-forms

如果我在SupplierForm中添加unit_price字段,则它确实会反映在我的模板上并添加了class属性,但它同时添加了两种形式。我想仅覆盖unit_price条目表单。我该怎么做。

class SupplierForm(forms.ModelForm):
    # unit_price = forms.FloatField(widget=forms.TextInput(
    #         attrs={
    #         'class':'product_price',
    #         }
    #     ))

    # VAT = forms.FloatField(widget=forms.TextInput(
    #         attrs={
    #         'class':'product_vat',
    #         }
    #     ))

    class Meta:
        model = Supplier
        exclude = ['uploaded_by', 'approved_by','unit_price']
        labels = {
        "payment_due_date": "Payment Due Date / Paid Date"
         }
        help_texts = {
            'invoice_date': '<b>Click on arrow for calendar</b>',
            'payment_due_date': '<b>Click on arrow for calendar</b>',
        }
        widgets = {
            'invoice_date': DateInput(format="%d %b %Y"),
            'payment_due_date':DateInput(),

        }

# I have added here unit_price field for add class attribute in this field but there is no reflect on template
class EnteriesForm(ModelForm):
    unit_price = forms.FloatField(widget=forms.TextInput(
            attrs={
            'class':'product_price',
            }
        ))
    class Meta:
        model = Enteries
        exclude = ()
        help_texts = {
            'unit_price': '<b>Click on arrow for calendar</b>',

        }

EnteriesFormSet = inlineformset_factory(Supplier, Enteries,
                                            form=SupplierForm,exclude=['uploaded_by'],extra=1)

1 个答案:

答案 0 :(得分:0)

您可以找到here,但只需更改form。并且一旦声明了form,则在声明fields时就不再需要使用excludeformset了,因为所有这些都应在{{1}中设置}

form

您确实应该返回并阅读class EnteriesForm(ModelForm): unit_price = forms.FloatField(widget=forms.TextInput( attrs={ 'class':'product_price', } )) class Meta: model = Enteries exclude = () help_texts = { 'unit_price': '<b>Click on arrow for calendar</b>', } EnteriesFormSet = inlineformset_factory( Supplier, Enteries, # this is where you select what form you want to use: form=EntriesForm, # 'uploaded_by' is not even apart of this form. # You should remove this. # exclude=['uploaded_by'], # 'extra': default is '1', so you don't really need this. # extra=1 ) 上的所有信息。继承为formsets-> formset-> modelformset,因此适用于inlineformset的所有内容都适用于formset