Django get all data from POST request

In this Python Django tutorial, I will explain how to get data from a POST request in Python Django in various ways. I will demonstrate this with the help of some examples.

  • How to get POST request data in Django
  • Django pass POST data to view
  • Django post request example
  • Django get post data list
  • Django get POST data as dict
  • Django POST data to database

How to get POST request data in Django

When a POST request is received at the Django server, the data in the request can be retrieved using the HTTPRequest.POST dictionary. All the data of the POST request body is stored in this dictionary.

For example, you can use the following code snippet inside your view.py file.

def index(request):
   if request.method == 'POST'
      var = request.POST[<parameter name>]

Assuming that the above index function handles the POST request, a parameter value is being stored in the variable named var.

After that, you can use this value in any code or template or store it in the database.

Read Get URL parameters in Django

Django pass POST data to view

When you create an HTML form, you specify the method type to POST when you need to send a POST request.

The input fields defined inside the form pass the data to the redirected URL. You can define this URL in the urls.py file. In this URLs file, you can define the function created inside the view and access the POST data as explained in the above method.

You just have to use the HTTPRequest.POST object to fetch POST data. Let us understand this with the help of an example.

Read Convert HTML page to PDF using Django in Python

Django post request example

I have created a Django template named index.html containing two input fields. I will enter data into these input fields and render it inside another Django template. The source code of the Django template named index.html is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
</head>
<body>
    <form action="validate" method="post">
        {% csrf_token %}
        Username : <input type="text" name="user" ><br><br>
        Password : <input type="text" name = "pass"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

As you can see in the above code, the form is redirecting to a URL endpoint named validate. We have to define this URL endpoint inside the urls.py file. In my case, the urls.py file is:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name = 'index'),
    path('validate', views.validate, name = 'validate')
]

Using the path defined above, a function named validate inside the views.py file will get executed when a request is made to the specified URL endpoint. Let us have a look at the views.py file:

# importing the necessary libraries
from django.http import HttpResponse
from django.shortcuts import render


def index(request):
      return render(request, 'index.html')
def validate(request):
   if request.method == 'POST':
      username= request.POST["user"]
      password = request.POST["pass"]
      dict = {
         'username': username,
         'password': password
      }
      return render(request, 'validate.html', dict)   

In the validate function, firstly we are validating if the request method is POST. Then we are fetching the POST request values. After that, we are rendering these values inside another Django template named validate.html.

In the validate.html file, we will access these values and render these as:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
</head>
<body>
  <p>Username is :{{username}}</p>
  <p>Password is: {{password}}</p>
</body>
</html>

Now let us open our first web page i.e. index.html and put some values inside the text boxes.

Django get all data from POST request
Submitting the values and sending a POST request

Clicking on Submit will redirect us to the validate.html page where we can see our rendered values.

How to get POST request data in Django
Rendering the POST request parameters in another template

Thus, you might have understood how you can pass and retrieve the POST request parameters in Django.

Read How to get data from get request in Django

Django get post data list

Sometimes, you may want to pass parameters as a list from an HTML form to your server. For example, you may want to pass a group of values through checkboxes from an HTML page.

In that case, you must specify the same name for all the checkboxes and retrieve the list of these controls using the HTTPRequest.POST.getlist() function. For example, look at the HTML page below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
</head>
<body>
    <form action="validate" method="post">
        {% csrf_token %}
        <input type="checkbox" id="hobby1" name="hobby" value="swimming">
        <label for="hobby1"> I like swimming</label><br>
        <input type="checkbox" id="hobby2" name="hobby" value="running">
        <label for="vehicle2"> I like running</label><br>
        <input type="checkbox" id="hobby3" name="hobby" value="Cycling">
        <label for="vehicle3"> I like Cycling</label><br>
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>

The above HTML page submits a list of hobbies to a Django server through a form using a POST request.

When a user clicks on the Submit button, a request is made to the ‘/validate‘ endpoint. Now we have to map this endpoint with a function in our urls.py file as:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name = 'index'),
    path('validate', views.validate, name = 'validate')

In the views.py file, we will use the HTTPRequest.POST.getlist() function to retrieve the list of values from the POST request.

Remember to specify the name of the HTML control inside this function as a list. For example, I have used the name hobby in my HTML page for all the checkboxes. While retrieving the list of values, I will specify the name as hobby[] inside the getlist() function as shown below:

# importing the necessary libraries
from django.http import HttpResponse
from django.shortcuts import render


def index(request):
      return render(request, 'index.html')
def validate(request):
   if request.method == 'POST':
         hobbies = request.POST.getlist('hobby[]')
   return render(request, 'validate.html', {'hobbies':hobbies})   

I have rendered the list of values using a loop in a Django template named validate.html that looks like:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
</head>
<body>
  <ol><p style="font-size: x-large;">Your hobbies are:<p>
    {%for hobby in hobbies %}
      <li style="font-size: large;">{{hobby}}</li>
    {% endfor %}
  </ol>
</body>
</html>

Now let us see the output. Let us start our server:

Django get post data list
Submitting values as a list

Clicking on submit will redirect us to the next page.

Django post request example
Retrieved the parameters as a list

You can see the list of values is rendered in the output.

In this way, you can pass a list of values from an HTML page and retrieve it in a Django application.

Read Python Django length filter

Django get POST data as dict

When you submit data or parameters through a POST request to a Django application, these parameters are stored in the form of a dictionary-like object of the class QueryDict.

This object is a dictionary-like object i.e. you can use almost all the functions of a dictionary object. For more information on the QueryDict class, you can read the official Django documentation.

Let me show you an example, where I will demonstrate how this object is a dictionary-like object. I have created a sample registration page whose source code is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Page</title>
</head>
<body>
    <form action="registered" method="post">
        {% csrf_token %}
        First Name  <input type="text" name ="fn" placeholder="Enter Your First Name" ><br><br>
        Last Name   <input type="text" name ="ln" placeholder="Enter Your Last Name" ><br><br>
        Email       <input type="email" name ="email"placeholder="Enter Your Email address" ><br><br>
        Password    <input type="password" name ="password" placeholder="Enter Your Password" ><br><br>
                    <input type="submit" value="Submit">
    </form>
</body>
</html>

Clicking on the submit button will redirect the user to the endpoint named “registered”. I have mapped this endpoint with a function in my urls.py file as:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name = 'index'),
    path('registered', views.registered, name= 'registered')
]

Now let us view the function that will be executed inside the views.py file:

# importing the necessary libraries
from django.shortcuts import render

def index(request):
      return render(request, 'index.html')
def registered(request):
      data = request.POST.items()
      return render(request, 'registered.html', {'data':data})

Here you can see that I am retrieving the parameters and rendering them in another Django template. We will retrieve the QueryDict object in the template using a for loop:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
</head>
<body>
    {% for keys, values in data %}
    <li>{{keys}} : {{values}}</li>
    {% endfor %}
</body>
</html>

Now let us see the output. Let us start our server and visit the root directory.

Django get POST data as dict
Passing the POST parameters

Let us click on the Submit button now and see the result.

django get all post data
Rendering the parameter values

Here you can see that all the parameter values are rendered including the CSRF token that we sent from the registration form.

Read Python Django group by

Django POST data to database

In this section, you will learn how you can store the data from a POST request into a database. For this tutorial, I will be using the SQLite database i.e. the default database offered by Django.

To interact with databases in Django, you have to create models. To know more about models and how to create them you can read our article on How to Create Model in Django.

  • Firstly, we will create an HTML form, from where we will send our POST data to the Django application, say the file name index.html. We will store this file in templates folder of our Django project.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Page</title>
</head>
<body>
    <form action="registered" method="post">
        {% csrf_token %}
        First Name  <input type="text" name ="fn" placeholder="Enter Your First Name" ><br><br>
        Last Name   <input type="text" name ="ln" placeholder="Enter Your Last Name" ><br><br>
        Email       <input type="email" name ="email"placeholder="Enter Your Email address" ><br><br>
        Password    <input type="password" name ="password" placeholder="Enter Your Password" ><br><br>
                    <input type="submit" value="Submit">
    </form>
</body>
</html>
  • The action attribute of the form will redirect us to a URL enpoint named registered in our Django application. We need to create a mapping for this endoint in our urls.py file as:
from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name = 'index'),
    path('registered', views.registered, name= 'registered')
]
  • We have mapped this URL endpoint with a function named registered() in our views.py file. In this function, we will write our logic to store the POST request data in the database.
  • But before that we need to create a model in our application. To create a model, open the model.py file of your Django application. In my example, the models.py file will look like:
from django.db import models

class Registration(models.Model):
    first_name = models.CharField(max_length= 20)
    last_name = models.CharField(max_length= 20)
    email = models.EmailField(max_length= 40)
    password = models.CharField(max_length= 50)

You can see that we have created a model class with some fields. This model class will create a table in the database named app1_registration, where app1 is my Django application name and registration is the name of the model class.

The structure of the table will be equivalent to:

CREATE TABLE app1_registration (
    id         INTEGER      NOT NULL
                            PRIMARY KEY AUTOINCREMENT,
    first_name VARCHAR (20) NOT NULL,
    last_name  VARCHAR (20) NOT NULL,
    email      VARCHAR (40) NOT NULL,
    password   VARCHAR (50) NOT NULL
);

To finally create the table, you need to run two commands.

python manage.py makemigrations

To define the changes in the database.

python manage.py migrate

To commit the changes in the database.

Once you have migrated the changes in your database, you need to create a logic for entering the data into this database. This will be done in the views.py file.

# importing the necessary libraries
from django.shortcuts import render
from app1.models import Registration
def index(request):
      return render(request, 'index.html')
def registered(request):
      first_name = request.POST['fn']
      last_name = request.POST['ln']
      email = request.POST['email']
      password = request.POST['password']
      
      person = Registration(first_name=first_name, last_name= last_name, email= email, password = password)
      person.save()   
      return render(request, 'registered.html', {'fn':first_name})
  • In the views file, firstly I will retrieve the data from the POST request.
  • Then I will create an object of our model class and specify the values that will be stored in the database.
  • The save() function will save the data in the database permanently.
  • After that the user will be redirected to another Django template namd registered.html, where a welcome message will be displayed.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
</head>
<body>
  <h1>Welcome {{fn}}. You have successfully registered your account</h1>
</body>
</html>

Now let us test our Django application. Run the Django server and open the root URL.

Django POST data to database
Submitting the form values

We will enter some data in the form input fields and click on Submit.

get data from post request django
The Welcome Page

You can see that we are successfully redirected to the welcome page. Now let us see if these values are stored in the database or not.

I will open my SQLite database file using SQLite Studio.

django get form data from post
Form data successfully stored in the database

You can see that the form data is stored in the database successfully.

Related Python Django tutorials:

In this way, you can store the data of a POST request in a database in a Django application.

  • How to get POST request data in Django
  • Django pass POST data to view
  • Django post request example
  • Django get post data list
  • Django get POST data as dict
  • Django POST data to database