I’m aware that there is many post like this, but can you spot the typo or error in my code?
I’m adding custom classes to my forms but when I inspect the element on the web page there are none. The same goes for placeholder.
Code:
Views.py:
JavaScript
x
7
1
def render_main(request):
2
form = AuthorForm()
3
context = {
4
'form' : form
5
}
6
return render(request,'nglib/search.html', context)
7
Template file:
JavaScript
1
8
1
{% csrf_token %}
2
<div class="col-6">
3
{{form.name}}
4
</div>
5
<div class="col-6">
6
{{form.surname}}
7
</div>
8
Forms.py:
JavaScript
1
29
29
1
from django.core.exceptions import ValidationError
2
from django.forms import ModelForm
3
from .models import SearchStats
4
from django import forms
5
import re
6
7
8
def isStandardized(value):
9
if not re.compile(r'^[a-zA-Z ]+$').match(value):
10
raise ValidationError('Enter only english characters')
11
return True
12
13
class AuthorForm(ModelForm):
14
15
name = forms.CharField(validators=[isStandardized])
16
surname = forms.CharField(validators=[isStandardized])
17
18
class Meta:
19
model = SearchStats
20
fields = ['name', 'surname', 'author_id', 'amount']
21
22
widgets = {
23
'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Name of an author'}),
24
'surname': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Surname of an author'}),
25
'author_id': forms.TextInput(attrs={'type':'hidden'}),
26
'amount': forms.TextInput(attrs={'type':'hidden'})
27
}
28
29
Advertisement
Answer
I think, you already specified the fields name
and surname
in the class itself, so you should use inline widgets not Meta widgets, as they are used for overriding default widgets, so:
JavaScript
1
14
14
1
class AuthorForm(ModelForm):
2
3
name = forms.CharField(validators=[isStandardized],widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Name of an author'}))
4
surname = forms.CharField(validators=[isStandardized],widget=forms.TextInput(attrs={'class':'form-control','placeholder':'surname of an author' }))
5
6
class Meta:
7
model = SearchStats
8
fields = ['name', 'surname', 'author_id', 'amount']
9
10
widgets = {
11
'author_id': forms.TextInput(attrs={'type':'hidden'}),
12
'amount': forms.TextInput(attrs={'type':'hidden'})
13
}
14