【问题标题】:How to set class to columns in django model formsets如何将类设置为 django 模型表单集中的列
【发布时间】:2014-09-17 00:41:43
【问题描述】:

有一个模型并用它来创建模型表单集。但是我看到 formset 为每个列提供 id ,例如 form 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 in form class .

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    您可以在表单中指定小部件中的属性:

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

    在此处查看完整文档:https://docs.djangoproject.com/en/dev/ref/forms/widgets/

    【讨论】:

    • 我试过这个,但它似乎不起作用,我想要它用于货币,这就是我所做的 currency = forms.CharField(widget=forms.HiddenInput(attrs={'class':'currencyClass' }), initial="USD"), 我做错了吗?
    • 它没有出现在您的 HTML 中?很奇怪,它对我有用,文档解释对我来说似乎很清楚:docs.djangoproject.com/en/dev/ref/forms/widgets/…。我不知道是什么导致了您的问题
    • 这可能是因为我使用的是表单集而不是表单,不确定,只是在思考?
    • 我想我明白了。您使用的是forms.ModelForm 而不是forms.Form。基本上,它从您的模型生成表单,我认为它没有考虑到您在 Meta 之前指定的内容。尝试将ModelForm 更改为Form
    • 我认为你是对的,但这似乎也不起作用,可能是因为我正在使用 modelformset_factory,因此它只是使用我的模型来创建表单,有没有办法在模型表单中指定类? ExpFormSet = modelformset_factory(Expenditure,extra=10,max_num=10,fields=('exp_date', 'description','amount','currency'),can_delete=False)
    猜你喜欢
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2019-03-06
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多