Django Forms :-
Django provides a Form class which is used to create HTML forms.
It describes a form and how it works and appears.
It is similar to the ModelForm class that creates a form by using
the Model, but it does not require the Model.
Each field of the form class map to the HTML form <input> element
and each one is a class itself, it manages form data and performs
validation while submitting the form.
Building a Contact Form in Django :-
//forms.py file
from django import forms
class ContactForm(forms.Form):
full_name = forms.CharField(required=True)
email = forms.EmailField(required=True)
mob_no= forms.IntegerField(required=True)
message = forms.CharField(widget=forms.Textarea,required=True)
>A ContactForm is created that contains four fields of different types.
Charfield is a class and used to create an HTML text input component
in the form.
Instantiating Form in Django:-
Now, we need to instantiate the form in views.py file:-
// views.py
from django.shortcuts import render
from .forms import ContactForm
def index(request):
contact = ContactForm()
return render(request,"index.html",{'form':contact})
>Passing the context of form into index template that looks like this:
//index.html
<html>
<head>
<title>Index</title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Send">
</form>
</body>
</html>
>Provide the URL in urls.py
from django.contrib import admin
from django.urls import path
from mysite import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index,name="index"),
]
>>Run Server and access the form at browser by 127.0.0.1:8000/index
>There are other output options though for the <label>/<input> pairs:-
{{ form.as_table }} will render them as table wrapped in<tr>tags
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags
//Formatting of index.html :-
<html>
<head>
<title>Index</title>
</head>
<body>
<form method="POST">
{% csrf_token %}
<table border="2" align="center" width="400" height="450" rules="none">
<tr>
<td colspan="2" align="center"><h1><u>Contact Form</u></h1></td>
</tr>
<tr>
<td>Name: </td>
<td> {{form.full_name}}</td>
</tr>
<tr>
<td>Email: </td>
<td> {{form.email}}</td>
</tr>
<tr>
<td>Mobile No.:</td>
<td> {{form.mob_no}}</td>
</tr>
<tr>
<td>Message:</td>
<td> {{form.message}}</td>
</tr>
<tr>
<td colspan="2"><br>
<input type="submit" name="submit" value="Send">
</td>
</tr>
</table>
</form>
</body>
</html>