{{ form.as_table }} – Render Django Forms as table

Django provides built-in methods to render forms with different HTML structures. The form.as_table method renders form fields as table rows, providing a structured and organized layout for user input forms.

Why Use form.as_table?

Rendering Django forms as tables offers several advantages:

  • Structured layout: Table format provides a clean and organized appearance, making forms easier to read and interact with.

  • Consistent alignment: Labels and input fields align properly across different field types and lengths.

  • Quick implementation: Minimal template code required compared to manual HTML form creation.

  • Accessibility: Screen readers can better interpret the relationship between labels and form fields.

Setting Up the Project

First, create a new Django project and app:

pip install django
django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Creating the Form

Create a forms.py file in your app directory and define a form class:

from django import forms

class UserForm(forms.Form):
    first_name = forms.CharField(max_length=50, label="First Name")
    last_name = forms.CharField(max_length=50, label="Last Name")
    email = forms.EmailField(label="Email Address")
    age = forms.IntegerField(min_value=1, max_value=120, label="Age")
    bio = forms.CharField(widget=forms.Textarea(attrs={'rows': 3}), label="Biography")

Creating the View

Update views.py to handle the form:

from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserForm

def user_form_view(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            return HttpResponse("Form submitted successfully!")
    else:
        form = UserForm()
    
    return render(request, 'form.html', {'form': form})

Creating the Template

Create a templates directory in your app and add form.html:

<!DOCTYPE html>
<html>
<head>
    <title>User Registration Form</title>
    <style>
        .form-table {
            border-collapse: collapse;
            width: 100%;
            max-width: 600px;
            margin: 20px auto;
        }
        .form-table td {
            padding: 10px;
            border: 1px solid #ddd;
        }
        .form-table input, .form-table textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <h2>User Registration</h2>
    <form method="POST">
        {% csrf_token %}
        <table class="form-table">
            {{ form.as_table }}
        </table>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

URL Configuration

Create urls.py in your app directory:

from django.urls import path
from .views import user_form_view

urlpatterns = [
    path('', user_form_view, name='user_form'),
]

Update the main project's urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

Adding the App to Settings

Add your app to INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',  # Add your app here
]

Running the Application

Start the development server:

python manage.py runserver

Navigate to http://127.0.0.1:8000/ to see your form rendered as a table.

Comparison with Other Form Rendering Methods

Method Output Format Best For
form.as_table Table rows (<tr><td>) Structured, aligned forms
form.as_p Paragraphs (<p>) Simple, responsive layouts
form.as_ul List items (<li>) When using custom CSS frameworks

Best Practices

  • Always include CSRF protection: Use {% csrf_token %} in your forms to prevent cross-site request forgery attacks.

  • Add proper styling: Include CSS to make your table forms responsive and visually appealing.

  • Handle form validation: Always validate form data on the server side before processing.

  • Use semantic HTML: Wrap the table in a <form> element and include proper labels.

Conclusion

The form.as_table method provides a quick and structured way to render Django forms. It creates well-aligned, accessible forms with minimal template code, making it ideal for admin interfaces and data entry forms.

Updated on: 2026-03-27T07:22:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements