更改Django模型形式的默认占位符的ForeignKey [英] Changing the default placeholder in a Django model form for a ForeignKey

查看:125
本文介绍了更改Django模型形式的默认占位符的ForeignKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码设置如下:

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

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

Basically, right now, without the widgets part, I get -------- as the placeholder for this field. However, I want to get 'Select the category', how can I do this? Thanks!

推荐答案

您可以使用 empty_label 字段:

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

    class Meta:
        model = Product

这篇关于更改Django模型形式的默认占位符的ForeignKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆