Home/Blog/Web Development/What is Django Python? Build your first program from scratch
Home/Blog/Web Development/What is Django Python? Build your first program from scratch

What is Django Python? Build your first program from scratch

Christina Kopecky
Jan 12, 2024
13 min read

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.

  • HTML/CSS
  • Python
  • How HTTP Requests work
  • How relational databases and how SQL works

In this article, we will look at:

Take your Python web dev skills to the next level

Cover
Django: Python Web Development Unleashed

Django is a free and open-source web application framework written in Python. It is used for rapid web development and clean, pragmatic design. It is built by experienced developers to make repetitive tasks easier, so you can focus on writing apps instead of reinventing the wheel. This course teaches Django for beginning and intermediate level learners. The course includes a hands-on learning experience with the help of interactive widgets. At the end of the course, you will have created a project in Django that can be used in your portfolio.

12hrs
Intermediate
44 Playgrounds
6 Quizzes

f

What is Django?#

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.


Benefits of Django#

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.


Understanding the Django Framework#

As highlighted earlier, Django — a high-level Python web framework, offers a robust, reliable, and efficient solution for building web applications and embraces a “batteries-included” concept by delivering many built-in and ready-to-use web development tools and components. This course will dive deep into the core components of the Django framework and explore its various features. It will specifically teach you the following:

  • Creating routes (or views): Views in the Django framework define what is displayed when a specific URL is requested.

  • Serving static content and files: You will learn how to configure and serve static files such as stylesheets, images, and JavaScript using Django’s built-in tools.

  • Connect templates with models to serve data dynamically: You will explore how to connect templates (the presentation layer) with models (the data layer) to display a web page.

  • Content views: This section will cover the process of defining models and their relationships by binding them with templates and views to create a fully functional web application.

  • Working with Databases using SQLite: In this part of the course, you will learn how to work with SQLite and perform common CRUD (create, read, update, and delete) database operations.

  • Handle and validate forms: Forms are essential to web applications by allowing users to input and submit data. This section will teach you how to create, handle, and validate forms using Django’s form system.

  • Create relative URLs with templates and explore template and custom filters: You will be guided on how to use relative URLs in your templates, which will result in versatile and easy to maintain applications.

  • User models, forms, and authentication: Not only will you learn how to create user models, registrations, and login forms, but you will also learn to implement them using Django’s built-in authentication system.

  • Building a Django application practically: Throughout the course, you will apply each section’s concepts and techniques to create a fully-functional Django application. This hands-on approach will reinforce your understanding of Django’s features and give you the practical experience to confidently develop your future web applications.


Learning Django Programming#

Diving into Django with Python programming will open a vast world of web development opportunities for you. Because Django is a high-level Python web framework that is popular for its swift development, clean design, and scalability, it will simplify complex tasks and allow you to focus on writing efficient code.

The keys to learning Django includes:

  • Understanding Python programming
  • Acquainting yourself with Django’s components (models, views, templates, and forms)
  • Working hands-on with real-world projects

Practical experience with small or big projects will help solidify your understanding of the framework.

Additionally, acquainting yourself with Django’s vast array of third-party packages, including the Django REST framework, Django-tenants, and Django-crispy-forms can streamline your development experience.

That being said, learning Django Python is an engaging and rewarding journey that will equip you with the skills needed to create dynamic and interactive web applications.

Django Design Pattern#

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.

Django vs. Flask#

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.


How does Django work?#

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

The inner 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.

The 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 settings.py. Your 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.

The 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!


Keep the learning going

Cover
Django: Python Web Development Unleashed

Django is a free and open-source web application framework written in Python. It is used for rapid web development and clean, pragmatic design. It is built by experienced developers to make repetitive tasks easier, so you can focus on writing apps instead of reinventing the wheel. This course teaches Django for beginning and intermediate level learners. The course includes a hands-on learning experience with the help of interactive widgets. At the end of the course, you will have created a project in Django that can be used in your portfolio.

12hrs
Intermediate
44 Playgrounds
6 Quizzes

Build your first Django program from scratch#

Let’s take this a step further and build our first proper Django project from scratch. We’ll learn the basics of Hello World in Django.


Step 1: Django Installation#

Windows

  1. Make sure to have Python 3 installed
  2. Create a virtual environment by navigating to the folder you want to create it in and entering: py -m venv project-name
  3. Start the virtual environment: run project-name\Scripts\activate.bat

You’ll now see “(project-name)” next to the command prompt to designate that you’re in your virtual environment.

  1. Install Django: py -m pip install Django
  2. Verify installation with django-admin --version

Mac:

  1. Make sure to have Python 3 installed. Anytime you use python in the command line, you’ll use python3 instead.
  2. Install pip:
    • Download: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
    • Run: python3 get-pip.py
  3. Install virtualenv: python3 -m pip install virtualenv
  4. Navigate to the place where you would like to create your virtual environment
  5. Create virtualenv: virtualenv <name_of_virtual_env>
  6. Use cd to get into virtualenv
  7. Activate virtualenv: source bin/activate
  8. Install Django: python3 -m pip install Django

Step 2: Initialize Project#

A Django project is a collection of applications and configurations. The following command will create a Django project in the first_project directory:

django-admin startproject first_project
  1. 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.
  2. cd into first_project.
  3. Run (Mac) python3 manage.py runserver or (Windows) py manage.py runserver and open up localhost:8000 to see if you get a site with an animated rocket that tells you your install worked!
Successful Django project
Successful Django project

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.


Step 3: Create Application#

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 first_project.

  1. In your virtual environment, run (Mac) python3 manage.py startapp first_app or (Windows) py manage.py startapp first_app
  2. Configure application in project. Look for the INSTALLED_APPS variable in the settings.py file of the first_project folder. After the final application in the list, add the name of our application as a string.
  3. Import the HttpResponse package from the HTTP Django module to create a view.
from django.http import HttpResponse
  1. Create a view function:
def index(request):
	return HttpResponse(“Hello World!”)
  1. Use Project URL Mapper to route to application view:
    • Navigate to first_project/urls.py
    • Import from first_app import views at the top of the file
    • In the urlpatterns list, add the following:
path('',views.index,name="index")		
  1. Execute Project: Run (Mac) python3 manage.py runserver or (Windows) py manage.py runserver and open up port 8000 to see the result of our example!

Congratulations! You’ve created your first basic program in Django! Next, let’s take a look at the Django Template Engine so we can take our formatting a little further.

widget

Intermediate Django: Template Engine#

The Django Template Engine allows us to create basic HTML templates for our data. This is a convenient way to generate HTML dynamically. We use template language for variables and basic logic that Django then uses to interpolate values inside HTML elements.

Templates help in understanding how Django interacts with our website. Think of this like the scaffolding or skeleton of your page.

The Django template language is designed for those who already use HTML. The language has tags, variables, filters, and comments. Below is a basic template that illustrates a few of these basic concepts.

{% extends "base_generic.html" %}
{% block title %}{{ page.title }}{% endblock %}
{% block content %}
<h1>{{ page.title }}</h1>
{% for blog in blog_list %}
<h2>
<a href="{{ blog.get_absolute_url }}">
{{ blog.header|upper }}
</a>
</h2>
<p>{{ blog.body|truncatewords:"100" }}</p>
{% endfor %}
{% endblock %}

What to learn next#

With this article, we have barely scratched the surface in regard to exploring the capabilities of the Django web framework!

Acquiring knowledge in Django templates is an excellent subsequent step to enhance your proficiency in intermediate Django software fundamentals. However, there is much more to discover!

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.

Happy learning!


Continue reading about web dev and Python#

Frequently Asked Questions

What is Django Python used for?

Django is a high-level python framework used for the following:

  • Rapid website development: Django streamlines the creation of complex web applications.
  • Secure and maintainable: It focuses on security and ease of maintenance.
  • Model-Template-View architecture: It simplifies database-driven website design.

  

Free Resources