Django add URL path to view

The URL path can map the URL to the view. Specifically, the URL path is composed of a string path, a view, and a name that can be used to name the URL within the scope of the project (the name is an optional parameter). Django traverses each URL path and stops at the first path that matches the requested URL. Subsequently, Django imports and executes the view matching the URL path, passing the HttpRequest class instance and keywords (or positional parameters).

Now add the following lines of code to the urls.py file in the blog application directory:

from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.post_list, name='post_list'),  
    path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
]

In the above code, the application namespace is defined by the app_name variable, and the URL can be organized by the application, and the corresponding name can be used when referencing. Here, two different paths are defined by the path() function. Among them, the first URL path does not receive any parameters and is mapped to the post_list view. The second path receives the following 4 parameters and maps them to the post_detail view.

Here, we use angle brackets to capture the URL value. Any value (in the form) defined in the URL path is captured as a string. We will use a path converter (such as int:year) to achieve a specific match, and return an integer and slug:post, which match the slug to a specific match (a string composed of ASCII letters, numbers, hyphens, and underscores) .

If path() and converters cannot meet current requirements, re_path() can be used to define complex URL paths containing Python regular expressions.

Next, you need to include the URL path of the blog application in the main URL path of the project. For this, you can edit the urls.py file located in the mysite directory of the project as follows:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls', namespace='blog')),
]

The new URL path defined by include refers to the URL path defined in the blog application, so it is included in the blog/path. In addition, such paths are also located in the namespace blog. In addition, the namespace must be unique throughout the project. Later, we can easily reference the blog URL, such as blog:post_list and blog:post_detail.

I will explain how to create a view template later, thank you for your support.

Guess you like

Origin blog.csdn.net/Erudite_x/article/details/112631717