django forms getting started¶
django forms are allow user to enter the data and send it to the server to use it further. django forms are powerful and generates the html form elements which simplifies developers life easy.
Basics of HTML form¶
Let's understand the basics of HTML form from below example.
<form action="/contact-us/" method="POST" enctype="multipart/form-data">
<label>First Name</label>
<input name="first_name" value="" />
<label>Last Name</label>
<input type="text" name="last_name" value="" />
<label> Message </label>
<textarea name="message"></textarea>
<input type="submit" value="Submit" />
</form>
- action: It specifies where to send the form-data when a form is submitted
- method: Type of request when the form is submitted
- enctype: encrypion type for the form data. "multipart/form-data" allows us to send the text and files data aswell.
- For more details on HTML forms visit https://www.w3schools.com/html/html_forms.asp
Django Forms and it's usage¶
In the above example we have written html code for the form. By using django forms we can simplify it with django form template tags like below. Let's write code to save the contact info the database. We will not be creating the django app from the scratch but we will write model and view and template and urls for the functionality.
models.py
from django.db import models
class ContacIfo(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
message = models.TextField()
def __str__(self):
return self.first_name
forms.py
from django import forms
from .models import ContacIfo
class ContactInfoForm(forms.ModelForm):
class Meta:
model = ContacIfo
fields = ('first_name', 'last_name', 'message')
views.py
from .forms import ContactInfoForm
from django.http import HttpResponse
from django.shortcuts import render
def create_contact_info(request):
if request.method == 'POST':
form = ContactInfoForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("Saved Contact info.")
else:
form = ContactInfoForm()
context = {'form': form}
return render(request, 'template.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
# ....
path('contact-info/', views.create_contact_info, name='contact_info'),
# ....
]
template.html
<html>
<title>Create Contact Info</title>
<body>
<form action="{% url 'contact_info' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit" />
</form>
</body>
</html>
Above code is used to save the contact info on the database.
- Django forms are two types 1. Model forms (i.e "
forms.ModelForm
") and 2. Forms (i.e "forms.Form
") - "
forms.ModelForm
" more advantages over the "forms.Form
" like we can save the object in the database directly usingsave
method of "forms.ModelForm
" but, it's not available for "forms.Form
". - "
{% csrf_token %}
" in template will create a csrfmiddleware token that used for security protection. It's must for POST requests but it's not needed for GET requests. - Django forms comes with inbuilt validations on the form fields, "
is_valid()
" method is used to validate the correctness of the form data.
It's just basic start for the django forms usage. Let's learn more about django forms in the next article. You can find the above project code at my github account "django forms getting started".
Reference: https://docs.djangoproject.com/en/3.0/topics/forms/