The Wayback Machine - https://web.archive.org/web/20240717024321/https://www.geeksforgeeks.org/initial-form-data-django-forms/
Open In App

Initial form data – Django Forms

Last Updated : 29 Dec, 2019
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

After creating a Django Form, if one requires some or all fields of the form be filled with some initial data, one can use functionality of Django forms to do so. It is not the same as a placeholder, but this data will be passed into the view when submitted. There are multiple methods to do this, most common being to pass the data dictionary when we initialize the form in Django view. Other methods include passing initial values through form fields or overriding the __init__ method.

How to pass initial data to a Django form ?

Illustration of passing initial data 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.

Now let’s create a demo form in “geeks/forms.py”,




from django import forms
  
// creating a django form
class GeeksForm(forms.Form):
    title = forms.CharField()
    description = forms.CharField()
    available = forms.BooleanField()
    email = forms.EmailField()


Now to render this form we need to create the view and template which will be used to display the form to user. In geeks/views.py, create a view




from django.shortcuts import render
from .forms import GeeksForm
  
# creating a home view
def home_view(request):
    context = {}
    form = GeeksForm(request.POST or None)
    context['form'] = form
    return render(request, "home.html", context)


and in templates/home.html,




<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">
</form>


Now let’s display the form by running

Python manage.py runserver

visit http://127.0.0.1:8000/
initial-form-data-django-forms

Method 1 – Adding initial form data in views.py

This first and most commonly used method to add initial data through a dictionary is in view.py during the initialization of a form. Here is the code of views.py with some added data.




from django.shortcuts import render
from .forms import GeeksForm
  
def home_view(request):
    context ={}
  
    # dictionary for initial data with 
    # field names as keys
    initial_dict = {
        "title" : "My New Title",
        "description" : " A New Description",
        "available":True,
        "email":"abc@gmail.com"
    }
  
    # add the dictionary during initialization
    form = GeeksForm(request.POST or None, initial = initial_dict)
  
    context['form']= form
    return render(request, "home.html", context)


Now open http://127.0.0.1:8000/. This method is senior of all and will override any data provided during other methods.
initial-data-django-forms

Method 2 – Adding initial form data using fields in forms.py

One can add initial data using fields in forms.py. An attribute initial is there for this purpose.
In forms.py,




from django import forms
  
class GeeksForm(forms.Form):
    # adding initial data using initial attribute
    title = forms.CharField(initial = "Method 2 ")
    description = forms.CharField(initial = "Method 2 description")
    available = forms.BooleanField(initial = True)
    email = forms.EmailField(initial = "abc@gmail.com")


Now visit, http://127.0.0.1:8000/. One can see the data being updated to method 2.

django-forms-initial-data-method-2

This way one can add initial data to a form in order to ease the work by a user or any related purpose. This data will be passed to models or views as defined by user and would act as normal data entered by user in the form.



Previous Article
Next Article

Similar Reads

Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
initial – Django Form Field Validation
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. initial is used to change the value of the field in the input tag when rendering this Field in an unbound
4 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
How to create a form using Django Forms ?
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. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in
3 min read
{{ 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
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 &lt;form&gt;...&lt;/form&gt; that allow a visitor to do things like entering text, select options, manipulate o
5 min read
CharField - Django Forms
CharField in Django Forms is a string field, for small- to large-sized strings. It is used for taking text inputs from the user. The default widget for this input is TextInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. CharField has following optional arguments: max
5 min read
BooleanField - Django Forms
BooleanField in Django Forms is a checkbox field which stores either True or False. It is used for taking boolean inputs from the user. The default widget for this input is CheckboxInput. It normalizes to: A Python True or False value. Syntax field_name = forms.BooleanField(**options) Django form BooleanField Explanation Illustration of BooleanFiel
5 min read
Practice Tags :
three90RightbarBannerImg