Reputation: 4808
I am trying to handle a form in django. I am from PHP background, and never used any framework. I used to write all fields of the form by myself in HTML as well as in backend. I used my own methods to validate them.
Now, coming to django, it has model form. But, I want to use bootstrap too in my code. So, I wrote HTML code like this:
<div class='form-group'>
<label class='control-label col-md-2 col-md-offset-2' for='id_email'>Contact</label>
<div class='col-md-6'>
<div class='form-group'>
<div class='col-md-11'>
<input class='form-control' id='id_email' placeholder='E-mail' type='text'>
</div>
</div>
<div class='form-group internal'>
<div class='col-md-11'>
<input class='form-control' id='id_phone' placeholder='Phone: (xxx) - xxx xxxx' type='text'>
</div>
</div>
</div>
</div>
Now, I want to validate it at backend. My model looks like:
class Student(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=200)
enrollment_no = models.CharField(max_length=10)
batch = models.CharField(max_length=4)
father_income = models.IntegerField(max_length=100)
email = models.CharField(max_length=1000)
mobile_number = models.CharField(max_length=1000)
Now, what is the best way to validate above form? Please help me to solve this.
Upvotes: 1
Views: 3837
Reputation: 967
For your form, you can use django's model form. You can add some definition to your model form with the class Meta
:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = [
'name', 'enrollment_no', # etc...
]
widgets = {
'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Title', 'required': True, } ),
'enrollment_no': # etc...
}
# you can also override validation/clean/save/etc methods here
*Note - because all of your fields are required (according to your model, and because we're using a model form here), django will validate requiring all fields.
Then in your template (assuming you pass the form instance in the context to your template as form
) you can access each field like so:
...
...
<div class='col-md-11'>
{{ form.name }}
</div>
...
...
Upvotes: 2