如何在django模型formsets中将类设置为列

有一个模型,并用它来创建模型表单集 . 但是我看到formset给每个列赋予id,比如0表格将有id_0_exp_date然后是id_1_exp_date等,但我在寻找是否有办法将类设置为列,所以所有exp_date表单都有相同的类 . 我想要这种行为,所以我可以轻松地在这些查询中指定jquery和css . 我在文档中找不到这个但我觉得应该有办法做到这一点..

models.py:

class Expenditure(models.Model):
    exp_date = models.DateField("Expenditure_Date")
    description = models.CharField(max_length=500)
    amount = models.FloatField(default=0)
    currency = models.CharField(max_length=15,default="USD",editable=True)

    class Meta:
        unique_together = ('exp_date', 'description',)

    def __unicode__(self):
        return self.description

forms.py

class ExpenditureForm(forms.ModelForm):

    exp_date = forms.DateField(widget=AdminDateWidget)
    description = forms.CharField(max_length=500)
    amount = forms.FloatField(initial=0)
    currency = forms.CharField(widget=forms.HiddenInput(), initial="USD")
"""
def __init__(self, *args, **kwargs):
    super(ExpenditureForm, self).__init__(*args, **kwargs)
    if self.instance.id:
        self.fields['currency'].widget.attrs['readonly'] = True
"""
# An inline class to provide additional information on the form.
    class Meta:
        # Provide an association between the ModelForm and a model
        model = Expenditure

提前致谢

基本上我想让货币字段只读,但似乎由于某些问题它不起作用或者我可能做错了什么:

我试过的:1 . currency = forms.CharField(widget = forms.HiddenInput(attrs = {'class':'currencyClass'}),initial =“USD”)2 . self.fields ['currency'] . 小部件 . attrs ['readonly'] =表格类中的True .

回答(1)

2 years ago

您可以在窗体中的窗口小部件中指定属性:

class ExpenditureForm(forms.ModelForm):

   exp_date = forms.DateField(widget=AdminDateWidget(attrs={'class':'nameOfYourClass'}))

请参阅此处的完整文档:https://docs.djangoproject.com/en/dev/ref/forms/widgets/