python - 更改 Django 模型表单中外键的默认占位符

标签 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'}),
        }

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

最佳答案

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

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

    class Meta:
        model = Product

关于python - 更改 Django 模型表单中外键的默认占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43710970/

相关文章:

python - 函数在子类中不被覆盖

python - 根据使用多列的条件聚合 Pandas DataFrame?

python - 如何在python中计算数组的绝对值?

python - 如何在 django channel 中设置连接超时?

python - Django FormWizard 如何动态更改 form_list

django - 如何使 Django 表单在验证失败后保留文件

python - 如何替换为正则表达式命名组?

python - 如何将输出文件从 Django 保存到 Amazon S3

python - 网站会自行从拒绝服务攻击中恢复吗?

python - __init__() 得到了一个意外的关键字参数 'user'