Sunday, 12 April 2015

Django - Working with URLs

In this post I'll discuss 
  • how to handle URL requests?
  • how to access parameters from query string?
  • how to design RESTful URLs?
Handling URL requests

In Django, a project contains different applications. The project contains a file urls.py and each application also contains a file urls.py.

The project runs on the server on a port (e.g. 8080). When this port is hit, then the server looks into urls.py file to find further matching URL and then it invokes respective view.

The projects urls.py file contains a variable urlpatterns. This variable references a call to patterns functions which takes calls to url functions as arguments. Each call to url will specify a patterns to match and then redirects to corresponding applications's urls.py file where further pattern matching is performed.

E.g. consider a URL http://localhost:8080/com/departments

Following is the project's urls.py file.
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',    
    url(r'^admin/', include(admin.site.urls)),
    url(r'^polls/', include('polls.urls')),
    url(r'^com/', include('company.urls'))
)

As the server running on localhost port 8080 will receive the URL request, it will see com/  in http://localhost:8080/com/departments and will go to urls.py file in company application.
from django.conf.urls import url
from company import views

urlpatterns = [
    url(r'^departments$', views.department_list, name="department")
]

Here it will match the next part http://localhost:8080/com/departments and will invoke function in the view department_list passing it request object. The views.py file in company application is as follows.
from django.http import HttpResponse

def department_list(request):
    return HttpResponse("Received request to show departments.")

The department_list will just return an HttpResponse. The output is as follows.


Accessing params from QueryString

E.g. consider a URL http://localhost:8080/com/departments?name=HR

Now we need to modify view department_list to read the value of query parameter name. Therefore,
from django.http import HttpResponse


def department_list(request):
    if 'name' in request.GET and request.GET['name']:
        dept = request.GET['name']
        return HttpResponse("Received your request for {}".format(dept))

    return HttpResponse("Received request to show departments.")

Here we check that the dictionary request.GET contains key name and the value isn't None. If the condition evaluates to true the the parameter from query string is read and response is sent to the user. A sample screen cap is as follows.


Designing RESTful URLs

Note: Here we just discuss how to create RESTful looking URLs and not Django Rest Framework, which will be covered in a different post.

A RESTful URL to get department with id=6 will be http://localhost:8080/com/departments/6. For this we need to update urls.py file which will look as follows.
from django.conf.urls import url
from company import views

urlpatterns = [
    url(r'^departments$', views.department_list, name="department"),
    url(r'^departments/(?P<dept_id>[0-9]+)$', views.department_only, name="department_only")
]

The new entry tells that after departments/ match for numbers, make it as a parameter with name dept_id and pass it to view department_only. The first parameter will always be request, all other parameters will be added next to it. Hence the new function in views.py will be as follows.
def department_only(request, dept_id):
    return HttpResponse("Received your request for {}".format(dept_id))

And the output,

As we learned how to build RESTful URLs, we will continue our learning with Django REST Framework and building RESTful applications.

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.