Table of contents
1.
Introduction
2.
Build a Django form scenarios
2.1.
forms.py
2.2.
views.py
3.
Description of all {{ field }} attributes
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Render Django Form Fields Manually

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django forms include a developer-friendly built-in feature, and Django has many different rendering build-in approaches. These methods, without a doubt, allow us to generate forms rapidly. Still, they also give us the least control over how they are rendered. There is no CSS or javascript in this HTML form. We can't have a user-friendly UI(user interface) without CSS, and we can't have a well-validated server-side form without javascript. So Django is wonderful for simple UI forms. Still, we render Django form fields manually to get a beautiful, user-friendly, more controlled Django template form.

Build a Django form scenarios

To understand the rendering of Django form fields manually through an example. Let’s consider a project having an app named test.

 

A new file, forms.py, can be created in our app to store all the forms. Django Form Class is required to develop a Django form. Let us see how.

forms.py

from django import forms

class TestForm(forms.Form):
   name = forms.CharField(max_length = 200)
   description  = forms.CharField(max_length = 500)
   contact_number = forms.IntegerField(
                    help_text = "Enter 10 digit mobile number"
                    )
   password = forms.CharField(widget = forms.PasswordInput())
You can also try this code with Online Python Compiler
Run Code

 

The field’s name is indicated on the left side, and the various functions of an input field are defined on the right side.

 

Create a data_view as shown to render this form into a view.

views.py

Construct an instance of the form class generated earlier in forms.py in view.

from django.shortcuts import render, redirect, reverse
from .forms import TestForm

def data_view(request):
   context ={}
   context['form']= TestForm()
   return render(request, "data.html", context)
You can also try this code with Online Python Compiler
Run Code

 

The below code has a form with a post method.

<form action = "" method = "post">
   {% csrf_token %}
   {{form }}
   <input type="submit" value=Submit">
</form>
You can also try this code with Online Python Compiler
Run Code

 

Output

 

As we can see, the UI is not very good, and it's also not a well-controlled form, which generates the need to render Django form fields manually.

 

as_table() renders the form using the template assigned to the forms template_name_table attribute. By default, this template is 'django/forms/table.html'.

as_ul() renders the form using the template assigned to the forms template_name_ul attribute. By default, this template is 'django/forms/ul.html'. 

as_p() renders the form using the template assigned to the forms template_name_p attribute. By default, this template is 'django/forms/p.html'.

 

They all work similarly. The only difference is the HTML code surrounding the inputs.

 

Render Django form fields manually.

Let’s fix the form by rendering it manually to make it look impressive.

<html>

<head>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<style>
.i-am-centered {
margin: auto;
max-width: 350px;
padding-top: 25%;
}
</style>
</head>

<body>
<div class="i-am-centered">
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label>First Name </label>
{{ form.name }}
</div>
<div class="form-group">
<label>description </label>
{{ form.description }}
</div>
<div class="form-group">
<label>Number</label>
{{ form.contact_number }}
</div>
<div class="form-group">
<label>Pwd</label>
{{ form.password }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>

</html> 

 

These were only some basic Bootstrap tweaks. Various CSS tricks and methods can be used to personalise it to an expert level.

 

output

 

Description of all {{ field }} attributes

When it comes to rendering Django form fields manually, we have to check out the description of the field attributes. 

Attributes

Description

{{ field.label }} Field labels, such as Name and Description, are rendered using the Label attribute.
{{ field.label_tag }} With the form's label suffix, the label tag attribute renders an entire appropriate label HTML tag. The colon is the default label suffix. Consider the following example: <label for="id_name">Name:</label>
{{ field.id_for_label }} It refers to the ID that will be used for this field. If we are manually creating the label, we might wish to use this instead of label_tag. It's also beneficial if we have inline JavaScript and don't want to hardcode the ID of the field.
{{ field.value }} This gives us the field's value
{{ field.html_name }} Specifies the field name that will appear in the name field of the input element. If the form prefix has been set, this is taken into account. For example Name
{{ field.help_text }} Any text that has been connected with the field as a source of help.
{{ field.errors }} This field generates an <ul class="errorlist"> that contains any validation errors. With a {% for error in field.errors %} in the loop, we can modify how the errors are shown. In this case, each item in the loop is a string with an error message.
{{ field.is_hidden }} If the form field is hidden, this property is True; otherwise, it is False. It's not particularly useful as a template variable, but it could be useful in conditional tests like: 
{% if field.is_hidden %} 
{# Do something special #}
{% endif %}
{{ field.field }} This BoundField covers a field instance from the form class. It may be used to get at Field attributes, such as  {{ name.field.max_length }}
{{ field.as_text }} This will display an HTML input tag, such as:  <input id=”id_description” name=”description” />
{{ field.as_textarea }}

The HTML Textarea tag will be rendered as a result. Example: 

<textarea name=”name” cols=”40″ rows=”10″ required id=”id_name></textarea>

{{ field.subwidgets }}

The subwidgets attribute aids in the rendering of a list of HTML Option tags.

Example: <option value=”published”>Published</option>, <option value=”pending”>Pending</option>

Frequently Asked Questions

  1. What is the default behavior of the fields in Django fields?
    The default behavior is that each field assumes that a value is required. If we pass None or an empty string then, Clean() will return a validation error.
     
  2. What is the use of the initial argument?
    The initial argument lets us specify the initial value to be used when rendering this field in an unbound form.

Key Takeaways

Django comes with a variety of built-in rendering options. We can build forms quickly with these, but we have the least control over how they are rendered. This HTML form doesn't have any CSS or javascript. Without CSS and javascript, we can't have a user-friendly UI or a well-validated server-side form. We can use various form field attributes to render Django form fields manually and get better control over our form.

If you loved reading this article discussing how to render Django form fields manually, check out Flask vs Django in 2021: Which Framework to Choose? and Advantages & Disadvantages of Django.

Live masterclass