Django Request Object
Learn how to read and manage the information provided by an HTTP request in Django
This page explains the request object provided by Django as the default argument in views. For those unfamiliar with Django, this web framework is written in Python by experienced developers using a batteries-included concept. For more information regarding this amazing web framework please access:
Let's create a Django project and code our first view where the request object is exposed:
Create and activate a virtual environment
1
$ # Linux-based systems
2
$ virtualenv env
3
$ source env/bin/activate
Copied!
For Windows-based systems, the syntax is slightly different:
1
$ virtualenv env
2
$ .\env\Scripts\activate
Copied!
Install Django - using PIP
1
$ pip install django
Copied!
The above command will install the latest stable version of Django.

Build a Django Project

A new project can be generated with ease in Django by using django-admin that provides a collection of settings for the database, Django, and security layer.
Create the project folder
1
$ mkdir my-django-project
2
$ cd my-django-project
Copied!
Inside the directory, we will generate the core of our project using django-admin tool :
1
$ django-admin startproject config .
Copied!
Note: Take into account that . at the end of the command.
Create the database and the app tables
1
$ python manage.py makemigrations # generate SQL
2
$ python manage.py migrate # Apply changes on database
Copied!
Start the application
1
$ python manage.py runserver
2
$
3
$ # Access the web app in browser: http://127.0.0.1:8000/
Copied!
At this point we should see the default Django page in the browser:
Django - Default Project Page.
​

Create New Application

In the previous section, we've generated the core of the project that handles the configuration and now we will create the first Django application to serve a simple page to the users.
1
$ python manage.py startapp app
Copied!
Update settings to include the new app - config/settings.py
1
# File: config/settings.py (partial content)
2
...
3
INSTALLED_APPS = [
4
'django.contrib.admin',
5
'django.contrib.auth',
6
'django.contrib.contenttypes',
7
'django.contrib.sessions',
8
'django.contrib.messages',
9
'django.contrib.staticfiles',
10
'app' # <-- NEW
11
]
12
...
Copied!
Update routing - config/urls.py
1
# File: config/urls.py (partial content)
2
...
3
from django.contrib import admin
4
from django.urls import path
5
from django.conf.urls import include, url # <-- NEW
6
from app.views import hello # <-- NEW
7
​
8
urlpatterns = [
9
path('admin/', admin.site.urls),
10
url('', hello), # <-- NEW
11
]
Copied!
Code out first route and get access to the request object
1
from django.shortcuts import render
2
from django.http import HttpResponse # <-- NEW
3
​
4
def hello(request): # <-- NEW
5
return HttpResponse("Hello Django") # <-- NEW
Copied!
​

Request Object Properties

The request object in Django comes with a few interesting properties:
Item / Helper
Sample Value
Short Information
REMOTE_ADDR
12.245.68.71
IP of the client
HTTP_USER_AGENT
Mozilla/5.0
User Browser Information
request.path
/admin/
The URL without domain
request.is_secure()
True / False
True if the request was made over HTTPS
request.method
POST / GET
The Request Method
How to check the request type in view.
A widely user code chunk is when we test the type of the request and manage the submitted data on POST (when we send information to the server, login action for instance):
1
from django.shortcuts import render
2
from django.http import HttpResponse
3
​
4
def hello(request):
5
​
6
if request.method == 'GET':
7
return HttpResponse("Received a GET request")
8
9
elif request.method == 'POST':
10
return HttpResponse("Received a POST request")
Copied!
For newcomers, GET is used to pull information from the server without altering anything. Search is a good example of a GET request when we try to locate information on Google or Wikipedia.
POST is used to update the information on the server like change the title for a book or register a new item in our service.
Another difference between GET and POST is the location of the submitted information.
    GET submits data in URL: http://myservice.com?search=all_books
    POST submits data in the request body (not visible in the URL)
List all request headers
This subsection contains a code sample that prints all headers and request objects provided by Django:
1
def headers(request):
2
values = request.META.items()
3
4
rows = ''
5
for key, val in values:
6
rows += '<tr><td>%s</td><td>%s</td></tr>' % (key, val)
7
​
8
return HttpResponse( '<table>' + rows + '</table>' )
Copied!
Here is the script output executed using a local development server:
Django Request Object - Provided Information.

Read Request Variables

Django provides dictionaries for GET and POST requests populated with all variables sent by the client. We can access the variables by key or using get() helper for both cases.
Read GET variables
1
def parse_get(request):
2
3
var1 = request.GET['my_var'] # this might throw KeyError exception
4
5
var2 = request.GET.get('var_2') # Soft read on variable
6
7
var3 = request.GET.get('var_3', 1) # Soft Read with Default value
Copied!
For POST, the process is identical.
1
def parse_post(request):
2
3
post_var1 = request.POST['my_var'] # this might throw KeyError exception
4
5
post_var2 = request.POST.get('var_2') # Soft read on variable
6
7
post_var3 = request.POST.get('var_3', 9) # Soft Read with Default value
Copied!
​
Thanks for reading! For more topics, feel free to contact Appseed.
​

Resources

Last modified 3mo ago