Initial Form Data

Let’s learn how to put initial form data into a form.

Setting up initial form data

Every once in a while, we might want to initialize our form with some data, that is, data that is already filled in. Doing so is not the same as a placeholder. Rather, we would use actual data that is present on default. Therefore, if the users don’t change the values, the data would be sent to the server-side as-it-is.

In this lesson, we will discuss two different methods to place some initial data in a form.

First method

In this first method, we can actually provide initial data in the views.py file, and it will come in as a dictionary. First, we make the following dictionary:

inital_dict={
        "text": "Some initial data",
        "integer": 123,
    }

In the snippet given above, initial_dict is the name of the dictionary, and text and integer are the names of our form_fields.

Now we just need to pass this dictionary in our form:

form = TestForm( request.POST or None,initial=inital_dict)

In the example above, initial is the keyword used to put the initial data into a form.

Get hands-on with 1200+ tech skills courses.