Reputation: 744
I have a django form setup like so:
from django import forms
class ContactForm(forms.Form):
full_name = forms.CharField(max_length=20)
phone = forms.CharField(max_length=20)
email = forms.CharField(max_length=30)
message = forms.CharField(max_length=400)
class Meta:
fields = ['full_name', 'phone', 'email', 'message']
widgets = {
'full_name': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Full Name'}),
'phone': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Phone Number'}),
'email': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'E-Mail Address'}),
'message': forms.TextInput(attrs={'class': 'dis-block s-text7 size20 bo4 p-l-22 p-r-22 p-t-13 m-b-20', 'placeholder': 'Message'}),
}
Which works fine. However, I recently learned that class Meta
can only be used with ModelForms.
I need to assign attributes like the above in my form, in forms.py. I understand it is bad practice to mix business and presentation logic, but I am dealing with a complicated paid web template at the moment, and methods to apply attributes using template tags have not worked so far. Given I am on a deadline, I am postponing assigning attributes that way as a v2 feature.
My question is, if class Meta can only be used with forms that have a corresponding model, how can I assign attributes to form widgets in forms that do not correspond to a model and thus cannot use class Meta?
Upvotes: 1
Views: 50
Reputation: 7049
You can use inline widgets.
An example used is as follows:
class CommentForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
url = forms.URLField()
comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))
Upvotes: 1