How to set placeholder for django integerfield

Question:

I have a model form:

class CaseForm(ModelForm):
    class Meta:
        model = Case
        fields = ["sex", "age"]

With corresponding model:

class Case(TimeStampedModel):
   id = models.UUIDField(
        primary_key=True, unique=True, default=uuid.uuid4, editable=False
    )

    user = models.ForeignKey(
        get_user_model(), blank=False, null=True, on_delete=models.SET_NULL)
    
    age = models.IntegerField("Age")
    SEX_CHOICES = [
                ("male", "Male"),
                ("female", "Female"),
                ('', "Sex")
    ]

    sex = models.CharField("Sex", max_length=20, choices=SEX_CHOICES, blank=False)

This displays a placeholder of ‘Sex’ for one field and I would like to display the a similar placeholder for ‘Age’.

One method I have seen is:

class CaseForm(ModelForm):
    age = IntegerField(label='Age', widget=TextInput(attrs={'placeholder': 'Age'}))
    class Meta:
        model = Case
        fields = ["sex", "age"]

However when this is rendered, although ‘Age’ is there as a placeholder, the field no longer behaves like an integer field.

Any advice?

Asked By: RobMcC

||

Answers:

The default widget for IntegerField() is NumberInput, so:

class CaseForm(ModelForm):
    age = IntegerField(label='Age', widget=NumberInput(attrs={'placeholder': 'Age'}))
    class Meta:
        model = Case
        fields = ["sex", "age"]
Answered By: Sunderam Dubey