OceanWP

Django Urls

Estimated reading: 3 minutes

Django uses a URL dispatcher to match URLs to views. In order to create a URL for your view, you need to create a URL pattern in your project’s main urls.py file. Here is an example of how to create a URL pattern for a view called “index_view” in a Django project:

Note: Before Getting started to create a URL pattern for a view the first step is to do is to create an urls.py file in your apps folder

Here is an example of the file structure for a Django app that includes a urls.py file:


myapp/
    migrations/
    __init__.py
    admin.py
    models.py
    views.py
    urls.py
    

Now let’s create a URL pattern for a view called “index_view” in a Django project:


from django.urls import path
from . import views

urlpatterns = [
    path('index/', views.index_view, name='index'),
]

In this example, we’re using the path() function from django.urls to create a URL pattern. The first argument passed to path() is the URL pattern that we want to match. In this case, it’s “index/”. The second argument passed to path() is the view that we want to call when this URL is accessed. In this case, it’s views.index_view.

The third argument is the name of the URL which can be used for reverse() lookup.

When a user visits “http://ideasorblogs.in/index/“, the index_view function will be called and the contents of that view will be displayed.

Additionally, you can use regular expressions to create more complex URL patterns. For example, you can use the following pattern to match a URL with a number at the end:


path('index/<int:id>/', views.index_view, name='index'),

This matches URLs like ‘index/1/’, ‘example/2/’, etc, and passes the matched value as parameter ‘id’ to the view function.

You can also use re_path() functions to match more complex regular expressions.

You can also include other URL patterns by using the include() function and passing it to the URLs module of the included app.


from django.urls import path, include

urlpatterns = [
    path('', include('tutorial.urls')),
]

This will include all the URL patterns defined in the urls.py file of the ‘tutorial’ app in the main URL patterns.

It is important to note that the order of the url patterns is important, as Django will match the first pattern that matches the requested URL.

In this tutorial, we’ve covered the basics of creating URL patterns in Django. With these tools, you should be able to create URL patterns that match any type of URL you need for your project.

Publisher
Share this tutorial