Learn Django Β· 1/13

Welcome to Django: Setup and First Steps πŸš€

6 min read

Welcome to the backend! If you are reading this, you are likely tired of static HTML files or frontend JavaScript frameworks that need a place to store data. You want to build systems, handle users, and manage databases.

You are in the right place. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.


1. The "Why" Before the "How": Why Choose Django?

Before we type a single line of code, we need to understand why we are using this tool.

Definition:
Django (pronounced JANG-goh) is a free and open-source web framework written in Python. It follows the "batteries-included" philosophy.

The Problem:
Imagine you want to build a social media site. You need:

  1. A way to handle user URLs (e.g., site.com/profile).
  2. A login/logout system (Authentication).
  3. A database to store posts.
  4. Security to stop hackers from stealing passwords.
  5. An admin panel to ban users who post spam.

Building this from scratch using raw Python is possible, but it is like building a car by mining the metal yourself. It takes months, and you will likely forget the seatbelts (security flaws).

The Solution:
Django provides all of these out of the box. The "batteries-included" philosophy means that authentication, database mapping (ORM), URL routing, and even a full Admin Interface come pre-installed.

Industry Reality Check:
Django is not a toy. It powers giants like Instagram, Pinterest, and Mozilla. It is designed to handle heavy traffic and complex data relationships. In the industry, we choose Django when we want to move fast (deadlines) and break nothing (security).

Fun Fact: Django was named after Django Reinhardt, a jazz guitarist. It’s built to handle rhythm and improvisation, but mostly, it just handles HTTP requests really well. 🎸


2. Setting up the Environment: Python, Pip, and Virtualenvs

In professional development, we never install packages globally on our computer if we can avoid it. We use Virtual Environments.

The Concept:
A Virtual Environment is an isolated directory that contains a specific Python version and a specific set of libraries for one specific project.

The Problem (Dependency Hell):
Imagine you are working on two projects:

  • Project A was built in 2020 and requires Django version 3.0.
  • Project B is brand new and requires Django version 5.0.

If you install Django globally on your computer, you can only have one version. Updating for Project B breaks Project A. This is called "Dependency Hell."

The Solution:
We create a "sandbox" for each project. Project A gets its own box with Django 3.0. Project B gets a separate box with Django 5.0. They never touch each other.

🧱 Hands-on: Setup

Open your terminal (Command Prompt, PowerShell, or Bash).

Step 1: Verify Python
Ensure you have Python installed.

bash
python --version
# On Mac/Linux, you might need to type: python3 --version

Step 2: Create a Project Directory
Keep your computer organized.

bash
mkdir my_first_django
cd my_first_django

Step 3: Create the Virtual Environment
We usually name the environment venv or .venv.

bash
# Windows
python -m venv venv

# Mac/Linux
python3 -m venv venv

Step 4: Activate the Environment (CRITICAL STEP)
You must "step inside" the sandbox.

bash
# Windows
venv\Scripts\activate

# Mac/Linux
source venv/bin/activate

Check: Your terminal prompt should now show (venv) at the start. If you don't see this, you are still in the global system!

Step 5: Install Django
Now that we are inside the box, let's install the engine.

bash
pip install django

3. Your First Django Project: django-admin startproject

Now that our tools are ready, we need to generate the boilerplate code.

The Concept:
Boilerplate code is the standard code required just to get the application running before you add any custom logic.

The Problem:
Setting up a server requires configuring settings, defining root URLs, and setting up gateway interfaces. Typing this manually every time is boring and error-prone.

The Solution:
Django provides a command-line tool django-admin to auto-generate the file structure for you.

πŸ› οΈ Industry Pro-Tip: The Dot .

Most tutorials tell you to run django-admin startproject mysite. This creates a folder inside a folder (mysite/mysite/settings.py). This double-nesting is annoying to navigate.

In the industry, we often run the command with a . (dot) at the end, which means "install the project in the current directory."

Execute this command:

bash
django-admin startproject core .

(Note the dot at the end!)

This tells Django: "Name the configuration folder core and put the manage.py file right here where I am standing."

Verify the Installation:
Run the development server to make sure it works.

bash
python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/.
You should see a rocket ship taking off. πŸš€
If you see this, congratulations! You have a web server running.

Note: To stop the server, press CTRL + C in your terminal.


4. Project Structure: Understanding the Django Blueprint

When you ran that command, Django created several files. Let's look at what they do.

The Scenario:
Imagine your Django project is a fancy Hotel.

manage.py (The Utility Belt)

This sits in your root folder.

  • Definition: A command-line utility that lets you interact with this Django project.
  • Role: This is the tool you use to start the server, create database tables, or create new users. You rarely edit this file; you just use it.

The core/ Directory (The Management Office)

This folder (named core in our previous step) contains the brain of your project.

1. settings.py (The Rulebook)

  • Definition: The main configuration file.
  • Role: This controls everything.
    • Which database are we using? (SQLite, Postgres).
    • What languages do we support?
    • Who is allowed to connect? (ALLOWED_HOSTS).
    • Where are the static files (CSS/Images)?
  • Analogy: This is the Hotel Manager deciding the rules: "No loud music after 10 PM" or "We only accept Visa cards."

2. urls.py (The Reception Desk)

  • Definition: The Table of Contents for your website.
  • Role: When a user visits yourwebsite.com/login, the request hits urls.py first. This file looks at the address ("login") and points the user to the correct piece of code.
  • Analogy: The Receptionist. A guest walks in and asks, "Where is the pool?" The receptionist looks at the directory and points: "Third floor, left side."

3. wsgi.py / asgi.py (The Power Lines)

  • Definition: Web Server Gateway Interface.
  • Role: These files allow your Python code to talk to the actual web server (like Nginx or Apache) when you deploy to the internet.
  • Practicality: You almost never touch these files until you are deploying to production (AWS, Heroku, DigitalOcean).

Summary Checklist

  1. Created a folder.
  2. Created and activated a Virtual Environment.
  3. Installed Django.
  4. Started a project using django-admin startproject core ..
  5. Ran the server with python manage.py runserver.

You now have a functional backend setup. In the next section, we will learn how to actually build functionality using "Apps".

πŸ“š References & Further Reading

Challenge

You've just learned how to initialize a new Django project. This challenge will test your memory of the key commands and the initial configuration files.

Your task is to simulate the creation and initial configuration of a new Django project directly within this editor.

Requirements:

  1. The project's main configuration directory should be named config.
  2. You are setting up the project in the current directory to avoid the extra nested project folder.
  3. In the code, write the correct terminal commands as comments where indicated.
  4. In the simulated settings.py section, configure the ALLOWED_HOSTS list to permit connections from 127.0.0.1.
  5. In the simulated urls.py section, import the necessary modules and set up the default URL pattern for the Django admin site.

Expected result

Your code should correctly represent the commands and initial configuration for a new Django project.

python
# Terminal commands
# 1. Write the command to create a new Django project with the configuration directory named 'config' in the current folder.
# django-admin startproject config .

# 2. Write the command to run the development server using the manage.py utility.
# python manage.py runserver


# --- config/settings.py ---
# This is a simplified representation of the settings.py file.
# For this challenge, configure the ALLOWED_HOSTS list.
ALLOWED_HOSTS = ['127.0.0.1']


# --- config/urls.py ---
# This is a simplified representation of the urls.py file.
# Import the necessary functions/modules from django.contrib and django.urls.
from django.contrib import admin
from django.urls import path

urlpatterns = [
    # Add the URL pattern for the Django admin site here.
    path('admin/', admin.site.urls),
]

Explanation:

  • django-admin startproject config .: This is the correct command. config becomes the name of the core configuration directory, and the . at the end places manage.py and the config directory in the current folder, which is standard practice.
  • python manage.py runserver: This is the universal command to start Django's built-in development web server.
  • ALLOWED_HOSTS = ['127.0.0.1']: This setting is a crucial security measure. For development, you must add '127.0.0.1' to allow your browser to connect to the server running on your local machine.
  • path('admin/', admin.site.urls): This line in urls.py is the default route included in any new Django project. It maps any URL starting with /admin/ to the views and functionalities of the powerful, built-in Django admin interface.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.