Adding URL Parameters and Query Parameters
Introduction to URL Parameters and Query Parameters
Welcome back! As you continue to build on your Django skills, it's time to explore a core functionality of web applications: handling URL and query parameters. This lesson is both a natural extension of your prior learning and an essential skill for any web developer. By integrating dynamic elements into your URL patterns, you'll make your application more flexible and interactive.
What You'll Learn
In this lesson, you will explore how to:
Add URL Parameters: URL parameters are parts of the URL that can be used to pass information to views. We will create a URL pattern that accepts a user's name and displays a personalized message.
Notice, that the user_view function takes an additional parameter name that corresponds to the URL parameter. Let's now set up the URL pattern in the project's urls.py file.
This code sets up a URL pattern that captures the user's name and passes it to the user_view.
With this setup, when a user navigates to http://127.0.0.1:3000/user/Alice/, they will see the message Hello, Alice!, since the URL parameter Alice is passed to the view as the name argument.
Utilize Query Parameters: Query parameters allow you to send additional information to your views using the URL. We will demonstrate how to create a search functionality that processes query parameters.
Notice that in this case, we are using the GET method to access the query parameters. The search_view function retrieves the query parameter q and displays the search term.
Let's set up the URL pattern in the project's urls.py file:
We don't need to specify the query parameter in the URL pattern, as it is passed as part of the URL.
With this, when a user navigates to http://127.0.0.1:3000/search/?q=python, they will see the message You searched for: python, since the query parameter q=python is passed to the view.
Notice that the query parameter is separated from the URL by a ? and can contain multiple key-value pairs separated by &, for example, http://127.0.0.1:3000/search/?q=python&sort=asc.
