Django crash course – Part 1 Basics

Deepak Radhakrishnan
()

Django is a web development framework that supports building and sustaining excellence web applications. Django assists reduce repetitious actions making the development process a simple and time-saving experience. This tutorial gives a total perception of Django.

Contents

  • Target Audience
  • Prerequisites
  • What we cover today?
  • What is so special about Django?
  • What is Model View Template -MVT?
  • Installation
    • Prerequisites
    • Setting Environment
    • Django Installation
  • Django Project vs Django Application
  • Let’s create Our first Django Project
  • Anatomy of the basic Django Project
  • Run the Project
  • Create a Django Application
  • Anatomy of Django Application
  • Register your Application to Project
  • Url Mapping
  • Conclusion

Target Audience

This tutorial is designed for developers as well as students who want to learn how to develop quality web applications using the smart techniques and tools offered by Django.

Prerequisites

A little bit of knowledge of python, html, web applications.

What we cover today?

In this tutorial, we will cover some basics of Django. Mainly Installation, Virtual environment, Creating Project and Application, Running Project and URL mapping.

What is so special about Django?

  • Loosely Coupled − Django aims to make each element of its stack independent of the others.
  • Less Coding − Less code so in turn a quick development.
  • Don’t Repeat Yourself (DRY) − Everything should be developed only in exactly one place instead of repeating it again and again.
  • Fast Development − Django’s philosophy is to do all it can to facilitate hyper-fast development.
  • Clean Design − Django strictly maintains a clean design throughout its own code and makes it easy to follow the best web development practices.
  • Object-Relational Mapping (ORM) Support − Django provides a bridge between the data model and the database engine and supports a large set of database systems including MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through Django-nonrel fork. For now, the only NoSQL databases supported are MongoDB and google app engine.
  • Multilingual Support − Django supports multilingual websites through its built-in internationalization system. So you can develop your website, which would support multiple languages.
  • Framework Support − Django has built-in support for Ajax, RSS, Caching and various other frameworks.
  • Administration GUI − Django provides a nice ready-to-use user interface for administrative activities.
  • Development Environment − Django comes with a lightweight webserver to facilitate end-to-end application development and testing.

What is Model View Template -MVT?

The name MVC will be familiar to you than MVT. MVT stands for Model View Template. In MVC architecture the controller is responsible for model and views. In the case of Django, it takes care of the controller (Software Code that establishes the communications between the Model and View), leaving us with the template. The template is an HTML file associated with Django Template Language (DTL).

Installation

Prerequisites

You must have Python 3.x and pip installed in your system .

Setting Environment

Creating your project inside a virtual environment is always a good idea. Additional modules you are installing will not harm your other codes also virtual environment makes your code more sharable and easy for migrations.

pip install virtualenv

Once installed you can create a project folder and inside that folder run the below commands in terminal.

virtualenv env

This command will create a virtual environment with the name env. Now all we have to do is to activate the virtual environment .

source env/bin/activate #for linux based 
source env/usr/local/bin/activate #for Mac users

By running this your virtual environment will be activated . You can see (env) in terminal like below.

(env) deepakradhakrishnan@Deepaks-MBP djangoproject % 

To confirm that , it is using the python inside the virtual environment you can check with the following command.

which python

This command will show you the current path of python which it is using right now. It muse be the path inside your virtual environment.

Django Installation

 python -m pip install Django

Bingo. Just running this command will do the job.

This will install the latest stable release of Django. You can also install the required versions using “python -m pip install Django == 2.2.10”.

You can check your Django Version by running the below commands in a python shell ,

import django
print(django.get_version())

Django Project vs Django Application

Let’s make this simple . Django application represents the whole web application and the Django Application refers to individual Apps functionalities like Login , Comment , Post . It is not necessary to have lots of Apps you can also have one App. But dividing the tasks to different Apps make the Project code looks beautiful .

Let’s create Our first Django Project

Unlike Flask (another Python Based Web Development Framework ) when we create a Django Project it automatically creates a basic skeleton/basic-structure of the Application. Let’s make one (make sure you are inside Virtual Environment. This is the common mistake we do.),

django-admin startproject djangoproject

You can observe that it will create a bunch of files and folders. Let’s see what all those files.

Anatomy of the basic Django Project

As you can see a folder/directory named “djangoproject” is created and there is another directory with the same name is inside this directory. Also, we have a manage.py file. Inside the secondary directory, we have “__init__.py”, “settings.py”,”urls.py” and “wsgi.py”.

__init__.py : This acts as a package .


settings.py: This file contains the settings of your Project.

urls.py: As the name indicates this causes the URL mapping.

wsgi.py: This file help Us to deploy our application using the Web Server Gateway Interface(WSGI).

Run the Project

Running your project is simple by just typing the following command (make sure you are inside the project directory inorder to access manage.py file),

python manage.py runserver

You can observe that your web application is successfully running on the localhost with a port number of 8000. You can copy-paste the address to a browser or just click on the link by pressing Ctrl(for windows and Linux)/Cmd (Mac). You will be able to see a default, Django Page.

Create a Django Application

A Django application is nothing but an App that serves a specific application/section of your entire web application. eg: Comment App, Post App, QR reading App, etc. Creating an App is simple ,

python manage.py startapp djangoapp

Here “djangoapp” is the app name. This will create a skeleton (folders and files) to set up your application. Let’s see what are those files.

Anatomy of Django Application

You can observe that Django is created a sqlite3 database, application folder, migrations folder and few files inside the application folder.

__init__.py: As I mentioned earlier this is a blank file which python treats this as a package.

admin.py: Can be used to register your so that you can use it in Django’s admin interface.

apps.py : Used to place application-specific configurations.

models.py : Here we store the application’s data models.

tests.py : This can be used to write test functions to test our code.

views.py: This is one of the important files where we configure our application views which will handle requests and return responses.

Migrations Directory : This stores database specific information.

Register your Application to Project

Creating App doesn’t mean that your Django Project is going to use that App directly. You need to tell Django Project that you have created an app called ‘djangoapp’ (or whatever the name you have given for your app) by adding that name under installed apps in settings.py of your main Django Project.

Now make sure your project is working fine by running the server .

python manage.py runserver

Creating Views

Views are nothing but the methods that handles the requests and giving corresponding responses. Let’s create a simple view.

In your application folder open view.py file and type the following code ,

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def index(request):
    return HttpResponse('<em>Hello World,</em> this is from index view')

You have created your first view. Now we have to inform Django App this view should load when a particular URL is calling . That is called URL mapping .

Url Mapping

URL mapping can be done in multiple ways depends on your requirements. You can refer Django official website for more details. Here we will be discussing 2 methods.

  1. Function views
  2. Including another URLconf

Function views

First one is the direct method. This method is suited for smaller applications. And for complex applications, if you follow this method your code will become a mess.

Inside urls.py of your Django Protect add the following code,

from django.contrib import admin
from django.urls import path
from djangoapp import views  #dont forget to add this 

urlpatterns = [
    path('',views.index,name='index'), #'' indicates blank, ie, the just the doain/ that is index. 
    path('admin/', admin.site.urls),
]

Now save the file and run the project .

You can observe that our <em> tag is an HTML tag we given in a string is still converted as an HTML tag . Django is that powerful and simple framework .

Including another URLconf

This method is suitable for simple as well as complex projects. By adding an additional URLconf file inside your Django App and including it inside the main urls.py file makes the code beautiful and less complex.

Modify urls.py in Django Project ,

from django.contrib import admin
from django.urls import path,include #we need an addition library called include to perform this 
from djangoapp import views

urlpatterns = [
    path('',views.index,name='index'),
    path('appindex/', include('djangoapp.urls')),  #we use include() to add urls.py from Application 
    path('admin/', admin.site.urls),
]

Now create a file named “urls.py” inside your Django Application directory and add the below code .

from django.urls import path,include
from djangoapp import views

urlpatterns = [
   path('',views.index,name='index'), 
]

Here what we are doing actually is creating an extra urls.py file and transferring the corresponding to the request from the main urls.py to the one in the application directory. Then the response will be displayed to the URL pattern written in the main urls.py file.

Let’s run the project to check it’s working .

Conclusion

That’s all! Curious about how it works? Do try it and see for yourself. If you need more support, be sure to get in touch with me.

Thank you for visiting our Tech Rover blog! Stay tuned for more. Happy coding and building. 😊

How useful was this post?

Click on a starts to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow me on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

%d bloggers like this: