Learn / Frameworks / Django / Introduction and Setup

Beginner 12 min

Introduction and Setup

What Django gives you, and how to create a project and run the server.

What you will learn

  • Create a Django project
  • Explain project vs app
  • Run the dev server

Django is a high-level Python web framework that follows a "batteries included" philosophy. Out of the box you get an ORM (talk to a database with Python objects), URL routing, templates, form handling, authentication, an automatic admin interface and strong security defaults. It powers sites such as Instagram and Pinterest.

The MTV pattern

  • Model: your data, defined as Python classes that map to database tables.
  • Template: the HTML, with placeholders for data.
  • View: a function that receives a request, gets data and returns a response.

A URL configuration connects incoming paths to views. This is Django's flavor of MVC.

python3 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install django

django-admin startproject mysite
cd mysite
python manage.py runserver

Visit http://127.0.0.1:8000/ to see the welcome page. A virtual environment keeps this project's packages separate from the rest of your system.

Project versus app

A project is the whole site (settings and root URLs). An app is one feature, such as blog or accounts. Apps are meant to be reusable and self-contained.

python manage.py startapp blog

Then register the app by adding "blog" to INSTALLED_APPS in mysite/settings.py.

What is in the folder

  • manage.py: command-line helper (run the server, migrations, tests).
  • mysite/settings.py: configuration, including database and installed apps.
  • mysite/urls.py: the root URL table.
  • blog/models.py, views.py, admin.py: the app's code.
Security

Never commit SECRET_KEY or run with DEBUG = True in production. Read them from environment variables.

Try it yourself

Create a project called library with an app called books, register the app, and confirm the dev server starts.

Show solution
django-admin startproject library
cd library
python manage.py startapp books
# add "books" to INSTALLED_APPS in library/settings.py
python manage.py runserver