This is part of the series Django For Beginners we are going to see about apps in app and we will see about urls in python.

In this post we are going to learn all about urls in django,, let’s get started.

Understanding URLS in Django

Let us first understand where we write our urls, we write our urls in our project folder in urls.py file, as shown below.

 πŸ“‚ myDjangoSite
	- πŸ“‚ myDjangoSite
		- πŸ“„ __init__.py
		- πŸ“„ asgi.py
		- πŸ“„ settings.py
		- πŸ“„ urls.py
		- πŸ“„ wsgi.py
	- πŸ“„ manage.py

In urls.py specifically we write path for our django website in urlpatterns list, in a patterns as shown below,

from django.urls import path
from . import views

urlpatterns = [
    path('', views.Home, name="home"),
    path('about/', views.About, name="about"),
]

The syntax for path is as follows,

path( route, view, name )

Where route is a string argument and denotes the relative path we want for that view. View is a view it may be a class-base or a function-based view, and last argument which is name is keyword argument and is optional but it comes in handy when we redirect uses within website and it is also is a good practice to name views as it makes clear that what we are dealing with. Each item in urlpatterns list denote a path and we are allowed restricted to use python safe keyword in path as path is a string.

Note : One of the most common mistakes done is adding / in start of route it will cause the route to be https://example.com// for https://example.com/, as django adds it for you by default. Also always add / in the end of the each route otherwise it will cause a variety of weird errors ( at least it did for me ), and if you visitors for some reasons open /my-route and your route in urls.py is /my-route/ then your user will be automatically redirected to /my-route/ automatically without any more extra work.

But when we expand we and create more and more apps it is not possible to manage path for all the apps in a single file as it will get messier and will cause a lot of error down the road, so to avoid this we break urls.py into chunks such that each app has it a file in which it stores its urls and it is called urls.py, you may need not to call it urls.py but it is a standard to call it as urls.py.

The file structure may appear something like this,

 πŸ“‚ myDjangoSite

 	- πŸ“„ manage.py

	- πŸ“‚ myDjangoSite
		- πŸ“„ __init__.py
		- πŸ“„ asgi.py
		- πŸ“„ settings.py
		- πŸ“„ urls.py
		- πŸ“„ wsgi.py
	- πŸ“„ manage.py

    - πŸ“‚ myFirstApp
        - πŸ“‚ migrations
        - πŸ“„ __init__.py
        - πŸ“„ admin.py
        - πŸ“„ models.py
        - πŸ“„ tests.py
        - πŸ“„ views.py
        - πŸ“„ urls.py
        - πŸ“„ apps.py

    - πŸ“‚ mySecondApp
        - πŸ“‚ migrations
        - πŸ“„ __init__.py
        - πŸ“„ admin.py
        - πŸ“„ models.py
        - πŸ“„ tests.py
        - πŸ“„ views.py
        - πŸ“„ urls.py
        - πŸ“„ apps.py

Path and Include Methods

Each app contains its own urls.py but now to question lies what is inside those urls.py and the answer is it is same as normal urls.py.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.Home, name="home"),
    path('about/', views.About, name="about"),
]

Now you may ask me how to get this in main urls.py and to get this we need to use include method from django.urls as shown below,

from django.urls import path, include

urlpatterns = [
  path('', include('myFirstApp.urls'), name="my_first_app_urls"),  
  path('', include('mySecondApp.urls'), name="my_second_app_urls"),  
]

Everything is same but the only change is that in place the view we pass a include and you should have noticed that we pass an empty string as first parameter and we do so to route the whole routes in urls files of the app.

The syntax of include method is as follows,

include( relative_path_to_urls_file )

It is useful when you want to route all the urls in an app to a path say https://example.com/myroute/<path>/ and use path of the route in place of <path> there are two ways of doing this one is adding myroute/ to all route in all path in a file and other is used to pass 'myroute/' to include as shown below,

path('myroute/',  include('myFirstApp.urls'), name="my_first_app_urls")
Django for Beginners: Build Websites with Python and Django

Django for Beginners: Build Websites with Python and Django

This is a awesome book written by Willam S. Vincent and this book is completely updated to the latest Django 3.1 if you prefer it. It is a good choice and it is my personal reccomendation for you. Just check it once it has few pages avilable to read for free online. 😊

Dynamic Urls - Retrieving Data from URLS

Creating dynamic links for most of the modern day websites to manage their data, and django makes it so easy for us, let’s see this by example,

from django.urls import path
from . import views

urlpatterns = [
	path('u/<str:username>/', views.userInfo, name="home"),
]
from django.http import HttpResponse

def userInfo(request, username):
    return HttpResponse(username)

We create dynamic urls by using < > and then passing variable name like this, < my_var > an to check for valid data type we also use path converters like this < str: my_var > and I will provide all the valid type at the end of the post.

You may ask how to get data from urls in the view and as you can already see we accept it as a argument for the function and note that variable name used in the route of the path should be same to one that is passed as an argument in the function otherwise it will throw errors.

You can get as much dynamic data from a single URL by creating appropriate variable to get date from it.

All the valid path converters are as follows,

Path Converteruse
strIt check whether data is string and try to convert data to string.
intIt check whether data is int and try to convert data to integer.
slugIt check whether data is slug and try to convert data to slug.
uuidIt check whether data is uuid and try to convert data to uuid.
pathIt is bit more different it gets path like \a\b\c\d\e\ as a argument and provide it for futher use in views.

Hope you guys like it and if you like then please share it πŸ˜… it helps me a lot. Also check out my other posts 😊.