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

2024-04-25 00:56:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码设置如下:

模型.py

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

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

表单.py

^{pr2}$

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


Tags: 代码namepy模型表单modelmodelsproduct
1条回答
网友
1楼 · 发布于 2024-04-25 00:56:15

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

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

    class Meta:
        model = Product

相关问题 更多 >