GE04 ‐ 4 ‐ Forms (Abi Drennan) - wycre/CS3300-Team-2-9 GitHub Wiki
When creating a Form class, the primary focus lies in specifying the form's fields. Every field incorporates personalized validation logic alongside additional hooks. Forms primarily serve the purpose of collecting user input in various ways and utilizing this data for logical operations on databases. For instance, registering a user involves gathering information such as their name, email, password, and so forth.
Django maps the fields specified in Django forms into HTML input fields. Django takes care of three distinct parts of the work involved in forms:
- Organizing and formatting data to prepare it for display
- Generating HTML forms for the data
- Handling the reception and processing of submitted forms and data from the client

It's important to recognize that all the tasks performed by Django forms can be accomplished using advanced HTML techniques, but Django makes it easier and efficient, particularly with validation. Once you become familiar with Django forms, you will just forget about HTML forms.
Syntax: Django Fields work like Django Model Fields and have the syntax below:
field_name = forms.FieldType(**options)
Example:
from django import forms
# creating a form
class Form(forms.Form):
title = forms.CharField()
description = forms.CharField()
To use Django Forms, it's necessary to have a project set up with an app working in it. Once you've initiated an app, you can proceed to create a form within the app's forms.py file. Before starting to use a form, make sure to know how to start a project and implement Django Forms.
Creating a Django Form
Creating a form in Django is very similar to creating a model. It entails defining the fields that will be present in the form and their respective types. For example, to input, a registration form may require fields such as First Name (CharField), Roll Number (IntegerField), and so on. Syntax:
from django import forms
class FormName(forms.Form):
# each field would be mapped as an input field in HTML
field_name = forms.Field(**options)
Below is an example from forms.py in portfolio_app:
from django.forms import ModelForm
from .models import Project, Portfolio, Student
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# create class for project form
class ProjectForm(ModelForm):
class Meta:
model = Project
fields =['title', 'description',]
# create class for portfolio form
class PortfolioForm(ModelForm):
class Meta:
model = Portfolio
fields = ['title', 'is_active', 'about', 'contact_email']
Django form fields offer numerous built-in methods to simplify the developer's tasks, but sometimes manual implementation is necessary for customizing the User Interface (UI). A from comes with 3 built-in methods that can be used to render Django form fields:
-
{{forms.as_table}}will render them as table cells wrapped in<tr>tags -
{{forms.as_p_}}will render them wrapped in<p>tags -
{{forms.as_ul}}will render them wrapped in<li>tags
To render this form into a view, move to views.py and create a home_view as below:
from django.shortcuts import render
from .forms import InputForm
# create your views here
def home_view(request):
context = {}
context['form'] = InputForm()
return render(request, "home.html", context)
In view, one must create an instance of the form class created above in forms.py. Now you can edit templates > home.html
<form action = "" method = "post">
{% csrf_token %}
{{ form }}
<input type = "submit" value = "Submit">
</form>
Django ModelForm is a class that is used to directly convert a model into a Django form. If you're building a database-driven app, chances are you'll have forms that map closely to Django models. When the project is ready, create a model in models.py such as the one in portfolio_app:
from django.db import models
from django.urls import reverse
class Project(models.Model):
# fields of the model
title = models.CharField(max_lengthh=200)
description = models.TextField()
portfolio = models.ForeignKey('Portfolio', on_delete=models.CASCADE, default=None)
# rename the instances of the model with their title name
def __str__(self):
return self.title
# return the absolute URL of the Project instance
def get_absolute_url(self):
return reverse('project-detail', args=[str(self.id)])