URL configurations in the django view layer

In today’s high-quality web application a clean,elegant URL scheme is very important.With django we can design URLs as we want,with no framework limitations.

We have to create a module called a URLconf (URL configuration) to design URLs for an app.This module URLconf  will contain pure python code and is a mapping between URL path expressions to views.This mapping can be short or long based on requirement.

Here’s a sample URLconf:

from django.urls import path

from . import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
]

Few Points To Note:

  • We will use angle brackets like <> to capture a value from URL.
  • We don’t have to add any leading slash.For example, it’s articles, not /articles.

Example requests:

  • If we have a url like /articles/2005/03,then it would match the third entry in the given url’s list.In that case django would call the function views.month_archive(request, year=2005, month=3).
  • If we have a url like /articles/2003/, then it would match the first entry in the given url’s list not the second one.In that case django would call the function views.special_case_2003(request).
  • If we have a url like /articles/2003/03/building-a-django-site/ then it would match the last pattern in the given url’s list.In that case django would call views.article_detail(request, year=2003, month=3, slug=”building-a-django-site”).

Using regular expressions

We can also use regular expressions for defining our URL patterns,if paths and converts syntax isn’t sufficient.To do so we will use re_path() instead of path().

In python the syntax for named regular expression groups is (?P<name>pattern),where name is the name of the group  we want to use and pattern is the pattern we want to match.

Now we will write the URLconf  again using regular expressions which we written earlier in the post.

from django.urls import path, re_path

from . import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$', views.article_detail),
]

Error handling

Django invokes an error-handling view when it can’t find a match for the requested URL or when an exception is raised.

Writing Views

A Simple View

As an example check the following view that returns the current date and time as an HTML document.

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

Now let’s go through each line once:

  • So in the initial two lines,we imported the class HttpResponse from the django.http module and also imported python’s datetime library.

  • Next in the third line we have defined a function called current_datetime,which takes the request object as it’s parameter.
  • The view function returns an HttpResponse object that contains the generated response as a result.

The Http404 exception

class django.http.Http404

We are responsible for defining the HTML content of resulting error page as following, whenevar we return an error as a HttpResponseNotFound.

return HttpResponseNotFound('<h1>Page not found</h1>')

If at any point in a view function if user raise a Http404 error,then dajngo will catch it and return the standard error page for our application along with an HTTP error code 404.

For Example:

from django.http import Http404
from django.shortcuts import render
from polls.models import Poll

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request, 'polls/detail.html', {'poll': p})

This is all about URLconf’s in django’s view layer and error raising in views in django.

Leave a Comment

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