Blog

urls.py is a url mapper in Django project .The mapper called as urlpatterns defines different types of url patterns and corresponding view function.

If an HTTP request is received that has a URL matching in the urlpatterns invokes the corresponding view function and passes that request.

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    (r'^$', 'djangorocks.blog.views.index'),
    url(
        r'^blog/view/(?P[^\.]+).html',
        'globalbridge_blog.gbs_blog.views.view_post',
        name='view_blog_post'),
    url(
        r'^blog/category/(?P[^\.]+).html',
        'globalbridge_blog.gbs_blog.views.view_category',
        name='view_blog_category'),
]

Explaination

urls are usually stored in a file called urls.py
The urlpatterns object is a Python list with items path().The first argument that the path() takes is the pattern(Route) that will be matched.

path() methods use angle brackets (<>) to capture the data from the URL and passes to the view function as a named argument(s). For example, if you have10 posts and the url looks like this ‘blog/my-blog-name’, then the <> takes the slug, i.e., my-blog-name from the URL to display corresponding content in the pages. You will see this in detail in coming Voting App Tutorial With Django.

The second argument is another function that invokes corresponding functions when the URL is matched. The notation globalbridge_blog.gbs_blog.views.view_post indicates that the function is called view_post(). This can be found in the views module (views.py).

A third argument name is an option which can be used to shorten the URL. You will learn about it later in this article.

Next >> Django Tutorial : Request handling / Writing Django Views (view.py)

Leave a Reply

Your email address will not be published. Required fields are marked *