Debug School

rakesh kumar
rakesh kumar

Posted on

Django URL mapping – A How-to Guide

django-url-mapping
django-urls-views
Basics of the Django URL Library
Here in the django.urls library, we have various functions that we are gonna use in our web application. Let’s learn more about them.

path(route,view, kwargs, name)
This function returns an element that needs to be included in urlpatterns. That is, path acts as a link between an element (for eg Views) and its URL.

route

This is the URL for a particular view. For eg: ‘/’ is a route.

So when we request this page from the URL, the server will return the view linked to it.

view

Here we need to write, the view name that we need to link. Or use the function “include” to add another urls.py file. (Like in the project/urls.py file)

kwargs and *args

args in function definition in python is a syntax used for the variable input argument list.

It is used with a single asterisk.

That is if for example, we need to input any variable number of arguments for a function, then we use *args. For eg let’s look at an example

Image description

So here we can give any number of arguments and *args will take up all of them. We can think that all the arguments are being saved by arg as some list, thereby using the line for arg in args, we are taking each element from the list.

the * is splitting up the list into elements thus *args gives you all the elements separately and args will give the elements as a list.

So if you will run the above code, you will get

Image description

kwargs in function definitions in Python are used for key-worded, variable arguments list.

It is used with double asterisk
That is if for example, we need to input any variable number of arguments (key-worded) for a function, then we use **kwargs. For eg. let’s look at an example then you will get more clarity about what exactly key-worded means

def myFun(**kwargs):
for item,price in kwargs.items():
print(f"{item}={price}")

myFun(Book=100,Pen=10,Watch=4000)
As you can see in the above example, we are able to pass complete values. The variable names and the values held by those variables with the use of the assignment operator.

We can think of the arguments being saved as a Python dictionary by the kwargs thus by using the line for the item, price in kwargs.items(), we are taking up the item(Book, Pen, etc) and their corresponding price(100,10, etc).

The ** splits the dictionary into its elements. Thus **kwargs gives you all the key-worded elements separately while kwargs gives you the key-worded elements as a dictionary.

Image description

Here in Django path(), we can use kwargs if we need to send more information to the view along with the URL route.

Image description

By using the URL name/25, Django will call views.name_id( request, id = 25, foo =’bar’).

name

Name is used to specify the name of the particular view that the URL is linking.

include(module,namespace=None)
This function takes another URL conf file that should be included by using this include function. That is to form a link with another urls.py file you should use include function. The namespaces can also be written inside but we don’t need to do that for now.

How to Map a URL to a View in Django

?

Image description

Here we are using path() function with the syntax learnt above:

path(‘ ’, sayHello, name = ‘sayHello’)
Enter fullscreen mode Exit fullscreen mode

Here sayHello is the function-based View name in views.py. We’re keeping the path as a blank string so we can access the view directly on the base directory – http://127.0.0.1:8000/ in my case.

URL mapping in Django Project

Image description

The path() function is linking the URL to the urls.py file present in the app. So we need the include() function with the syntax we learned above.

For example, here we used:

path(‘sayHello/’,include(‘HellpWorldApp.urls’))
Enter fullscreen mode Exit fullscreen mode

Apart from the path and include functions there are re.path() and register_converter() functions which we won’t be using much in our course of Python-Django.

Note: in project/urls.py we used:

path(‘sayHello/’, include(HelloWorldApp.urls)),
Enter fullscreen mode Exit fullscreen mode

Now here even if we write sayHello/ in app/urls.py and simply ‘ ’ in project/urls.py, the behavior will be the same.

Here’s a sample implementation:

apps/urls.py:
Enter fullscreen mode Exit fullscreen mode
path(‘sayHello/’, sayHello, name = ‘sayHello’)
Enter fullscreen mode Exit fullscreen mode

projects/urls.py:



![Image description](https://www.debug.school/uploads/articles/nft2fg3c2gmfxajbzgs9.png)




![Image description](https://www.debug.school/uploads/articles/h144yw07r2sv66pm085r.png)















path(‘ ’, include(HelloWorldApp.urls))
Enter fullscreen mode Exit fullscreen mode

For more than one View, it is suggested to use this new way. And hence from now on, we will keep the endpoints in apps/urls.py and ‘ ‘ (host website linkage) in project/urls.py.

Hence, we can change them now, as shown in the image below.

For more than one View, it is suggested to use this new way. And hence from now on, we will keep the endpoints in apps/urls.py and ‘ ‘ (host website linkage) in project/urls.py.

Hence, we can change them now, as shown in the image below.

Image description

Image description

Now that we know about the path and include functions, let’s move one to make more than one view and link them up to different endpoints.

Django URL mapping for more than one View
Just as we did in our hello world article, we are going to add one more View in the views.py.

Let us create a view Book. Add the code:

Image description

Image description
For the newer View, we need to make another endpoint. So in the apps/urls.py we have to just add another path for the endpoint ‘ Books/’

Image description

Image description

Now lets run the server and check in the Browser.

Image description

Image description

URL Mapping – Variable Endpoint

Let us make a View that takes the Book ID as request and then simply returns a line giving us the ID.

In the views.py, let’s make another View having the endpoint like ‘Books/’.

Image description

Here we are just taking the book ID along with the request, and then we will return Response specific to that particular Book.

Image description

Now we have to add the endpoint in the apps/urls.py.

Image description

Image description

Image description

Here we have to mention using the syntax shown

Let’s run and check

Image description
Now let’s run the browser and visit 127.0.0.1:8000/Books/1

Image description

We can also check for any other random Book ID.

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Top comments (0)