Reputation: 73
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'})
Upvotes: 0
Views: 1608
Reputation: 11
I found a way to alter completely the input. In this code I changed it to type=range and added also bootstrap classes to it.
class RangeBooted(Input):
def get_context(self, name, value, attrs):
ctx = super(RangeBooted, self).get_context(name, value, attrs)
ctx['widget']['type'] = "range"
ctx['widget']['attrs']['class'] = "form-range bg-secondary rounded shadow w-75 p-2"
ctx['widget']['attrs']['min'] = "0"
ctx['widget']['attrs']['max'] = "100"
ctx['widget']['attrs']['step'] = "2"
return ctx
Upvotes: 0
Reputation: 3635
You can achieve those things using wigets(attrs="{}") which provided by django in forms api
class DemoClass(models.Model):
description = models.TextField()
deadline = models.DateField()
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'}),
}
{% block body %}
<div class="container">
<div class="row">
<div class="col-lg-12">
{{form.as_p}}
</div>
</div>
</div>
{% endblock body %}
Upvotes: 0
Reputation: 374
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):
...
Upvotes: 0