Django Request Object - Soft Introduction for Beginners
Tags: django, webdev, python, beginners
Published: 2021-06-19 16:02:59

---
title: Django Request Object - Soft Introduction for Beginners
published: true
description: Learn how to read and manage the information provided by a browser request in Django
tags: django, webdev, python, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1thvoomu3c6hx42og41b.png
canonical_url: https://docs.appseed.us/content/tutorials/django-request-object
---
Hello Coders,

This page explains the [request object provided by Django](https://docs.appseed.us/content/tutorials/django-request-object) 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.

> *Thanks for reading!* - Content provided by **[App Generator](https://appseed.us/)**.

--- 

Let's create a Django project and code our first view where the request object is exposed:

> Create and activate a virtual environment

```bash
$ # Linux-based systems
$ virtualenv env
$ source env/bin/activate  
```

For Windows-based systems, the syntax is slightly different:

```bash
$ virtualenv env
$ .\env\Scripts\activate
```

> Install Django - using PIP (the official package manager for Python)

```bash
$ pip install django
```

In case anyone prefers a specific Django version, use this syntax:

```bash
$ pip install "django==2.2.10" # This will install 2.x version
```

---

## 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

```bash
$ mkdir my-django-project
$ cd my-django-project
```

Inside the directory, we will generate the core of our project using **django-admin** tool:

```bash
$ django-admin startproject config .
```

> Set up the database

```bash
$ python manage.py makemigrations # generate SQL
$ python manage.py migrate        # Apply changes on database   
``` 

> Start the app in development mode

```bash
$ python manage.py runserver 
$
$ # Access the web app in browser: http://127.0.0.1:8000/
```

At this point we should see the default Django page in the browser:

![Django Request Object - The default Django page.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/slln3436eil1r1914dlt.png)

---

## 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. 

```bash
$ python manage.py startapp app
``` 

> Update settings to include the new app - `config/settings.py`.

```python
# File: config/settings.py (partial content)
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app'                           # <-- NEW
]
...
```

> Update routing - `config/urls.py`

```python
# File: config/urls.py (partial content)
...
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url   # <-- NEW
from app.views import hello                 # <-- NEW

urlpatterns = [
    path('admin/', admin.site.urls),
    url('', hello),                         # <-- NEW
]
```

> Code out first route and get access to the `request` object

```python
from django.shortcuts import render
from django.http import HttpResponse     # <-- NEW

def hello(request):                      # <-- NEW    
    return HttpResponse("Hello Django")  # <-- NEW   
```

![Django Request Object - Simple Hello World served by the app.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrx3y185i09eqggbpe0i.png)
 
---

## Request Object Properties

The request object in Django comes with a few interesting properties like the IP of the client, the browser (aka user-agent), request path, or the information that help us to detect if the connection is secure (HTTPS-type).

![Django Request Object - Header variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w0n2vi93yo8a3av9m014.png)
 
---

> 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):

```python
from django.shortcuts import render
from django.http import HttpResponse     

def hello(request):

    if request.method == 'GET':    
        return HttpResponse("Received a GET request")
        
    elif request.method == 'POST':    
        return HttpResponse("Received a POST request")
```

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:

```python
def headers(request): 
    values = request.META.items() 
    
    rows = ''
    for key, val in values:
        rows += '<tr><td>%s</td><td>%s</td></tr>' % (key, val)

    return HttpResponse( '<table>' + rows + '</table>' )
``` 

Here is the script output executed using a local development server:

![Django Request Object - Full dump of request variables.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxe32dozj885stmftpe2.png)

---

## 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 contexts. 

> Read GET variables

```python
def parse_get(request):
    
    var1 = request.GET['my_var']       # this might throw KeyError exception
    
    var2 = request.GET.get('var_2')    # Soft read on variable
    
    var3 = request.GET.get('var_3', 1) # Soft Read with Default value     
```

> For POST, the process is identical. 

```python
def parse_post(request):
    
    post_var1 = request.POST['my_var']       # this might throw KeyError exception
    
    post_var2 = request.POST.get('var_2')    # Soft read on variable
    
    post_var3 = request.POST.get('var_3', 9) # Soft Read with Default value     
```

--- 

> Thanks for reading! Feel free to AMA in the comments section. For more resources, please access:

---

- Read more about [Django](https://www.djangoproject.com/) (official docs)
- Start fast a new project using development-ready [Django Starters](https://appseed.us/admin-dashboards/django)