How to render Django forms as a table

What are Django forms?

Django forms are similar to advanced HTMLHyperText Markup Language forms, except that they are more Python-oriented in nature.

To render Django forms as a table, you need to use the {{ form.as_table}} command.

Code

First, you will need to install Django, which can be done using the following commands:

pip install pipenv
pipenv shell
pipenv install django

Next, create your Django project:

django-admin startproject DjangoForm ./
python manage.py startapp codebase
python manage.py migrate
python manage.py runserver

Configurations

First, you will need to add the project name to go to the settings.py file, as shown below.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'codebase'
]

Note: codebase should be replaced by the name of your Django project.

Next, in the codebase application folder, go to the models.py file and create the following model:

from django.db import models
# Create your models here.
class DataModel(models.Model):
name = models.CharField(max_length = 200)
department = models.CharField(max_length=300)
age = models.IntegerField()
def __str__(self):
return self.name

Once your model is created, you need to register it in the admin.py file, as shown below:

from django.contrib import admin
from .models import DataModel
admin.site.register(DataModel)

Create the form

With the configuration complete, you can create a file for the form. In our case, the file is named forms.py.

from django import forms
class DataForm(forms.Form):
name = forms.CharField(max_length = 200)
department = forms.CharField(max_length = 200)
age = forms.IntegerField(
# help_text = "Enter 6 digit roll number",
widget=forms.NumberInput()
)

With the form created, you can now create a view for your project. The corresponding views.py file is shown below:

from django.shortcuts import redirect, render
from .models import DataModel
from .forms import DataForm
def home(request):
form = DataForm(request.POST or None)
if request.method == 'POST':
# form.is_valid() make the form to submit only
# when it contains CSRF Token
if form.is_valid():
# form.cleaned_data returns a dictionary of validated form input fields
name = form.cleaned_data['name']
department = form.cleaned_data['department']
age = form.cleaned_data['age']
queryset = DataModel(name=name,department=department, age=age)
queryset.save()
return redirect('home')
else:
pass
context = {
'form':form
}
return render(request, 'app/home.html', context)

Next, in the codebase app folder, create a folder and name it templates. Inside the templates folder, create another folder and name it app. Inside the app folder, create the home.html file as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action='.' method="POST">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="Submit">
</form>
</body>
</html>

Set route URLs

Within the main folder, in the urls.py file, you need to add a route to the URLs of the codebase app, as shown below:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# including the codebase urls.py file
path('', include('codebase.urls'))
]

Finally, in the codebase folder, create a file called urls.py that contains the route to the home view:

from django.urls import path
#importing home function from views.py
from .views import home
urlpatterns = [
path('', home, name='home'),
]

Access form

Once the entry process is complete, run the following commands:

python manage.py makemigrations

python manage.py migrate

In case you want to create a super-user, run the following command.

python manage.py createsuperuser

Once you’re ready to access your newly created form, run this command:

python manage.py runserver

The command above starts your server on the URL http://127.0.0.1:8000/admin, which you can now access.

Free Resources