Python Django Full Tutorial For Beginners

By admin December 20, 2025 11 min read

Welcome to the Ultimate Python Django Full Tutorial for Beginners

Welcome to Halogenius Ideas! If you have been looking for a definitive guide to start your journey into web development with Python, you have arrived at the right place. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It was built by experienced developers to take care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel.

In this detailed, step-by-step tutorial, we are going to build a web application from scratch. We will cover every single line of code you need, explaining the “why” and “how” behind it. We will pay special attention to Python indentation, as it is the backbone of Python syntax.

This article serves as a detailed text companion to our comprehensive video guide. For a full, step-by-step visual walkthrough, please watch the full tutorial on YouTube.

Prerequisites

Before we start typing commands, let’s ensure you have the necessary tools. You do not need to be an expert, but having these basics will help you follow along smoothly:

  • Python Installed: You need Python installed on your computer. You can check this by typing python --version in your terminal.
  • Terminal/Command Prompt: You should be comfortable opening your terminal (Mac/Linux) or Command Prompt/PowerShell (Windows).
  • Code Editor: A good text editor is essential. We highly recommend VS Code due to its excellent Python support.
  • Basic Python Knowledge: You should understand variables, functions, and dictionaries.

Setting up Your Development Environment

Organization is critical in programming. We never want to just create files on our desktop. Let’s create a dedicated folder for this project. Open your terminal and run the following commands one by one:

# 1. Create a new directory named 'django_course'
mkdir django_course

# 2. Enter that directory
cd django_course

Installing a Virtual Environment

This is a step many beginners skip, but it is vital. A Virtual Environment is like a sandbox. It keeps the libraries for this specific project separate from other projects on your computer. This prevents “dependency conflicts” later on.

Run the following command to create the environment:

# For Windows Users
python -m venv venv

# For Mac and Linux Users
python3 -m venv venv

Creating it isn’t enough; you must “turn it on” or activate it:

# Windows Activation
venv\Scripts\activate

# Mac/Linux Activation
source venv/bin/activate

Crucial Check: You will know it worked if you see (venv) appear in parentheses at the very beginning of your command prompt line.

Installing Django

Now that we are inside our virtual environment, we can install Django safely. We use pip, which is the Python package manager.

pip install django

Once the installation bars finish loading, verify it was successful:

python -m django --version

Django File Organization

In Django, there is a distinction between a Project and an App.

  1. Project: The entire website configuration (e.g., The whole “Halogenius Ideas” site).
  2. App: A specific feature within the project (e.g., a blog, a user profile system).

Let’s create the main project. We will call it myproject. Note the dot . at the end of the command—this is important as it installs the project in your current folder rather than creating a new sub-folder.

django-admin startproject myproject .

Your folder structure now looks like this:

  • manage.py: The command center for your project. You will run this file often.
  • myproject/: A folder containing your settings and root configurations.

Creating a Django App

Now we need an “App” to actually write our logic. Let’s create an app called base.

python manage.py startapp base

IMPORTANT STEP: Just creating the app isn’t enough. We must tell the main Project that this App exists. Open the file myproject/settings.py. Scroll down until you find the list called INSTALLED_APPS and add 'base', to the list.

# myproject/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Add your new app here
    'base',
]

URL Configuration

When a user visits your website, Django needs to know which code to run. This is handled by URLs. Think of urls.py as the receptionist directing calls.

First, we need to point the main project’s URL file to our app. Open myproject/urls.py:

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include  # We must import 'include'

urlpatterns = [
    path('admin/', admin.site.urls),
    # This tells Django: "If the URL is empty, go check base.urls"
    path('', include('base.urls')),
]

Now, create a new file named urls.py inside your base folder (it does not exist yet). Add the following code:

# base/urls.py
from django.urls import path
from . import views

urlpatterns = [
    # We will create the 'home' view in the next step
    path('', views.home, name='home'),
]

Creating (Functional) Views

A View is a Python function. It takes a web request from the user and returns a web response (like HTML). This is where your logic lives.

Open base/views.py. Pay close attention to the indentation here (4 spaces).

# base/views.py
from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    # This function handles the logic for the home page
    return HttpResponse("Welcome to Halogenius Ideas Tutorial!")

Now, go to your terminal and run the server:

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/. You should see your text!

Dynamic URLs in Django

Websites aren’t static; they change based on data. For example, viewing a specific product. We handle this with dynamic URL parameters.

In base/urls.py, let’s add a new path that accepts an ID (primary key or pk):

# base/urls.py
urlpatterns = [
    path('', views.home, name='home'),
    # <str:pk> captures a value from the URL and passes it to the view
    path('room/<str:pk>/', views.room, name='room'),
]

Now update base/views.py to handle this new view:

# base/views.py

def room(request, pk):
    # We can access the 'pk' passed from the URL
    return HttpResponse(f"You are looking at Room ID: {pk}")

Django Templates

Returning simple strings is boring. We want to return full HTML pages. Django uses a folder specifically named templates to find these files.

  1. Inside your base folder, create a new folder named templates.
  2. Inside templates, create a file named home.html.
<!-- base/templates/home.html -->
<h1>Halogenius Home Page</h1>
<p>This is served via a Django Template!</p>

Now, let’s update our view to “render” this HTML file instead of a string:

# base/views.py
from django.shortcuts import render

def home(request):
    # render takes the request and the template name
    return render(request, 'home.html')

Template Inheritance

On a real website, the Navigation Bar and Footer remain the same on every page. We don’t want to copy-paste that code into every single HTML file. We use Inheritance.

Create a main.html file in your templates folder. This will be the “Parent” layout.

<!-- base/templates/main.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Halogenius App</title>
</head>
<body>

    <nav>
        <a href="/">Logo</a> | 
        <a href="/about">About</a>
    </nav>

    <hr>

    <!-- This block is a placeholder for child content -->
    {% block content %}
    {% endblock %}

</body>
</html>

Now, modify home.html to extend this parent:

<!-- base/templates/home.html -->
{% extends 'main.html' %}

{% block content %}
    <h1>Welcome Home</h1>
    <p>The nav bar above comes from the parent file!</p>
{% endblock %}

Passing Dynamic Data into Django Templates

To display Python data in HTML, we use a “Context Dictionary”.

# base/views.py
def home(request):
    # This data could come from a database or calculation
    my_data = {'username': 'JohnDoe', 'role': 'Admin'}

    # We pass the dictionary as the third argument
    return render(request, 'home.html', my_data)

In the HTML, we use double curly braces {{ }} to access the variables:

<h1>Hello, {{ username }}</h1>
<p>Your role is: {{ role }}</p>

Template Filters

Sometimes you want to format data inside the HTML (e.g., make it uppercase). We use Filters with the pipe | character.

<p>Username Uppercase: {{ username|upper }}</p>
<p>Length of name: {{ username|length }}</p>

Build a Simple Calculator

Let’s build a functional feature to understand how data flows. We will make a simple adder.

Step 1: The View Logic

# base/views.py

def calculator(request):
    result = 0

    # Check if the user sent data via POST method
    if request.method == 'POST':
        # Retrieve numbers from the form input names
        # We wrap in int() because inputs are strings by default
        try:
            num1 = int(request.POST.get('num1'))
            num2 = int(request.POST.get('num2'))
            result = num1 + num2
        except:
            result = "Invalid Input"

    return render(request, 'calculator.html', {'result': result})

Step 2: The Template (calculator.html)

<!-- base/templates/calculator.html -->
<h1>Simple Adder</h1>

<form method="POST">
    <!-- Security Token required by Django for POST forms -->
    {% csrf_token %}

    <input type="number" name="num1" placeholder="First Number">
    +
    <input type="number" name="num2" placeholder="Second Number">

    <button type="submit">Calculate</button>
</form>

<h2>Result: {{ result }}</h2>

Generating URLs in Django Templates

Avoid hardcoding URLs like <a href="/room/1">. If you change your URL pattern later, you have to fix every HTML file. Instead, use the {% url %} tag.

<!-- Use the 'name' we defined in urls.py -->
<a href="{% url 'home' %}">Go Home</a>

<!-- Passing an ID parameter -->
<a href="{% url 'room' pk=1 %}">Go to Room 1</a>

GET and POST Methods

Understanding HTTP verbs is crucial:

  • GET: Used to retrieve data. The parameters show up in the URL bar (e.g., google search).
  • POST: Used to send data (create/update). Data is hidden in the body.

In Django views, we check if request.method == 'POST': to determine if a form is being submitted.

Class-Based Views in Django

While we have used functions so far, Django also supports Classes for views. They are great for standard operations to reduce code.

from django.views.generic import TemplateView

class AboutPage(TemplateView):
    template_name = 'about.html'

You would hook this up in urls.py slightly differently:

path('about/', AboutPage.as_view(), name='about'),

Managing Static Files in Django

Static files are things that don’t change: CSS, Images, and JavaScript.

  1. Create a folder named static inside your base app.

To use this in your HTML, you must load the static tag:

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

Models

Models are the heart of Django. A Model is a Python class that represents a table in your database. Django handles the SQL for you.

Open base/models.py:

# base/models.py
from django.db import models

class TodoItem(models.Model):
    # This creates a text column with max 200 characters
    title = models.CharField(max_length=200)

    # This creates a large text area, which can be empty
    description = models.TextField(null=True, blank=True)

    # Automatically set the time when created
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        # This determines how the item looks in the Admin panel
        return self.title

After creating a model, you must run two commands to update the database:

# Create the migration file (the blueprint)
python manage.py makemigrations

# Apply the migration (build the table)
python manage.py migrate

CRUD: Create, Read, Update, Delete

Let’s interact with our database using the Django Shell. Run python manage.py shell in your terminal.

1. Create

from base.models import TodoItem

# Create and save in one step
item = TodoItem.objects.create(title="Buy Milk", description="2% Fat")

2. Read

# Get all items
items = TodoItem.objects.all()

# Get a specific item by ID
one_item = TodoItem.objects.get(id=1)

3. Update

item = TodoItem.objects.get(id=1)
item.title = "Buy Almond Milk" # Change value
item.save() # Commit change to database

4. Delete

item = TodoItem.objects.get(id=1)
item.delete()

Django Forms

Writing raw HTML forms is risky and tedious. Django Forms automate validation and HTML generation.

Create a new file base/forms.py:

# base/forms.py
from django.forms import ModelForm
from .models import TodoItem

class TodoForm(ModelForm):
    class Meta:
        model = TodoItem
        fields = '__all__' # Or a list like ['title', 'description']

Now use it in a view:

# base/views.py
from .forms import TodoForm
from django.shortcuts import redirect

def create_todo(request):
    form = TodoForm()

    if request.method == 'POST':
        # Populate form with data
        form = TodoForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
            
    return render(request, 'todo_form.html', {'form': form})

Advanced Django Models & Relationships

Data is rarely isolated. A user has posts; a post has comments. We link models using Foreign Keys.

from django.contrib.auth.models import User

class TodoItem(models.Model):
    # If the User is deleted, delete their items (CASCADE)
    host = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=200)

User Management

Django includes a robust authentication system out of the box. To manage users, we first need to create a “Superuser” (Admin).

python manage.py createsuperuser

Enter a username and password (the password won’t show as you type). Then, run the server and navigate to http://127.0.0.1:8000/admin/ to log in.

Login and Logout

To let regular users log in, we can use Django’s built-in views. In myproject/urls.py (or your app urls), add:

from django.contrib.auth.views import LoginView, LogoutView

urlpatterns = [
    # ... other paths ...
    path('login/', LoginView.as_view(template_name='login.html'), name='login'),
    path('logout/', LogoutView.as_view(next_page='login'), name='logout'),
]

You simply need to create a login.html template containing a form, and Django handles the session security, password hashing, and validation automatically.


This brings us to the end of our beginner’s guide. You have set up a project, built apps, created databases, and handled user input. This is the foundation of any scalable web application. For more advanced tips, keep visiting Halogenius Ideas.

Watch The Video

Watch on YouTube

How did this article make you feel?

Share This Post

About admin

Founder and Lead Developer at Halogenius Ideas, bridging the gap between professional web design and accessible tech education. With years of experience in full-stack development and a passion for teaching, I lead a team dedicated to building stunning digital experiences while empowering the next generation of developers through comprehensive tutorials and courses. When I'm not coding or creating content, you'll find me exploring new technologies and mentoring aspiring developers.

Leave a Reply

Your email address will not be published. Required fields are marked *

eighty + = eighty five
Powered by MathCaptcha