URL patterns

Django URL patterns are very clean and simple and make for nice websites where the URLs are short and memorable. To make this possible, there is matching of the requested URL with a view (or application-level URL that matches with a view). The URLs and their destination are matched inside a list called urlpatterns

Within the project folder (C:Projectschapter12chapter12), there is a script called urls.py just underneath settings.py. This script controls project-level URL routing. For this application, we'll also add application-level URLs inside the arenas folder and will point the project-level URL routing to the application URLs.

Open up the project-level urls.py, and copy the following code over any existing code:

from django.urls import include, path
from django.contrib.gis import admin
urlpatterns = [
path('', include('arenas.urls')),
path('arena/', include('arenas.urls')),
path('admin/', admin.site.urls),
]

This code will redirect the requests to two different URLs in the application-level urls.py file, where they can be further sorted. Any requests sent to the admin URL are handled by the administrative code. The path function accepts two required parameters: the URL path (for example, 'arenas/', which goes to http://127.0.0.1:8000/arenas), and the view or application-level code that will accept the request. The include function is used to add the available URLs from the Arenas application into the project level URLs.

To create the application-level URLs, create a script called urls.py inside the Arenas application folder. Copy the following code:

from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('arena', views.arena, name='arena'),
]

This time, the function path directs requests to views (that will be) inside the views.py script. Both the base URL and the arena URL are redirected to a view. The optional parameter name is also included.

Note that a major change in Django URL patterns was introduced in Django 2.0. Earlier Django versions do not use the path function but use a similar function called url. Ensure that you are using the newest version of Django to match the code here.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset