I'm trying to render a simple form with no db models but I am getting error. Following is the code:
from django import forms
from django.utils.safestring import mark_safe
class ContactForm(forms.Form):
category_options = (
('select category', '--Select Category--'),
('fire safety', 'Fire Safety'),
('batteries/solar panels', 'Batteries/Solar Panels'),
( 'cctv systems','CCTV Systems')
)
category = forms.ChoiceField(label="Select a Category", choices=category_options, required=True)
full_name = forms.CharField(required=False)
email = forms.EmailField()
phone = forms.CharField(widget=forms.IntegerField)
message = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 10}))
def clean_email(self):
email = self.cleaned_data.get('email')
return email
I'm not getting the phone field right. I need to add validation for phone numbers and couldn't figure out the right way to use widget for IntegerField.
I need to find the accurate way of adding a phone field.
I'm getting the error:
AttributeError at /contact/
'IntegerField' object has no attribute 'is_hidden'
I get following results when I use
phone = forms.CharField(widget=forms.NumberInput)
My html generated from the python code for different fields is following:
<p>
<label for="id_email">Email:</label>
<input id="id_email" name="email" type="email">
</p>
<p>
<label for="id_phone">Phone:</label>
<input id="id_phone" name="phone" type="number">
</p>
Both my fields above are generated with python code but email field is applying template css properly. But "Phone" field is not rendering css.
Please advise.
You assign the form field forms.IntegerField to "widget" which is wrong:
class ContactForm(forms.Form):
# ... # Wrong
phone = forms.CharField(widget=forms.IntegerField)
# ...
So, instead, you need to assign the widget forms.NumberInput to "widget" which is correct:
class ContactForm(forms.Form):
# ... # Correct
phone = forms.CharField(widget=forms.NumberInput)
# ...