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

时间:2014-07-25 08:09:58

标签: python django django-forms

有一个模型并用它来创建模型表单集。但是我看到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']。widget.attrs ['readonly'] =表单类中的True。

1 个答案:

答案 0 :(得分:1)

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

class ExpenditureForm(forms.ModelForm):

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

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