Getting Started with Django Tutorial

Will Vincent - Aug 29 - - Dev Community

This tutorial is designed for programmers new to the Django web framework, whether you are a beginner who wants to build web applications in Python for the first time or an experienced web developer looking for a complete overview of what Django offers.

In comparison to Flask, which adopts a microframework approach, Django is a "batteries-included" framework that includes by default most of what you need to build, test, and deploy powerful websites quickly. It has built-in solutions for user authentication (sign up, log in, log out), database connections and queries, logic, templates, security, and more. As the tagline says on the Django website, it is "The web framework for perfectionists with deadlines."

This tutorial focuses on Django itself. If you'd like to compare the two most popular Python web frameworks, please refer to the article on Flask vs Django.

What is Django?

Django is a web framework written in the Python programming language that takes care of the difficult and routine parts of web development--authentication, database connection, CRUD (Create, Read, Update, Delete) operations, URL routing, forms, security, etc.--so that developers can concentrate on what makes a website unique without needing to reinvent the wheel.

It was initially developed in the early 2000s at the Lawrence Journal-World newspaper in Lawrence, Kansas, and named after the famous jazz guitarist Django Reinhardt. First open-sourced in July 2005, Django grew rapidly thanks to an active community, regular updates, and widespread adoption that makes it one of the most popular web frameworks used by companies including Instagram, YouTube, Spotify, DropBox, Octopus Energy, and more.

Django is run as a non-profit by the Django Software Foundation and features regular local meetups, an online forum, and constant updates every month with a major new release every eight months. In short, Django is a mature and stable technology that is also actively maintained and improved.

Why Use The Django Web Framework?

Django's "batteries-included" approach offers a wide range of features right out of the box, including:

  • ORM (Object-Relational Mapper): write Python rather than SQL to create and query database information
  • Admin Interface: a visual way to interact with website content
  • URL Routing: clean, elegant URL schemas that are easy to maintain and reason about
  • Templating Engine: a simple syntax for adding variables and logic to create dynamic HTML
  • Forms: a powerful form library that handles rendering forms in HTML and validating user-submitted data
  • Authentication: a full-featured and secure authentication system for user accounts, groups, permissions, and cookie-based user sessions
  • Internationalization: multilingual support plus locale-specific formatting of dates, time, numbers, and time zones
  • Security: protection against SQL injection, cross-site scripting, cross-site request forgery, clickjacking, and remote code execution
  • Documentation: world-class documentation that is extensive and actively maintained by the community
  • Third Party Packages: thousands of supplemental packages available to provide further functionality (see DjangoPackages.org)
  • Regular releases: bugfixes every month and a major new release every eight months
  • Written in Python: an expressive language suitable for beginners and used in many areas of programming, including data science, AI/ML, scientific computing, web scraping, and more

But the best part of Django is the community, which is welcoming and supportive to developers of all backgrounds and experience levels. There are regular meetups in major cities, annual conferences, online communities, and a forum to help fellow developers.

What are the Prerequisites for Django?

The two major prerequisites are a basic understanding of the Python programming language and web development fundamentals. You should understand Python syntax, how to import and export modules, and be familiar with object-oriented concepts like classes and objects. The building blocks of web development also include knowledge of HTML, CSS, some JavaScript, and how databases/SQL work together.

You don't need to be an expert in Python or web development to start. The best way to learn is to have a project in mind and then learn as you go rather than trying to understand all these concepts abstractly without actually building something.

Django Architecture

Django follows a variant of the Model-View-Controller (MVC) architecture called the Model-View-Template (MVT) pattern that emphasizes separation of concerns:

  • Models are the data structure layer that represents the database schema
  • Views are the business logic layer that receives a web request and returns a web response
  • Templates are the presentation layer that displays information to the user

All websites follow a client/server model where HTTP requests are sent from the web browser, processed by the website, and an HTTP request is returned. In Django, that sequence looks as follows:

  1. A user makes an HTTP Request, for example.com
  2. A URLs processes it and assigns the correct View
  3. The View combines a Template and data from a Model/Database to create an HTTP Response
  4. The HTTP Response is returned to the user

Under-the-hood things are slightly more complicated than that, but the general flow remains the same.

An image of the request/response cycle is as follows:

Django Architecture

Django Project Structure

Django doesn't force you to build web applications in a particular way. Still, there is a default structure that applies to most websites: a single Project has multiple Apps, each containing discrete functionality.

Django Project
    -> App 1
    -> App 2
    -> App 3
    ...
    -> App X
Enter fullscreen mode Exit fullscreen mode

Django ships with several built-in apps such as admin, auth, sessions, messages, staticfiles, and more containing its "batteries." If you were to create a new Newspaper website with articles, you might make an articles app with that functionality. If you added payments later on, that would reside in a separate payments app. This structure helps developers reason about the code and means that even large Django codebases are relatively similar in structure.

Models

Django's ORM (Object-Relational Mapper) means developers can define data models in Python and query them via a dynamic API, but you can still write SQL if needed. For example, this model defines an Article table in a newspaper app that contains three fields: title, content, and pub_date.

# models.py
from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
Enter fullscreen mode Exit fullscreen mode

The title field is a character field (CharField) with a maximum length of 100 characters; the content field is a text field (TextField) that can store any amount of text; and the pub_date field is a date-time field (DateTimeField) that stores a timestamp of when the article was published.

Django provides support for many different field types as well as field options such as null, blank, primary_key, and unique.

Once you've created your data models, Django provides a database-abstraction API to create, retrieve, update, and delete objects.

URLs

A clean and elegant URL schema is essential for any high-quality web application. Django encourages beautiful URL design by creating a Python module called a URLconf. Similar to a table of contents for your app, it features precise mapping between URL patterns and your views.

# urls.py
from django.urls import path

from .views import HomePageView, ArticleListView, ArticleDetailView

urlpatterns = [
    path("", HomePageView.as_view(), name="homepage"),
    path("articles/", ArticleListView.as_view(), name="article-list"),
    path("articles/<int:pk>", ArticleDetailView.as_view(), name="article-detail"),
]
Enter fullscreen mode Exit fullscreen mode

In this example, three views are imported for a home page, an article list page, and an article detail page. Then, we define three paths that can define thousands or even millions of different webpages of articles.

Views

Views are the business logic layer that receives web requests and returns web responses. In Django, you can write your own function-based views, class-based views, or take advantage of class-based generic views to handle common use cases such as displaying a template, a list of items, or a detail view of a single item.

# views.py
from django.views.generic import TemplateView, ListView, DetailView
from .models import Article

class HomePageView(TemplateView):
    template_name = "home.html"

class ArticleListView(ListView):
    model = Article
    template_name = "article_list.html"

class ArticleDetailView(DetailView):
    model = Article
    template_name = "article_detail.html"
Enter fullscreen mode Exit fullscreen mode

This snippet is all the code we need to use built-in views to display a template called home.html, list all articles in a template called article_list.html, and display a detail view of a single article in article_detail.html.

Templates

Django's templating engine strikes a balance between power and ease. A template is a text file, typically HTML, that contains variables replaced with values when the template is evaluated and built-in tags and filters that control the logic of the template.

For example, a simple template file that displays all articles in the database would look as follows:

<!-- article_list.html -->
<h1>All Articles</h1>
{% for article in article_list %}
  <div>
    <h2>{{ article.title }} | {{ article.pub_date }}</h2>
    <p>{{ article.content }}</p>
  </div>
{% endfor %}
Enter fullscreen mode Exit fullscreen mode

And a template file to display a single article could look like this:

<!-- article_detail.html -->
<h1>{{ article.title }} {{ article.pub_date }}</h1>
<p>{{ article.content }}</p>
Enter fullscreen mode Exit fullscreen mode

It is possible to swap templating engines to use Jijna if you prefer and it is easy to sprinkle in HTMX as needed.

Projects

If you want to jump in and try Django for yourself, here are several free projects demonstrating how to build web applications with Django.

Courses

If you'd like to become proficient in Django, premium courses cover multiple projects in far richer depth and provide a progressive introduction to Django concepts.

Frequently Asked Questions (FAQs)

Is Django easy to learn?

If you have a basic understanding of Python and web development concepts, yes. Django is written in Python and comes with many batteries included to make it fast to start and deploy websites quickly. As with all web frameworks, you will need some understanding of HTML, CSS, JavaScript, and databases to maximize its features.

What are the differences between Flask and Django?

Flask and Django are Python-based web frameworks but adopt very different approaches. Flask is a lightweight and flexible micro-framework, whereas Django is "batteries-included" and provides an extensive feature set by default. Flask is ideal for projects requiring maximum flexibility, while Django shines for traditional websites that value structure, excellent documentation, and a vibrant ecosystem.

Is Django for the backend or frontend?

Django is primarily used for backend web development: connecting to a database, adding logic, user authentication, creating APIs, URL routing, etc. It has a lightweight templating language for frontend use, but Django can also function as a backend API coupled with a frontend JavaScript framework like React, Vue, or Angular.

What is Django vs. Python?

Python is a general-purpose computer programming language that emphasizes the readability of code, making it popular for both beginners and experienced programmers. It is used in data science, artificial intelligence, automation, and web development. Django is a web framework written in Python that handles common challenges in web development--connecting to a database, authentication, forms, security, URL routing, etc.--so developers don't have to reinvent the wheel.

Is Django a programming language?

No, Django is a web framework for creating applications or APIs written in the Python programming language. There are many common challenges in web development--connecting to a database, user authentication, URL routing, forms, security--and a framework like Django handles them all so a developer can focus on writing code specific to the project rather than reinventing the wheel.

Is Django full-stack or not?

Yes, Django provides all the backend and frontend web development tools, including database connections, URL routing, forms, and templates. It is generally considered a backend framework because developers can also swap in a dedicated JavaScript frontend library like Vue or React.

Should I learn Django before Python?

You should start with Python since Django is a Python-based web framework. Everything in Django is just Python. You don't need to master Python before attempting Django, but understanding basic syntax, variables, dictionaries, and object-oriented techniques like classes is recommended.

How do I ask a good programming question?

Many beginners need help moving past following a tutorial or course to building their own projects. Whatever functionality you can imagine has already been implemented by others. The trick is finding an example online or asking a good question on a place like the Django Forum. If you need help, try to be as specific as possible and make clear you have put in effort already. So, instead of saying, please help me build a blog!, you could say, I've already implemented authentication and models, but I'm stuck on a view displaying all posts, and here is the code I'm trying to use that I know is incorrect. A more experienced developer can quickly look at the code and make suggestions.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .