In Django, you can also pass parameters as part of the URL. In this Django tutorial, you will learn how to get URL parameters in Django.
In various web applications, you might have seen some URLs that end with some parameters. For example, look at the below URL:
https://www.shop.tsinfo.com/products/12
The above URL fetches the products page corresponding to a product id i.e. 12. This means 12 is a URL parameter and the result is shown according to this value.
Now let us learn how we can implement this in Django.
- How to get parameter from URL in Django
- Django URL pass parameter to view
- Django URL parameters in template
- Get parameters from URL in Django example
- Path converters Django
- Django URL parameters string
- Django URL slug parameter
How to get parameter from URL in Django
To get a parameter from the URL, you have to perform the steps explained below:
- Create and map a path to a view in the application’s URLs file and pass the parameters to the view
- Define a function in the view that will take the parameter and pass the parameters to Django template.
- Design the Django template to show the results corresponding the passed parameters.
Let us discuss these steps briefly in the upcoming sections.
Django URL pass parameter to view
You can pass a URL parameter from the URL to a view using a path converter.
But, firstly you have to create a path and map it to a view. For this, you have to edit your application’s urls.py file. A sample urls.py file will look like this:
from django.urls import path
from . import views
urlpatterns = [
path("URL endpoint">/<path converter: URL parmeter name>, view_name.function_name, name = "path name")
]
For example, if the requested URL is:
https://www.shop.tsinfo.com/products/12
- Then “products” will be the URL endpoint.
- A path converter defines which type of data will a parameter store. You can compare path converters with data types. In the above example, the path converter will be int.
- You will learn more about various path converters in the upcoming sections.
- URL parameter name will be the name that you will use to refer to the parameter.
- The view_name will be the view that will handle the request and the function_name is the function that will be executed when the request is made to the specified URL endpoint.
- The name will be the name of the path that you are going to create.
The next step is to pass the parameters in a Django template.
Also, check: How to setup Django project
Django URL parameters in template
Firstly, you have to create a Django template where you will render your results. To pass a URL parameter to a Django template, you have to edit the views.py file in Django. A sample view.py file looks like this:
from django.shortcuts import render
def function_name(request, url_parameter):
return render(request, 'Django Template', {url_parameter})
This is the function that will be executed when the specified URL endpoint is hit. This function is taking the URL parameter and passes it to a Django template as a dictionary.
In the Django template, you can receive the parameter and display the results accordingly. For example, you can see in the below sample Django template how to fetch the parameter.
<!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>Products</title>
</head>
<body>
<h2>Your parameter value is : {{URL parameter}}</h2>
</body>
</html>
In this way, you can fetch parameters from a URL and pass it to a Django template.
As you have seen the steps to get URL parameters in Django, now is the time to see an example. You will get a clearer image of the process by understanding it with an example.
Read: Python Django vs Flask
Get parameters from URL in Django example
In this section, I will be using my localhost address for the demonstration purpose. You can change it with your website’s base URL.
For example, if the URL is:
http://localhost:8000/products/125
Then products will be the URL endpoint and 125 will be the URL parameter.
First of all, I have to edit my URLs file as shown below:
from django.urls import path
from . import views
urlpatterns = [
path('',views.index),
path('products/<int:id>', views.viewpara, name = 'view_products')
]
I have created a path to the products endpoint. I have defined the path converter as int to specify that the URL parameter will be an integer.
Do not get confused with the path named index. It is just a path pointing to my base URL.
The views.viewpara is the function defined in the views.py file that will be executed when the request is made. The views.py file will be:
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def viewpara(request, para):
return render(request, 'result.html', {'para' : para})
The above function will receive the parameter from the request. I have passed this parameter to a Django template named result.html as a dictionary object.
The Django template looks like this:
<!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>Products</title>
</head>
<body>
<h2>Your parameter value is : {{id}}</h2>
</body>
</html>
This Django template will be rendered when the request is made. Now let us have a look at the output:
You can see that the parameter value passed to the URL is shown in the Django template. If I change the value of the parameter, the result will also change:
Thus, you might have got a basic understanding of passing the parameters in a URL in Django. I will explain more examples in the upcoming sections. But before that let us learn about the path converters in Django.
Read: Python Django get admin password
Path converters Django
Path converters in Django specify what type of data you are trying to send as parameters through URL. In the above example, I used the int path converter to pass integer values as the URL parameter.
However, you can also use other in-built path converters. Below are some in-built path converters that you can use while defining the URL parameters:
int: Can be used to provide positive integer values including 0 as the URL parameter. For example, passing a product id.
str: The str path converter can be used to define string parameters excluding the “/” symbol and verifies if the string is non-empty. For example, passing a username or token.
slug: It consists of a slug string containing ASCII values including the hyphen and the underscore operator. You might have seen a slug parameter in blogs or articles websites.
For example, the URL https://pythonguides.com/python-django-get/ will redirect to a specific article with the help of the slug parameter. In this URL, python-django-get is the slug parameter.
uuid: A formatted UUID. You can use this path converter if you want to pass a UUID as the parameter. An example of a UUID is: 123e4567-e89b-12d3-a456-426614174023.
path: This path converter consists of a non-empty string, including the “/” symbol, and is defined to pass a path as the parameter.
The difference between the str and the path is that if you pass a path parameter to an str converter, it will be terminated at the “/” symbol and you will not be able to send the full path.
On the other hand, in the case of the path, the “/” symbol is included and the whole path value is passed successfully.
These were some of the in-built path converters in Django. You can also define your custom path converters. For more information on custom path converters, you can read the official Django documentation.
Django URL parameters string
Now let us see an example of a URL that takes a string as the URL parameter.
I will use the below URL endpoint to define the URL parameter:
http://localhost:8000/showmessage/<message>
In the above URL, the <message> will be a string parameter.
Now, I will define this URL in my urls.py file. The urls.py file will look like this:
from django.urls import path
from . import views
urlpatterns = [
path('showmessage/<str:msg>', views.showmessage, name = 'showmessage')
]
You can see I have defined the str path converter and msg is the name of the parameter.
Now let us change the views.py file:
from django.shortcuts import render
def showmessage(request, msg):
return render(request, 'result.html', {'msg' : msg})
I have used the result.html template to render the message which 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>Products</title>
</head>
<body>
<h2>The message is : {{msg}}</h2>
</body>
</html>
Now if you want to send a string parameter, suppose “Hello World”, you can define this string in the URL as:
http://127.0.0.1:8000/showmessage/Hello%20World
Here the space character needs to be URL encoded. %20 specifies the URL-encoded space character. The response can be seen in the below image:
You can see that that the string parameter passed, is rendered in a Django template.
Also, read: Difference between app and project in Django
Django URL slug parameter
A slug is generally used to fetch a particular webpage. A slug is created in such a way that it is easy to understand the relevance of the webpage by just reading the slug.
An example of a URL using a slug as the URL parameter is https://pythonguides.com/how-to-install-django/.
In the above URL, the how-to-install-django part is a slug.
Generally, this slug is created from the webpage title. All the words are converted to lowercase and separated by a hyphen symbol.
In this section, I will use the slug path converter to accept the slug as the URL parameter in Dajngo.
Suppose I have created a topics endpoint for my blog website and I want to use the below URL to display a particular blog post:
http://localhost:8000/topics/<blog post slug>
Firstly, I have to create a path in the urls.py file. In my case the urls.py file will be:
from django.urls import path
from . import views
urlpatterns = [
path('topics/<slug:msg>', views.showarticle, name = 'showarticle')
]
Here you can see that I have defined the path converter type as slug and the name of the URL parameter is msg.
Secondly, I have to define a function named showarticle in the views.py file as shown below:
from django.shortcuts import render
def showarticle(request, msg):
return render(request, 'result.html', {'msg' : msg})
Now I will render this slug inside a Django template named result.html. In the Django template, I will receive the slug parameter 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>Welcome to Python Guides</title>
</head>
<body>
<h2>The blog post slug is : {{msg}}</h2>
</body>
</html>
Now let us send a request to the following URL in a browser:
http://127.0.0.1:8000/topics/get-data-from-get-request-in-django
In the above URL, get-data-from-get-request-in-django is the slug that we are passing as the URL parameter.
Hence, in this way, you can pass a slug as a URL parameter in a Django application.
You may also like to read the following tutorials on Python Django.
- How to Get Current time in Django
- Validate URL string in Python Django
- How to Create model in Django
- Python Change Django Version
- Python Django get
- Python Django filter
- Python Django group by
Thus, you might have learned how you can pass and fetch various types of URL parameters in a Django application.
We have also created an article on How to get data from a GET request in Django. You can read this article to know about the usage of GET parameters in a Django application.
- How to get parameter from URL in Django
- Django URL pass parameter to view
- Django URL parameters in template
- Get parameters from URL in Django example
- Path converters Django
- Django URL parameters string
- Django URL slug parameter
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.