Render Django Form Fields Manually

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 manunally.

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,



filter_none

edit
close

play_arrow

link
brightness_4
code

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())

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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,

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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
  • {{ 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 }}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.