Creating forms with Django

Most websites require a form. Unless you are developing a website or application that only publishes articles and does not require user input, a form is not required on your application.

Generally, the standard way in which web applications accept users' input is through HTML forms. An HTML form is a collection of elements inside the <form>form> tag. The user inputs some data using the form and submits it to the server for processing. Basically, Django handles more of the form functionality on the server side. Django forms are automatically rendered in plain HTML on the template. It is rendered in simple HTML to make the front end design very flexible. To render the form, the form instance is place in the template.  So if your form is called form in the context, {{ form }} will render its <label> and <input> elements appropriately. 

Now, let's create a form using the Django Modelform class. The form we will create is a contact form. 

The Django ModelForm is usually used to convert a Django model into a form. In a situation where we have a Django model that has similar fields to the form you are about to create, it is advisable to use a Django ModelForm that will map the fields of the Django model to the fields of the form. This practice eliminates redundancy and saves time. 

Model.py file

from django.db import model

class Contact(models.Model):
name = model.CharField(max_length = 200)
email = models.EmailField()
phone = models.CharField(max_length = 15)
message = models.TextField()

def __str__(self):
return self.name

We have created a model that has the fields name, email, phone, and message. Now we will match the field with the modelform class in the forms.py file.

forms.py file

from django.forms import ModelForm
from .models import Contact

class ContactForm(ModelForm):
class Meta:
model = Contact
fields = ["name", "email", "phone", "message"]

The form has been created. Now let's write the code on how the form will function in the view file.

views.py

from .forms import ContactForm
from django.http import HttpResponseRedirect
From django.shortcuts import render

def index(request):
form = contactForm()
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
email = form.cleaned_data["email"]
phone = form.cleaned_data["phone"]
message = form.cleaned_data["message"]
form.save()
return HttpResponseRedirect('/thanks/')
context = {"form" : form }
return render(request, "index.html", context)

We defined a function named index(). The variable form is used to store the contactForm. We check if the user's form is a POST request and if it's valid. If the form is_valid is True, we will now be able to find all the validated form data in its cleaned_data attribute. After submission, the database will be updated, and will send HttpResponseRedirect to the url /thanks/. 

Templates

<body>
<div class = "content">

<form method ="POST" id='form'>
{% csrf_token %}
{{ form }}
<button type = "submit" class = " btn btn-primary">Send</button>
</form>
<style>
.content {
top: 50px;
margin: auto;
position: absolute;
right: 500px;
width: 800px;
border: 20px solid #73AD21;
padding: 10px;
}
</style>
</div>
</body>

The {% csrf_token %} is used in the template that uses a POST form for security reasons.

Url.py

from django.urls import path
from . import views


urlpatterns = [
path('', views.index, name = 'indexpage'),

path('thanks/', views.index),]

The form will look like so:

After submission check the changes in the Url. 

In the admin admin section, you will see the submitted forms like so;

If you want to learn how to beautify your django form, you can use django crispy form.  Check the link below to see how to use the Django crispy form