Django is a Python framework for building websites and APIs. This Django tutorial builds one small app that stores courses in a database and shows them in the browser. You then add an admin page, a form and a simple API.
You need basic Python: functions, classes, lists and imports. If those are new, start with the Python basics tutorial. You should also know simple tags from the HTML tutorial.
Django tutorial setup in Python
Check that Python works, then make a folder and a virtual environment. A virtual environment keeps this project's packages separate.
python --version
mkdir course-site
cd course-site
python -m venv .venv
Activate it on Windows PowerShell:
.\.venv\Scripts\Activate.ps1
On macOS or Linux, use:
source .venv/bin/activate
Now install Django and create a project:
python -m pip install django
django-admin startproject config .
python manage.py migrate
python manage.py runserver
Keep the dot after config. It puts the project in the current folder. Open http://127.0.0.1:8000/ and you should see Django's welcome page. Press Ctrl+C to stop the server.
Use a Django version that supports your Python version. The official Django documentation lists the supported pairs.
Project, app and request flow
A project is the whole website and its settings. An app is one part of it, such as courses or users. Create an app:
python manage.py startapp courses
In config/settings.py, add "courses" to the existing list:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"courses",
]
These are the files you will use:
| File | Its job |
|---|---|
models.py |
Describes the data |
views.py |
Handles a request and makes a response |
urls.py |
Connects a web address to a view |
templates/ |
Holds the HTML pages |
admin.py |
Controls the admin site |
When a visitor opens a page, Django checks the URLs, calls the matching view, gets data through a model and puts it into a template. This pattern is called MVT: model, view, template.
Interview note: Django's view holds request logic. Its template controls display. In MVC terms, the Django view is closer to a controller, and the template is closer to the view.
Create a model and database table
Put this in courses/models.py:
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=100)
weeks = models.PositiveIntegerField()
is_open = models.BooleanField(default=True)
def __str__(self):
return self.name
Each field becomes a database column. Django also adds an id column. __str__ controls how a course is shown in the admin and shell.
Make a migration, then apply it:
python manage.py makemigrations courses
python manage.py migrate
makemigrations writes instructions for the database change. migrate carries them out. Run both when you change a model. SQLite is the default database, so you do not need a separate server to learn.
Try the model in the shell with python manage.py shell:
from courses.models import Course
Course.objects.create(name="Python", weeks=8)
Course.objects.create(name="SQL", weeks=4)
Course.objects.filter(weeks__gt=5)
The last line returns a query result containing Python. weeks__gt=5 means weeks greater than 5. Django turns it into SQL and runs the query when the result is needed.
Common mistake: If you see "no such table", you probably forgot
makemigrations,migrate, or the app name inINSTALLED_APPS.
Show data with a view, URL and template
Put this in courses/views.py:
from django.shortcuts import render
from .models import Course
def course_list(request):
courses = Course.objects.order_by("name")
return render(request, "courses/list.html", {"courses": courses})
Create courses/urls.py:
from django.urls import path
from . import views
app_name = "courses"
urlpatterns = [
path("", views.course_list, name="list"),
]
Change config/urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("courses/", include("courses.urls")),
]
Create courses/templates/courses/list.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Courses</title>
</head>
<body>
<h1>Courses</h1>
<ul>
{% for course in courses %}
<li>{{ course.name }}: {{ course.weeks }} weeks</li>
{% empty %}
<li>No courses yet.</li>
{% endfor %}
</ul>
</body>
</html>
Start the server and visit http://127.0.0.1:8000/courses/. Python and SQL should appear in name order. {% %} holds template instructions and {{ }} prints values. Django escapes printed values by default, which helps stop unsafe HTML from running.
Use the admin and add a form
Register the model in courses/admin.py:
from django.contrib import admin
from .models import Course
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
list_display = ("name", "weeks", "is_open")
search_fields = ("name",)
Create an admin user with python manage.py createsuperuser. Start the server and open /admin/. You can now add, search, edit and delete courses.
You can also build your own form page. Create courses/forms.py:
from django import forms
from .models import Course
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ["name", "weeks", "is_open"]
Replace courses/views.py with the complete version:
from django.contrib.admin.views.decorators import (
staff_member_required,
)
from django.shortcuts import redirect, render
from .forms import CourseForm
from .models import Course
def course_list(request):
courses = Course.objects.order_by("name")
return render(request, "courses/list.html", {"courses": courses})
@staff_member_required
def add_course(request):
form = CourseForm(request.POST or None)
if request.method == "POST" and form.is_valid():
form.save()
return redirect("courses:list")
return render(request, "courses/form.html", {"form": form})
Add path("add/", views.add_course, name="add") to the list in courses/urls.py. Then make courses/templates/courses/form.html:
<h1>Add a course</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
Open /courses/add/ while signed in as your admin user. A valid form saves the course and returns to the list. A bad value shows an error beside its field. The staff_member_required line keeps ordinary visitors out.
csrf_token protects the form from a fake request made by another site. Do not remove it to silence a 403 error.
Learn Django REST Framework basics
An HTML page is made for people. A JSON API is made for other programs, such as a React app. Django REST Framework, or DRF, helps you build one. Learn Django REST Framework after models, views and URLs make sense.
python -m pip install djangorestframework
Add "rest_framework" to INSTALLED_APPS. Create courses/serializers.py:
from rest_framework import serializers
from .models import Course
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = ["id", "name", "weeks", "is_open"]
A serializer turns a course into data that can become JSON. It can also check incoming data. Create courses/api.py:
from rest_framework import viewsets
from .models import Course
from .serializers import CourseSerializer
class CourseViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Course.objects.order_by("name")
serializer_class = CourseSerializer
Replace config/urls.py with:
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from courses.api import CourseViewSet
router = DefaultRouter()
router.register("courses", CourseViewSet, basename="course-api")
urlpatterns = [
path("admin/", admin.site.urls),
path("courses/", include("courses.urls")),
path("api/", include(router.urls)),
]
Visit /api/courses/ to see the courses. This API is read-only on purpose. Before you allow changes, add login and permission rules. Our guide to REST APIs explains methods and status codes.
Pro tip: Do not set DRF access to open just to make a POST request work. Decide who may create data, then write that permission.
Learn Django from scratch: your next steps
This Django tutorial for beginners covers the main path. Extend the same site in this order:
- Add a detail page for one course.
- Add edit and delete pages with permission checks.
- Add a teacher model linked by a foreign key.
- Add login for students.
- Write tests for the list and form.
- Move to PostgreSQL and deploy the site.
Before release, set DEBUG = False, keep the secret key out of Git, set ALLOWED_HOSTS and run python manage.py check --deploy. The development server is not meant for public use.
To learn Django from scratch, rebuild the app once without this page. Any Django tutorial in Python is easier when you can say which file does which job. If you want to learn Django for interviews, use the Django interview questions. Then plan the remaining skills with the Python full stack course outline.

