更改ForeignKey的Django模型表单中的默认占位符

时间:2017-04-30 20:23:41

标签: python django django-forms

我的代码设置如下:

models.py

class Category(models.Model):
    name = models.CharField(max_length=255)

class Product(models.Model):
    category = models.ForeignKey(Category)

forms.py

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ('category',)
        widgets = {
            #'category' : forms.TextInput(attrs={'placeholder' : 'Select the category'}),
        }

基本上,现在,如果没有小部件,我会将--------作为此字段的占位符。但是,我想要“选择类别”,我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用empty_label字段设置自定义占位符:

class ProductForm(forms.ModelForm):
    category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label='Select the category')

    class Meta:
        model = Product