Initial form data – Django Forms
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
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
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”,
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
and in templates/home.html,
Now let’s display the form by running
Python manage.py runserver
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.
Now open http://127.0.0.1:8000/. This method is senior of all and will override any data provided during other methods.
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.
Now visit, http://127.0.0.1:8000/. One can see the data being updated to 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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course