Getting Started with Django
Django — The Web framework for perfectionists with deadlines.
We must know what web frameworks are — before we dive into Django.
Web Frameworks and their importance
A Web Framework provides a standard way to build and deploy web applications on the web. They provide support for web services, resources, and APIs. It’s a complete package designed to aid the process of developing web applications. There are several web frameworks for different programming languages. Some of the popular ones are :
- Angular/ React/ Vue (JavaScript) [Front End Frameworks/ Libraries]
- NodeJS/ Express (JavaScript) [Back End Frameworks]
- Django/ Flask (Python)
- Ruby on Rails (Ruby)
- Laravel/ Symphony (PHP)
Why do we need web frameworks?
Well, you don’t, if you are willing to handle all CRUD operations, user authentication, notifications, sessions, cookies, render static files. Every time you make a new website, you will need to reimplement all the features again. A Web Framework provides the tools for all these operations out of the box. It allows you to focus better on making your website and accelerates your development process. Using a well-adopted web framework also implies that you will receive the support of the developers belonging to that framework’s community.
What is Django?
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
The above definition fetched from djangoproject.com defines Django in its entirety. It uses MVT (Model-View-Template) Architecture. [What‘s that? More on that later] and can be used in conjunction with other web frameworks like Angular, React, and Vue. Django is the most opt-for framework for intermediate-level and big projects because of its completeness in terms of the variety of tools it provides — both for frontend and backend. Since it is a python framework, it implies that we can utilize the general-purpose nature of the Python programming language to make all kinds of websites.
Some Websites you might have heard of:
- Disqus
- Bitbucket
- NASA
- Mozilla Firefox
Django powers all these sites. It might have given you an idea about the versatility of the framework. Check out this link, if you still have doubts about whether you should use Django in your project.
MVT (Model-View-Template) Architecture
Every Django project is a composition of three different components working with each other. These three components are Model (Helps to Handle Databases), View (Renders the template and handles business logic), Template (Presentation layer defines the UI).
An appropriate view handles the URL received by the webserver. Then, the selected view displays the template customized with the data provided by the model to the client.
Hello World in Django
Let the action begin.
Let’s first make a folder and call it helloworld. Next, we will create a virtual environment using the venv module. The name of our virtual environment will be — .venv
python -m venv .venv
Next we will activate the virtual environment using:
source .venv/bin/activate (linux)
OR
source .venv/Scripts/Activate.bat (windows)
Now it’s time to install django:
pip install django
Now that our virtual environment is activated and Django installed, we can dive into making our application.
Note: Virtual Enviroments in Python are tools that create an isolated environment for Python projects. This means that each project can have its own dependencies, regardless of what dependencies every other project has. It also makes installing dependencies for projects easier.
Creating a django project
Now we will use some command line tools installed by django to create and manage our django projects. Run the following command to create the project:
django-admin startproject helloworld .
This will create the create the project in your current directory. After running this command your directory structure should look something like this:
helloworld/
│
├── helloworld/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
│
├── .venv/
│
└── manage.py
Now the next step is to fire up your server and test if your project is up and running:
python manage.py runserver
Then visit localhost:8000
and you should see this:
Congratulations! You have made your first Django site.
Making your First Django App
Now that we have our Django project set up correctly, we will move on to creating a helloword Django application. To create the app, type this into the shell:
python manage.py startapp my_app
This will create a new Django app called ‘my_app’ and place it under the parent directory. Now your project directory should like this:
helloworld/
├── .venv/
│
├── helloworld/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py│
│
│── db.sqlite3
│
│── manage.py
│
└── my_app/
├── __init__.py
├── admin.py
├── apps.py
├── migrations/
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
So what are all these files under the my_apps directory?
- __init__.py : Initialises the app direcory as a python package.
- admin.py : Contains code for Django Admin pages.
- apps.py : Contains code for configuring the application
- models.py: Contains all the classes that the Django ORM converts to database tables
- tests.py: Contains all test classes
- views.py: Contains all function or class based views that handles what data is displayed in HTML templates.
Now we need to register our app my_app
to the django project helloworld
. For that, we just need to add our app to the INSTALLED_APPS list inside the helloworld/settings.py
file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
]
Creating a View:
Views in Django are a collection of functions/classes inside the views.py
file in your app directory. Each function or class handles the logic that gets executed each time a different URL is visited.
Now we are going to create our hello_world
view function in the my_apps/views.py
file:
from django.http import HttpResponsedef hello_world(request):
return HttpResponse('<h1>Hello, World!<h1>')
When this function is called, it will render the HTML Response which is being returned from the view function. The view function takes one argument, request
. This object is an HttpRequestObject
which is created whenever a page gets loaded. It contains information about the request, like whether if it is a GET or POST request.
What now? Remember the MVT diagram from before, you need to map a URL to the view function, so that you can visit the page you’ve just created. Inside helloworld/urls.py
, add the following lines:
from django.contrib import admin
from django.urls import path, includeurlpatterns = [
path('admin/', admin.site.urls),
path('', include('my_app.urls')),
]
The include('mp_app.urls')
looks for a urls.py
under the inside the my_apps/
directory. But the file doesn’t exist yet, so we will now create it:
from django.urls import path
from my_app import views
urlpatterns = [
path('', views.hello_world, name='hello_world'),
]
This maps the hello_world
view to the url — localhost:8000/
.
Restart the server and you should see your page rendered out:
Congratulations! You have made your first django application.
So What’s Next?
Well, keep practicing and learn more about Django from the official documentation. With Django, you will be developing and deploying web applications like clockwork.
I hope this little introduction helped you to gain an understanding of the Django Framework. In a future tutorial, we will learn about Django models and templates and apply our knowledge to build a portfolio site. Make sure to check it out.