简体   繁体   中英

Changing the default placeholder in a Django model form for a ForeignKey

I have my code set up as follows:

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!

You can set custom placeholder using empty_label field:

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

    class Meta:
        model = Product

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM