Creating My First Django Application Part 3

Naresh Kumar
5 min readMar 3, 2020

So as of know we have successfully created out fist Django Application in which we have learnt

  1. Organizing Setting.py
  2. Maintaining URL in urls.py
  3. Creating Views using function
  4. Creating Views with template HTML

Request and Response are the main part of a web application. Opening a image, filling up a form, clicking on a button each and every event is outcome of request given to server and response coming from the server.

In following tutorial we will learn how to handle GET and POST request. GET and POST are the only HTTP methods to use when dealing with forms.

Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response.

GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL. The URL contains the address where the data must be sent, as well as the data keys and values. GET and POST are typically used for different purposes.

Any request that could be used to change the state of the system — for example, a request that makes changes in the database — should use POST. GET should be used only for requests that do not affect the state of the system.

Handling GET Request

Create a view

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from pprint import pprint
def index(request):
return HttpResponse('404')
def addition(request,num1,num2):
text = """The method used in the request is <b>%s</b></br>
Path of <b>%s</b> is <b><u>%s</u></b> </br>"""%(str(request.method),str(request.method),str(request.path))

addition = int(num1) + int(num2)
return render(request,'get.html',{"data":text,"num1":num1,"num2":num2,"sum":addition})

The above view will print the values type of request and path of the url and will print the addition of the two integer numbers passed in the url

Create get.html

<HTML>
<HEAD>
<TITLE>This is a Sample Django Application</TITLE>
<style type=”text/css”>
body
{
background-color: #fcfcfc;
}
.center-div
{
position: absolute;
margin: auto;
top: 0;
font-size:20px;
right: 0;
bottom: 0;
left: 0;
width: 400px;
height: 400px;
background-color: #ccc;
border-radius: 3px;
}
</style>
</HEAD>
<BODY BGCOLOR=”FFFFFF”>
<div class=”center-div”>{{data|safe}}
<br> The sum of {{num1}} and {{num2}} is {{sum}}</div>
</BODY>
</HTML>

Here we can see that in {{data|safe}} we are using filter to disable auto-escaping for an individual variable.

By default in Django, every template automatically escapes the output of every variable tag. Specifically, these five characters are escaped:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' (single quote) is converted to &#x27;
  • " (double quote) is converted to &quot;
  • & is converted to &amp
This will be escaped: {{ data }}
This will not be escaped: {{ data|safe }}

Update urls.py

from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path(‘/’,views.index),
path(‘addition/<int:num1>/<int:num2>’,views.addition,name=”addition”),

]

In the urlpatterns, we are using <int:num1> to define the GET parameters.

It means that in url /addition/2/3 2 will be assigned to num1 variable and 3 will be assigned to num2 variable

Notes:

  • To capture a value from the URL, use angle brackets.
  • Captured values can optionally include a converter type. For example, use <int:name> to capture an integer parameter. If a converter isn’t included, any string, excluding a / character, is matched.
  • There’s no need to add a leading slash, because every URL has that. For example, it’s articles, not /articles

The following path converters are available by default:

  • str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn’t included in the expression.
  • int - Matches zero or any positive integer. Returns an int.
  • slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.
  • uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase. For example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns a UUID instance.
  • path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than a segment of a URL path as with str.

Runserver

Open your project and start the server using following command

python manage.py runsever

URL with GET Parameters

Handling POST Request

In POST method, the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response

To demonstrate a POST request handling we will have to perform following steps

2. Open views.py and create a view

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

from myapp.forms import Addition #importing form Addition
def index(request):
return HttpResponse(‘404’)
def total1(request):
if request.method == "POST":
num1 = int(request.POST['num1'])
num2 = int(request.POST['num2'])
total = num1 + num2
return render(request,'post_data.html',{"sum":total,"num1":num1,"num2":num2})
else:
return render(request,'add_data.html')

3. Create a html page -> add_data.html to show the html form

<html>
<body>

<form name = "form" action = "{% url 'total' %}"
method = "POST" >{% csrf_token %}

<div style = "max-width:470px;">
<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "" name = "num1" />
</center>
</div>

<br>

<div style = "max-width:470px;">
<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "" name = "num2" />
</center>
</div>

<br>

<div style = "max-width:470px;">
<center>

<button style = "border:0px; background-color:#4285F4; margin-top:8%;
height:35px; width:80%;margin-left:19%;" type = "submit"
value = "Login" >
<strong>Login</strong>
</button>

</center>
</div>

</form>

</body>
</html>

In the action it is using the reverse naming. The post data will be sent to the path

4. Create a html -> post_data.html to print the post value

<HTML><HEAD>
<TITLE>This is a Sample Django Application</TITLE>
<style type=”text/css”>
body
{
background-color: #fcfcfc;
}
.center-div
{
position: absolute;
margin: auto;
top: 0;
font-size:20px;
right: 0;
bottom: 0;
left: 0;
width: 400px;
height: 400px;
background-color: #ccc;
border-radius: 3px;
}
</style>
</HEAD>
<BODY BGCOLOR=”FFFFFF”>
<div class=”center-div”><br> The sum of {{num1}} and {{num2}} is {{sum}}</div>
</BODY>
</HTML>

5.Open urls.py to map the URL

from django.contrib import admin
from django.urls import path
from myapp import views
from django.views.generic import TemplateView
urlpatterns = [
path(‘/’,views.index),
path('total/',views.total1,name='total'), #when post request is received total view will handle it]

6. Run the server

Form Template
Output of Post Request

References

  1. https://docs.djangoproject.com
  2. https://docs.djangoproject.com/en/3.0/topics/http/urls/
  3. https://tutorialspoint.com/
  4. Django Unleashed — Book by Andrew Pinkham

--

--

Naresh Kumar

Security Analyst making safe cyberspace 4 people #cyber4people India