Django Web Framework[Part-7]

Debapriya Basu
8 min readSep 3, 2023

--

URL : Uniform Resource Locator

URL consists of several parts. Let’s get learning 🍀.

Here is an example.

Parts of URL

Scheme

It is responsible for transmission and exchange of data. http sends data as plain text and https encrypts the data.

Subdomain

It contains the home page and other important pages. WWW stands for World Wide Web.

Domain

Domain has two parts 1) Second level domain 2) Top level domain.
1) SLD(Second level domain) refers to organisation. For example: Little lemon is name for the organisation.

2) Top level domain usually has Country, Category etc. “.com” indicates a commercial entity, “.org” refers an organisation, “.ie” refers Ireland(country specific).

File Path

Location of the resources which are transmitted over http such as web documents, image files, metadata etc. It can be local and web-based(hosted externally). Local is mainly stored in user’s device or server. Web-based means location in external server.

URL Parameters

For example, the web based URL for the 4.1 release for Django has its own URL with a specific file path which includes the year, month and day it was published.

URL parameters are also known as query strings and are used to structure additional information inside a URl. You use URL parameters to capture any part of the URL and pass its value for processing A query string is similar.

It begins with a question mark symbol and is placed after the URL Path. It contains parameters represented as key value pairs that can appear inside a URL path. You can add more than one by adding the ampersand symbol between parameters.

Django can process both types of URL but mainly uses the URL parameters.

Parameters

The view function in Django is like any other Python function in that it receives its mandatory argument as the request object from the server context. The client may pass additional arguments via different methods.

Path parameter

The client browser sends data along with the URL itself. For example, a URL such as http://example.com/customer/5. Here, the URL endpoint id, /customer/5, is the variable parameter (this can be any other number).

The parameter linked to the URL’s endpoint is called a path parameter. Note that there may be multiple path parameters in the URL, separated by / symbol.

For now, consider that the browser will use the URL http://localhost:8000/getuser/John/1

The URL dispatcher should identify John as the name parameter and 1 as the id parameter.

This pattern is mapped to the pathview() function with the following path in the URL patterns list in the app’s url.py file.

from django.contrib import admin
from django.urls import path, include
from littleLemon import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('littleLemon.urls')),
path('say_hello/', views.say_hello),
path('dispaly_date/', views.dispaly_date),
path('menu/', views.menu),
path('getuser/<name>/<id>', views.pathview, name='pathview'), ---Add this
in you existing urls.py of APP

Add below in views.py of APP

#Path parameter in URL
def pathview(request, name, id):
return HttpResponse("Name : {} UserID : {}".format(name, id))
Output after adding param in view

Path converters

The URL pattern treats the identifiers in angular brackets (<..>) as the path parameters. By default, it parses the received value to the string type. Other path converters available are:

  • str — Matches any non-empty string and excludes the path separator, ‘/’. This is the default if a converter isn’t included in the expression.
  • int — Matches zero or any positive integer and returns an int. For example:/customer/<int:id>
  • slug — Matches any slug string consisting of ASCII letters or numbers, including the hyphen and underscore characters.
  • uuid — Matches a formatted UUID. For example: 075194d3–6885–417e-a8a8–6c931e272f00 and returns a UUID instance.
  • path — Matches any non-empty string and includes the path separator, ‘/’.

Query parameter

A query string is a sequence of one or more key=value pairs concatenated by the & symbol. Each key is the query parameter. The query string ends with the ? symbol after the URL endpoint.

Query strings are an alternative approach to URL parameters for adding URL configurations.

The URL dispatcher doesn’t parse these parameters. They are fetched by the view from the request object it receives. The request object’s GET property is a dictionary object.

The key-value pairs in the query string are added to the request.GET property. Hence, the name can be obtained with request.GET[‘name’] expression.

The next step is to add the following path in the urls.py file:

from django.contrib import admin
from django.urls import path, include
from littleLemon import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('littleLemon.urls')),
path('say_hello/', views.say_hello),
path('dispaly_date/', views.dispaly_date),
path('menu/', views.menu),
path('getuser/<name>/<id>', views.pathview, name='pathview'),
path('getuser/', views.queryview, name='queryview'),
]
#Query parameter in URL
def queryview(request):
queryName = request.GET['name']
queryID = request.GET['id']
return HttpResponse("Name : {} UserID : {}".format(queryName, queryID))
Query parameter output on localhost

Body parameters

An HTML form sends the data to the URL mentioned in its action attribute using the POST method. The POST method is a more secure way of sending data than the GET method because the data is not revealed in the URL.

Let’s construct a simple form containing two text input elements. Then, save it as form.html in the templates folder.

<form action = "/app/getform/" method = "POST">
{% csrf_token %}
<p> Name : <input type="text" name="name"> </p>
<p> ID : <input type="text" name="id"> </p>
<input type="submit">
</form>

The {% csrf_token %} tag is necessary to prevent cross-site forgery attacks. We’ll learn more about this later on in the course.

Add in views.py of App
Add url in urls.py of App

Run local host with showform parameter

Submit above form
Output after submission

In the real world, the received data may be meaningfully processed, such as storing it in a database table.

We’ll learn how to do this when you explore Models, Forms and Database Connections.

Regular expressions to create Urls

    path('menu_item/10', views.dispaly_menu_item),
#URL pattern is fixed we can't serarch for item 1 or anything else
re_path(r'^menu_item/([0-9]{2})/$', views.dispaly_menu_item),
#to make the URL dynamic
]

URL Namespacing and Views

reverse() function

However, the hard-coded URLs make the application less scalable and difficult to maintain as the project grows. In such a case, you can obtain the URL from the name parameter used in the path() function.

python manage.py shell 

Django’s reverse() function returns the URL path to which it is mapped.

>>> from django.urls import reverse 
>>> reverse('index')
'/demo/'

The problem comes when the view function of the same name is defined in more than one app. This is where the idea of a namespace is needed.

Application namespace

The application namespace is created by defining app_name variable in the application’s urls.py and assigning it the name of the app. In the demoapp/urls.py script, make the change using the following code:

#demoapp/urls.py
from django.urls import path
from . import views
app_name='demoapp'
urlpatterns = [
path('', views.index, name='index'),
]

The app_name defines the application namespace so that the views in this app are identified by it.

To obtain the URL path of the index() function, call the reverse() function by prepending the namespace to it.

>>> reverse('demoapp:index') 
'/demo/'

To appreciate the advantage of defining a namespace, add another app in the project, for example, newapp. Provide an index() view function in it and define app_name in its URLConf file (that is urls.py).

#newapp/urls.py 
from django.urls import path
from . import views
app_name='newapp'
urlpatterns = [
path('', views.index, name='index'),
]

Update the project’s urls.py.

from django.contrib import admin 
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('demo/', include('demoapp.urls')),
path('newdemo/', include('newapp.urls')),
]
>>> reverse('newapp:index') 
'/newdemo/'

Instance namespace

You can also use the namespace parameter in the include() function while adding an app’s urlpattern to that of a project.

#in demoproject/urls.py 
urlpatterns=[
# ...
path('demo/', include('demoapp.urls', namespace='demoapp')),
# ...
]

Using namespace in view

Suppose you want the user to be conditionally redirected to the login view from inside another view. You need to obtain the URL of the login view and send the control to it with HttpResponsePermanentRedirect.

from django.http import HttpResponsePermanentRedirect 
from django.urls import reverse

def myview(request):
....
return HttpResponsePermanentRedirect(reverse('demoapp:login'))

namespace in the url tag

An HTML form is submitted to the URL specified in the action attribute.

<form action="/demoapp/login" method="post"> 

#form attributes

<input type='submit'>

</form>

The form will then be processed by the view mapped to this URL. However, as mentioned above, a hard-coded URL is not desired. Instead, use the url tag of the Django Template Language. It returns the absolute path from the named URL.

Use the url tag to obtain the URL path dynamically, as shown below:

<form action="{% url 'login' %}" method="post"> 
#form attributes
<input type='submit'>
</form>

Again, the login view may be present in multiple apps. Use the named URL qualified with the namespace to resolve the conflict.

<form action="{% url 'demoapp:login' %}" method="post"> 
#form attributes
<input type='submit'>
</form>

Thus, the concept of namespace helps in resolving the conflict arising out of multiple apps under the same project having views of the same name.

Link to my Repo

🎯 https://github.com/Debapriya-dev/BackendDevelopment

Additional resources

Creating views– official documentation

Class-based views — Official

The render() function in Django

Getting query parameters from a request in Django

The HTTP server responses

What’s Next

Previous topics ⭐️👇

🎯DJango Web Framework[Part-1]

🎯DJango Web Framework[Part-2]

🎯Django Web Framework[Part-3]

🎯Django Web Framework[Part-4]

🎯Django Web Framework[Part-5]

🎯Django Web Framework[Part-6]

Next topics ⭐️👇

🎯Django Web Framework[Part-8][Upcoming..]

I will sum up few more topics which I found interesting to look at. Let’s get learning🍀!

🙏 Thank you for reading to the end! Comment below or email me at dbpr.sinha@gmail.com if you have any questions. For more articles please stay tuned. Also follow my links.

--

--

Debapriya Basu

Engineer @ IKEA group with product mindset and ready to take any challenges.