How do I change input type of form field in django forms?

I have a form class in my form.py file where I initiated properties of form fields. I want to change my 'Description' field from an input field to a textarea field of height 5 lines. Also want to change my 'Deadline' field to a date input field because at the moment it's an input text field.

class JobPost_form(ModelForm):
class Meta:
    model = Job_post
    fields = "__all__"

def __init__(self, *args, **kwargs):
    self.fields['Job_role'].widget.attrs.update(
        {'class': 'form-control Password2', 'id': 'form3Example1c', 'placeholder': 'Job role'})
    self.fields['Company'].widget.attrs.update(
        {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Company'})
    self.fields['Deadline'].widget.attrs.update(
        {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'YYYY-MM-DD HH:MM:SS'})
    self.fields['Description'].widget.attrs.update(
        {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Description'})

I think that in the code you have passed a tabulation is missing since the meta and the init will be inside the class: JobPost_form. As for marking the description field as a textarea you should do:

class JobPost_form(ModelForm):
    description = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}))

    class Meta:
        model = Job_post
        fields = "__all__"

    def __init__(self, *args, **kwargs):
...

You can achieve those things using wigets(attrs="{}") which provided by django in forms api

models.py

class DemoClass(models.Model):
    description = models.TextField()
    deadline = models.DateField()

form.py

class DemoForm(forms.ModelForm):
    class Meta:
        model = DemoClass
        fields = "__all__"

        widgets={
            'description':forms.Textarea(attrs={"rows":"4", "cols":"50"}),
            'deadline':forms.TextInput(attrs={'type':'date'}),
            --------------- OR -------------------------------
            'deadline':forms.DateInput(attrs={'type':'date'}),
            
        }

HTML

{% block body %}
  <div class="container">
    <div class="row">
      <div class="col-lg-12">

        {{form.as_p}}
        
      </div>
    </div>
  </div>
{% endblock body %}

Output

enter image description here

Back to Top