The Wayback Machine - https://web.archive.org/web/20241001042122/https://www.geeksforgeeks.org/render-django-form-fields-manually/
Open In App

Render Django Form Fields Manually

Last Updated : 22 Jul, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to render Django form fields. 
 

These render the form automatically but if you want to create a beautiful form with some CSS effects, you need to render the form fields manually. This article revolves around how to render the form fields manually.
 

Rendering Form fields manually

Illustration of Rendering Django Forms Manually using an Example. Consider a project named geeksforgeeks having an app named geeks. 
 

Refer to the following articles to check how to create a project and an app in Django. 
 

In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate how, 
In your forms.py Enter the following, 
 

Python3




from django import forms
  
# creating a form 
class InputForm(forms.Form):
  
    first_name = forms.CharField(max_length = 200)
    last_name = forms.CharField(max_length = 200)
    roll_number = forms.IntegerField(
                     help_text = "Enter 6 digit roll number"
                     )
    password = forms.CharField(widget = forms.PasswordInput())


Let’s explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as 
Syntax : 
 

Field_name = forms.FieldType(attributes)

Now to render this form into a view, move to views.py and create a home_view as below. 
 

Python3




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 needs to just create an instance of the form class created above in forms.py. 
Now let’s edit templates > home.html 
 

html




<form action = "" method = "post">
    {% csrf_token %}
    {{form }}
    <input type="submit" value=Submit">
</form>


All set to check if form is working or not let’s visit http://localhost:8000/ 
 

create-django-form

. 
Form is working properly but visuals are disappointing, We can render these fields manually to improve some visual stuff. Each field is available as an attribute of the form using {{ form.name_of_field }}, and in a Django template, will be rendered appropriately. For example: 
 

{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="{{ form.subject.id_for_label }}">Email subject:</label>
    {{ form.subject }}
</div>

.
Let’s modify our form to look pretty impressive, 
 

html




<html>
  
<head>
    <link 
     rel="stylesheet"
    <style>
        .i-am-centered {
            margin: auto;
            max-width: 300px;
            padding-top: 20%;
        }
    </style>
</head>
  
<body>
    <div class="i-am-centered">
        <form method="POST">
            {% csrf_token %}
            <div class="form-group">
                <label>First Name </label>
                {{ form.first_name }}
            </div>
            <div class="form-group">
                <label>Last Name </label>
                {{ form.last_name }}
            </div>
            <div class="form-group">
                <label>Roll Number</label>
                {{ form.roll_number }}
            </div>
            <div class="form-group">
                <label>Password</label>
                {{ form.password }}
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</body>
  
</html>


Now visit http://localhost:8000/ and check modified form. 
 

django-forms-render-manualy

These were just some basic modifications using Bootstrap. One can customize it to an advanced level using various CSS tricks and methods. 
 

{{ field }} attributes

 

  • {{ field.label }} 
    The label of the field, e.g. Email address.
  • {{ field.label_tag }} 
    The field’s label wrapped in the appropriate HTML tag. This includes the form’s label_suffix. For example, the default label_suffix is a colon: 
     
<label for="id_email">Email address:</label>
  • {{ field.id_for_label }} 
    The ID that will be used for this field (id_email in the example above). If you are constructing the label manually, you may want to use this in place of label_tag. It’s also useful, for example, if you have some inline JavaScript and want to avoid hardcoding the field’s ID.
  • {{ field.value }} 
    The value of the field. e.g someone@example.com.
  • {{ field.html_name }} 
    The name of the field that will be used in the input element’s name field. This takes the form prefix into account, if it has been set.
  • {{ field.help_text }} 
    Any help text that has been associated with the field.
  • {{ field.errors }} 
    Outputs a <ul class=”errorlist”> containing any validation errors corresponding to this field. You can customize the presentation of the errors with a {% for error in field.errors %} loop. In this case, each object in the loop is a string containing the error message.
  • {{ field.is_hidden }} 
    This attribute is True if the form field is a hidden field and False otherwise. It’s not particularly useful as a template variable, but could be useful in conditional tests such as: 
     
    {% if field.is_hidden %}
       {# Do something special #}
    {% endif %}
  • {{ field.field }} 
    The Field instance from the form class that this BoundField wraps. You can use it to access Field attributes, e.g. {{ char_field.field.max_length }}


Previous Article
Next Article

Similar Reads

{{ form.as_p }} - Render Django Forms as paragraph
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article,
2 min read
{{ form.as_table }} - Render Django Forms as table
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article,
2 min read
{{ form.as_ul }} - Render Django Forms as list
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article,
2 min read
Django Form | Data Types and Fields
When gathering user information to store in a database, we employ Django forms. Django offers a variety of model field forms for different uses, and these fields have a variety of patterns. The fact that Django forms can handle the fundamentals of form construction in just a few lines of code is their most crucial feature. Although the developer ha
6 min read
Django Form | Build in Fields Argument
We utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of code. Although the developer has the option of des
3 min read
Render Model in Django Admin Interface
Rendering model in admin refers to adding the model to the admin interface so that data can be manipulated easily using admin interface. Django's ORM provides a predefined admin interface that can be used to manipulate data by performing operations such as INSERT, SEARCH, SELECT, CREATE, etc. as in a normal database. To start entering data in your
3 min read
Render a HTML Template as Response - Django Views
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This article revolves around how to render an HTML page from Django using views. Django has always been known for its app structure and ability to manage applications easily. Let's dive in to see how to render a template file through
3 min read
Render HTML Forms (GET & POST) in Django
Django is often called "Batteries Included Framework" because it has a default setting for everything and has features that can help anyone develop a website rapidly. Talking about forms, In HTML, a form is a collection of elements inside <form>...</form> that allow a visitor to do things like entering text, select options, manipulate o
5 min read
Intermediate fields in Django | Python
Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship exists between two models A and B, when one instance of A is related to multiple instances of B, and vice versa. For example - In a shop management system, an Item and a Customer share a many-to-many relationship, as one customer can buy multiple items, a
2 min read
Python | Relational fields in Django models
Prerequisite: Django models Django models represent real-world entities, and it is rarely the case that real-world entities are entirely independent of each other. Hence Django supports relational databases and allows us to establish relations between different models. There are three types of relational fields which Django supports: many-to-one, m
4 min read
Django model data types and fields list
The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete. Example: from django.db import models class Musician(models.Model): first_name = models.Char
4 min read
Boolean Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
String Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
Core arguments in serializer fields - Django REST Framework
Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer
6 min read
URL fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
File upload Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
Numeric fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
Date and time fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, date, etc. Then, you would need AutoField, Ch
7 min read
Choice Selection Fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
Serializer Fields - Django REST Framework
Serializer comes with some fields (entries) that process data in and out of the serializer in Django REST Framework. The very motive of Serializing is to convert DB data to a datatype that can be used by javascript. For example, if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need
13 min read
Implement Search Autocomplete For Input Fields in Django
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Today we will create joke app in django. In this article we will lear
2 min read
Django Dynamic Model Fields
In web development, Django is a framework that helps to build awesome websites. One of the main features of Django is dynamic model fields so we will discuss what we mean by dynamic model fields and how to use them in Django. In this article, we will read about the dynamic model fields in Django. What are Django Dynamic Model Fields?Dynamic Model f
5 min read
How to Define Two Fields "Unique" as Couple in Django
In many applications, you might encounter scenarios where you need to ensure that a pair of fields in a database model must be unique together. For example, if you have a Booking model in a restaurant reservation system, you may want to ensure that the combination of table_number and reservation_time is unique, preventing double bookings for the sa
2 min read
Can "list_display" in a Django ModelAdmin Display Attributes of ForeignKey Fields?
Django's admin interface is a powerful tool for managing application data. One of the common requirements while using Django admin is to customize the way data is displayed. The list_display attribute in Django's ModelAdmin is particularly useful for this purpose, allowing developers to specify which fields should be displayed in the list view of t
3 min read
Convert Django Model Object to Dict with all of the Fields Intact
Django, a high-level Python web framework, simplifies the process of building web applications by providing a robust ORM (Object-Relational Mapping) system. Often, while developing web applications, there arises a need to convert Django model instances into dictionaries, retaining all the fields intact. This conversion is useful for various purpose
4 min read
Include Related Model Fields In Django Rest Framework
In Django Rest Framework (DRF), it is common to work with related models, especially when building APIs that expose complex data structures. We might need to include data from related models (like foreign keys and many-to-many relationships) in our serialized API responses. DRF provides powerful mechanisms like SerializerMethodField, depth, and nes
3 min read
How to Filter Empty or NULL Fields in Django QuerySet?
When working with a Django project, we often need to filter records where certain fields are either empty or NULL. This is a common requirement, especially when dealing with user-generated data where fields might be left blank. In Django, we can filter a QuerySet where a specific field has no value or is explicitly set to NULL. In this article, we
3 min read
How to Get a List of the Fields in a Django Model
When working with Django models, it's often necessary to access the fields of a model dynamically. For instance, we might want to loop through the fields or display them in a form without manually specifying each one. Django provides a simple way to get this information using model meta options. Each Django Model has a protected _meta attribute whi
2 min read
How to Add created_at and updated_at Fields to All Django Models Using TimeStampedModel
In Django applications, tracking when records are created and last updated in the database is common. Two of the most frequently used fields for this purpose are created_at and updated_at. Django provides a convenient way to handle this by creating an abstract base class called TimeStampedModel, which can automatically add these fields to any model
4 min read
Using Certbot Manually for SSL certificates
Let's Encrypt has become one of the most important organizations for creating a secure Internet. Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit, a service provided by the Internet Security Research Group (ISRG). They give people the digital certificates they need in order to enable HTTPS (SSL/T
3 min read
Practice Tags :