Codegeek.io Django

Introduction to Django: Python Web Framework

Django- Intro

It doesn’t matter to learn django whether you are new to web development or not. By learning django you will be able to develop a web application in a different way, plus using python. Till now you have enjoyed python, right? No? Then go through the python basics first and I am sure you haven’t gone through it as no one can say that they didn’t enjoy python. Learning Django being a python framework is also as much as python, maybe more, while you are fed up with repetitive PHP and SQL codes. The best part of django is that you can make the web applications interact-able and functional using your python knowledge and hence will have fun doing things quickly.

Django is a python web application framework developed for those who want to develop complex web applications with their python skills lot quicker than traditional web developers.

Web Frameworks

According to the Wikipedia web framework is a software framework that is designed to support the development of web applications including which includes web services, web resources and web APIs. I will keep things short and crisp to get into the real thing quickly. If you are curious to learn more about Web Frameworks then visit Web Framework Wiki Page here.

Requirements to move forward:

  • A computer, of course with python installed.
  • Basic knowledge of python including control structures, data structures, classes,objects,inheritance and yeah, if possible learn about regular expressions too.
  • Understanding of HTML codes.
  • An Internet connection, as you will enjoy reading this post through the Internet.

Things you will learn:

  • How to download and install django module
  • Creating a django project
  • Running the web server
  • Creating dynamic web pages
  • Creating dynamic web pages with dynamic urls

How to download and install Django

To get started you should have django framework installed in your system. And yeah, it is obvious that you need python installed on your system before installing django. You can download python here. If you are using Linux or Mac OS X, then probably python is pre-installed in your system. After you download and install python follow the steps below:

  1. First, you need to download the django library. You can visit django download page to download it.
  2. Just download the .tar file of django and extract it.
  3. Just navigate to the django directory using “cd” command in terminal and then type this code
    In Linux and OS X ->

    sudo python setup.py install

    In Windows ->

    python setup.py install

    And wait for installation to complete.

How To create a django project

Most of the steps will refer to windows system, if you are using another operating system, then you can skip them.

  1. If you know in programming a project is a set of all the settings and assets required to run a program. Likewise, we are also going to create a project which will contain all the files required for your web application.
  2. First, you need to add environment variables for the file “django-admin.py” located in your django installed directory,
    django>bin>django-admin.py

    I assume that you know how to add environment variables for an application in these steps. Otherwise, if you don’t know then I can just tell you in short, that in Windows it is in My Computer properties> Advance System Settings> Environment Variables> System Variables. Now just choose the “path” path variable and add the location of django-admin.py located in your system.

  3. Now your are ready to start a project. Other operating systems instead of adding django-admin.py environment variables need to navigate to its path through terminal to launch django-admin.py or need to open terminal via its directory.
  4. Launch your system terminal and type this command directly if used environment variables or navigate to its directory as mentioned in above step:
    python django-admin.py startproject [projectname]
    Use anything as projectname. For example in this article I will go according to this project:
    django-admin.py startproject djsite
    After that a project will be created will be created in the directory you have been navigated to
  5. Go through those files until you reach the next section as you have learned to create a new django project.

Playing with urls while running the web server

  1. As you have learnt to create to create a project, you need to go further to build a functional web application project. So, on starting the way you first need to check that if the server is running or not for your project.
  2. Don’t worry, you don’t need any external web server application for now, as django comes with a lite working web server. This function is included in django to help you check your developing quickly and easily.
  3. So, let’s start the web server by running the terminal and navigating to your project directory. Well, I think you will find it difficult to always run the terminal and navigate to things, so, I recommend you to use an IDE software to get on things directly and quickly. The IDE I personally use is “PyCharm”, and you can download it from here. And pycharm allows you to use the terminal and developing console in its environment, which you will be required much of the time.
  4. So, after doing all the above stuffs start your terminal there and use this command:
    manage.py runserver
    (Note: Make sure that you have been navigated to the directory where the manage.py file is present)
    If no error occurs, then your server has been started. By default the server address is localhost or 127.0.0.1 at port 8000.
  5. Start your browser and in the url bar type 127.0.0.1:8000
  6. The browser will then display a message like “It worked!
    Congratulations on your first Django-powered page.”
    and few more lines. The message is just to show that you have successfully run a server. We will understand more about the message returned on web page after a few steps.
  7. If you want, you can also change the port and server address too. To do that, just add the address and port like this.
    manage.py runserver [IP address:port]
    Like for example:
    manage.py runserver 192.168.1.2:80
    Now open the browser and just type “192.168.1.2” in the url bar. Obviously it will show the same message. And then check “127.0.0.1” in the url bar, but you won’t be able to connect to server. It is because you have changed the server address and port.

Getting started with Dynamic Web Pages

  1. We will start with a hello world printing page here. For starting any web stuff we always try to print “Hello World!” right? And yeah, you can view this article on Hello World code in Different Programming Languages.
  2. So, let’s get started now. First, create a python file in your project directory and name it as “hello_world”, though you can name whatever you want. I am just using “hello_world” for convenience.
  3. In the python file, enter the code below:

    from django.http import HttpResponse
    def hello(request):
    html='Hello World PageHello Web World'
    return HttpResponse(html)

    Now let’s go through the code:

    • At first we have imported the function HttpResponse from django.http module
    • Then, We have defined a function hello() such that it returns the string values rendered by Django applications.
    • Httpresponse takes one argument by default which is given as the “request”
    • html variable is used for the html content. Using this, I have created the html code of the web page.
  4. Now to use this function to display on web page you need to move to “urls.py” file first, which is already created by django for your project.
  5. In the urls.py you may see a code already there like this:

    from django.conf.urls import url
    from django.contrib import admin
    urlpatterns = [
    url(r'^admin/', admin.site.urls),
    ]
  6. The above code was secret for showing that success page when you started the server and loaded the url 127.0.0.1. So, similarly like you can also add your links and modify the data according to your needs. Here we will add few lines of codes to add another sub link to print the hello page. Just go like this:

    from django.conf.urls import url
    from django.contrib import admin
    from djsite.hello_world import *
    urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/', hello)
    ]

    urlpattern variable contains a list of links with its functions. So, we have imported all the functions from helloworld file. And in the url() we have included the url and the function hello too.
  7. It’s time to view the page in the web browser. So, first run the server using terminal and view the url in the browser. What you saw there? Well, you don’t need to say that to me, I know you did right.
  8. Let’s make it little more functional, uhmm like instead of “Hello World!” let’s print your name and age.
  9. Now move to that hello_world.py file again and modify the code as below:

    from django.http import HttpResponse
    def birthday(request):
    name='Jack'
    age=18
    html='Hello World PageHello %s, how is your %d birthday going?'%(name,age)
    return HttpResponse(html)

    Save the file and run the server again and visit the url again. What you saw?
    This?

    Hello Jack, how is your 18 birthday going?

    I know, right.

  10. For better link understanding change the url of page too in urls.py file like this:

    from django.conf.urls import url
    from django.contrib import admin
    from djsite.helloworld import *
    urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^birthday/', birthday)
    ]

How to start with dynamic urls

  1. In the above procedures we learnt to create dynamic pages, but the url we used were static. Let’s say if we want to print birthday wish for different children who were also born in different years. Some of you will say to make a program with lots of function with lots urls having different names and ages.
  2. But that will get too long first of all. Second, it will increase the size of the project and hence decrease in page performance. Third, the code will get hard to read. Fourth, you will know it yourself while creating something like that.
  3. So, what should we do? Is there any solution? Hmm, of course, there is !! And I am going to show it to you too.
  4. So, first change age and name of jack to just a variable given as a parameter to the function. Well, like this:

    from django.http import HttpResponse
    def birthday(request, name, age):
    html='Hello World PageHello %s, how is your %s birthday going?'%(name, age)
    return HttpResponse(html)

    name and age are given in parameters, so that we can call the function with any name and age by passing the arguments.
  5. Time to modify the urls.py, which is the most important step at this part, as we are going to deal with dynamic urls.
    Just copy the code below and follow;

    from django.conf.urls import url
    from django.contrib import admin
    from djsite.hello_world import *
    urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^birthday/(.+)/(\d+)/$', birthday)

    Explaining the code:

    • As usual, we have imported the birthday function using from djsite.hello_world import *
    • Now, as we have created a parametrized function, we will need to input the arguments and we did that thing by using dynamic urls. The variables in parenthesis act as the parameters of the function. The.  (dot) denotes any character and. + denotes one or more than one any character. Similarly, \d denotes any digit and \d+ denotes one or more than one digit.
  6. Yeah, now again run the server and enter the url as you have created in urls.py. And don’t forget to put the arguments, which are the characters/digits after each slash as defined.
    For example: Enter the url 127.0.0.1/birthday/Kath/17
    And the output on browser will be like this:

    Hello Kath, how is your 17 birthday going?
  7. In a similar way you can modify the things and get the results as you want.

That’s it for this post, but the series is not finished. Django is not this small. You will need to improve your django programming skills while improving python skills, both by practicing projects yourself and learning new topics from sources.
One such source is djangobook, where you will learn almost everything about django. Though, I will write another post on coming topics to simplify things for you, but till that you have to keep your practice in motion.
Hope you liked the post and learnt things which you wanted to.

Please share if you liked it and you can comment for any suggestion or doubt below. 🙂

Leave a Reply