Django is a popular Python open-source web development framework used for rapid web development and clean, pragmatic design. It is a robust and approachable framework that lets you focus on your application by having salient parts pre-baked that are fairly standard practice. This framework makes it easier to focus on writing apps instead of reinventing the wheel.
Django is used in all sorts of tech stacks, including Instagram, Pinterest, Mozilla, and Eventbrite. Companies everywhere are actively using Django and invested in its development. In 2020, it is the 4th most wanted web framework according to StackOverflow.
Today, we will introduce Django and build a program from scratch. If you want to get started today, knowledge of the following concepts will be helpful.
- How HTTP Requests work
- How relational databases and how SQL works
In this article, we will look at:
- What is Django?
- Django Design Pattern
- Django vs. Flask
- How does Django Work?
Hello Worldin Django
- Build your first Django program from scratch
- What to learn next
Take your Python web dev skills to the next level
Learn how to create powerful Django apps. Ideal for intermediate or beginner Python developers.
Django is a high-level, web framework written in Python for rapid development and pragmatic design. A framework is simply a collection of modules that are grouped together for creating web applications from a reliable, pre-existing existing source. Django offers a large collection of theses modules.
Django was created in 2003 when web developers working for a newspaper company in Lawrence, Kansas, needed a better way to organize their code. Because the developers were surrounded by many newspaper journalists, clear documentation became an integral part of the project that became known as the “Django” project.
Django has since blossomed into a massive online open-source community that has a solution for just about everything you can think of, from authentication to content management systems.
There are several benefits to using Django over other possible solutions:
- Fast: because of the way Django is set up, you can get off the ground very quickly. It doesn’t really take any time at all to get a Django application setup if you have the architecture of the app already in mind.
- Scalable: Django can meet the traffic demands of a large project.
- Fully loaded: there are all sorts of packages that you can use to carry out standard web application tasks like authentication or content administration or querying. It’s all pre-baked in.
- Versatile: Django is fairly versatile. You can use it for all sorts of applications. The sky is the limit really on what you can do with it.
- Secure: common security risks are averted with Django’s built-in security protocols for cross-site request forgeries, cross-site scripting, clickjacking, and SQL injection.
- SEO optimized: Django makes SEO easier by maintaining a website through URLs rather than IP addresses.
- Documentation: Django's documentation is one of the best on the market. It's easy to read, even for people with no technical background.
With Django’s versatility, it’s certainly capable of meeting your project’s needs. Companies like Spotify, Pinterest, National Geographic, and Dropbox use Django for their business models. Let’s take a look next at the common design patterns that these companies have used so you can get a feel for the shape of a typical project.
There are three major components to Django’s architecture: elements that aid in working with the database, a template system that works for people who don’t program, and a framework that automates a lot of the website management. This lends itself to a Model, View, Template design pattern:
- Model: defines the structure of the database
- View: defines the logic that returns something from an HTTP request.
- Template: defines the structure of how a web page will look with plaintext information that can be read by someone who doesn’t necessarily program
These constituent parts are put in their own distinct files named for their purpose in Django web applications. In addition, you might have a URL mapper that deals with routing to a specific view for different endpoints.
So far we have taken a look at an introduction to Django. So, how does it really differ from another popular Python solution, Flask?
Flask is a microframework, meaning it is simple but extensible. Flask is based on the concept of doing one thing and doing it well. Flask does not need any tools or extra libraries. It also does not possess any database abstraction layer.
Django, on the other hand, is a batteries included framework that provides many things out of the box. It offers less control than Flask, with the inclusion of an admin panel, an ORM (Object Relational Mapping). Django has the goal of simplifying website creation.
So, which is better? There isn't really a solution that is better or worse. It comes down to your requirements. They are both great in their own market and domains. At a high-level, Django provides the advantage of being a full stack framework. Generally, teams prefer Django over Flask for its variety.
In Django, we can make projects and applications. In most instances, the terms can be interchangeable, but in Django they are not. Projects can contain several smaller applications that serve a particular function or purpose. In a library project, we can have a registration application, a login application, a catalog application, etc..
The root directory will look something like the code below when we create a run the application’s migrations. Later, we’ll go over how to actually install and run Django on your device.
¬project_1/ ¬project_1/ __init__.py asgi.py settings.py urls.py wsgi.py ¬application_1 ¬migrations __init__.py __init__.py admin.py apps.py models.py tests.py views.py manage.py
project_1 folder contains all the pertinent files for your project.
__init__.py: Empty file that signifies it’s a Python package.
asgi.py: Asynchronous Server Gateway Interface.
settings.py: contains all of the core information needed for your project to actually work, such as database connection, api keys, static files, and more.
urls.py: Project Level url mapper. Maps to specific views or to another application level url mapper.
wsgi.py: Web Server Gateway Interface.
application_1 folder contains all the pertinent files for your application.
- `migrations: Migrations from db are stored here
__init__.py: Empty file that signifies this is a Python app
admin.py: register models here
apps.py: app config
models.py: create models here
tests.py: create tests here
views.py: create views here
When we run our server, the server configures Django’s default configuration with your add-ons that are setup in
ROOT_URLCONF points to the URL mapper in your project folder. The URL mapper then points to views, which contain logic to return a response to some sort of HTTP request.
models file is where we create the schema for our table. We use SQL-like syntax to make constraints on the data that gets passed. We register the models in the admin file so that we can run migrations on the project after registration.
When learning how Django works, it’s easiest from the top down, starting at
settings.py. From there, you can navigate through the project by going to the project’s URL mapper.
It’s best want to understand how the structure works is by creating a project, so let’s do it!
So, now we understand the basics of
Hello World in Django. Let's take this a step further and build our first proper Django project from scratch.
- Make sure to have Python 3 installed
- Create a virtual environment by navigating to the folder you want to create it in and entering:
py -m venv project-name
- Start the virtual environment:
- Install Django:
py -m pip install Django
- Verify installation with
- Make sure to have Python 3 installed. Anytime you use python in the command line, you’ll use
- Install pip:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
- Install virtualenv:
python3 -m pip install virtualenv
- Navigate to the place where you would like to create your virtual environment
- Create virtualenv:
cdto get into
- Activate virtualenv:
- Install Django:
python3 -m pip install Django
Django project is a collection of applications and configurations. The following command will create a Django project in the
django-admin startproject first_project
- In your virtual environment command line, run
django-admin startproject first_project. This creates the workspace that will encapsulate all of your applications and your config files.
- Run (Mac)
python3 manage.py runserveror (Windows)
py manage.py runserverand open up
localhost:8000to see if you get a site with an animated rocket that tells you your install worked!
Note: You might get an error in your terminal saying you need to run migrations. Don’t worry about that at this point since we are not working with a database.
As mentioned in previous sections, projects and applications are very different in Django. An application serves one basic purpose or function. In this sample application, we’ll create a basic
Hello World application for our
- In your virtual environment, run (Mac)
python3 manage.py startapp first_appor (Windows)
py manage.py startapp first_app
- Configure application in project. Look for the
INSTALLED_APPSvariable in the
settings.pyfile of the
first_projectfolder. After the final application in the list, add the name of our application as a string.
HttpResponsepackage from the HTTP Django module to create a view:
from django.http import HttpResponse
Create a view function:
def index(request): return HttpResponse(“Hello World!”)
Use Project URL Mapper to route to application view. Navigate to
first_project/urls.py. Import from
first_app import viewsat the top of the file. In the
urlpatternslist, add the following:
Execute Project: Run (Mac)
python3 manage.py runserveror (Windows)
py manage.py runserverand open up port 8000 to see the result of our example!
We’ve just scratched the surface of what Django can do. Learning the Django templates is a great next step for mastering intermediate Django. But there is still a lot to learn!
Continue your journey by learning how to:
- Create models and forms
- Create a REST API
- Serve static files
- and much more
All of these concepts and more and covered in Educative’s course Django: Python Web Development Unleashed. You'll learn beginning and intermediate concepts alongside tons of real-world projects. At the end of the course, you will have created a few Django projects and solved Django challenges that can be used in your portfolio.