Getting Started with Django
Before diving into Django development, we need to set up our environment and understand how to create and configure a Django project. This process resembles preparing a workspace before starting a complex engineering project – we need the right tools, proper organization, and a clear understanding of the structure.
By the end of this lecture, you'll know how to:
- Set up a Python virtual environment for Django development
- Install Django and its dependencies
- Create a new Django project
- Understand the project structure
- Configure key project settings
- Run and test your Django development server
Prerequisites
Before we begin, ensure you have the following installed on your system:
-
Python 3.8+: Django requires Python 3, with version 3.8 or higher recommended.
- Check your version:
python --versionorpython3 --version
- Check your version:
-
pip: The Python package installer, which comes bundled with Python 3.4+.
- Check if it's installed:
pip --versionorpip3 --version
- Check if it's installed:
- Text editor or IDE: Tools like VS Code, PyCharm, Sublime Text, or Atom.
- Command-line interface: Terminal (macOS/Linux) or Command Prompt/PowerShell (Windows).
Having these tools ready is like gathering ingredients before cooking – it ensures a smooth process without interruptions.
Setting Up a Virtual Environment
A virtual environment is an isolated Python environment where you can install packages without affecting your system-wide Python installation. This is considered a best practice for Python development.
Think of a virtual environment like a separate workshop for each project. You won't accidentally use tools from one project in another, and you can have different versions of the same tool for different projects without conflicts.
Creating a Virtual Environment
Here's how to create and activate a virtual environment:
# Windows
# Create
python -m venv myenv
# Activate
myenv\Scripts\activate
# macOS/Linux
# Create
python3 -m venv myenv
# Activate
source myenv/bin/activate
When activated, you'll notice your command prompt changes to indicate the active environment. All Python packages you install will now go into this isolated environment.
Deactivating the Environment
When you're done working on your project, you can deactivate the virtual environment:
# All platforms
deactivate
Installing Django
With your virtual environment activated, you can now install Django:
# Install the latest version
pip install django
# Or install a specific version
pip install django==4.2.3
Verify the installation by checking the Django version:
python -m django --version
Installing Django is like acquiring a specialized toolbox for web development. Each version of Django comes with its own set of features, improvements, and sometimes changes in behavior, so it's important to know which version you're working with.
Creating a Django Project
Now that Django is installed, you can create a new project using Django's command-line utility:
django-admin startproject myproject
This command creates a new directory named myproject with the initial project structure. If you want to create the project in the current directory without creating a new parent directory, you can use:
django-admin startproject myproject .
Creating a Django project is like laying the foundation for a building. The startproject command sets up the basic structure and essential files that every Django project needs.
Project Structure
Let's examine the structure of a newly created Django project:
myproject/
├── manage.py
└── myproject/
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
- manage.py: A command-line utility that lets you interact with your Django project
-
myproject/ (inner directory): The actual Python package for your project
- __init__.py: An empty file that tells Python this directory should be considered a package
- asgi.py: An entry-point for ASGI-compatible web servers
- settings.py: Configuration settings for your project
- urls.py: URL declarations for the project
- wsgi.py: An entry-point for WSGI-compatible web servers
This structure is like the blueprint of a building, with each file serving a specific purpose in the overall architecture.
Understanding the Django Project Files
Let's take a closer look at each of the key files in a Django project:
manage.py
This is a command-line utility that allows you to interact with your Django project in various ways. It's a thin wrapper around the django-admin command-line utility.
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
Think of manage.py as the main control panel for your project. You'll use it to run the development server, create database tables, create new apps, and more.
settings.py
This file contains all the configuration of your Django installation. It's where you register any applications you create, configure your database, set your time zone, and more.
# Some key settings (not the complete file)
SECRET_KEY = 'your-secret-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
The settings.py file is like the control center of a spacecraft – it contains all the dials, switches, and settings that determine how your Django project behaves.
urls.py
This file is a table of contents for your Django-powered site. It tells Django which view to execute for a given URL pattern.
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
Think of urls.py as a receptionist for your web application. When a request comes in, the receptionist (URLs) directs it to the right department (view) based on the requested URL.
wsgi.py and asgi.py
These files are entry points for WSGI and ASGI-compatible web servers to serve your project. WSGI is the traditional Python standard for web servers and applications, while ASGI is a newer standard that supports asynchronous code.
You won't typically interact with these files directly unless you're deploying your project to a production environment.
These files are like the adapters that connect your Django project to the outside world – they ensure that web servers can communicate with your Django application.
Configuring Your Django Project
The settings.py file contains various settings that you can customize for your project. Let's look at some key settings you might want to configure:
Database Configuration
By default, Django uses SQLite as the database, which is fine for development but not suitable for production. You can configure Django to use other databases like PostgreSQL, MySQL, or Oracle:
# PostgreSQL configuration example
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_database_name',
'USER': 'your_database_user',
'PASSWORD': 'your_database_password',
'HOST': 'localhost',
'PORT': '5432',
}
}
Installed Apps
The INSTALLED_APPS setting includes a list of all Django applications that are activated in this project. By default, it includes the following built-in apps:
django.contrib.admin: The admin sitedjango.contrib.auth: Authentication systemdjango.contrib.contenttypes: A framework for content typesdjango.contrib.sessions: A session frameworkdjango.contrib.messages: A messaging frameworkdjango.contrib.staticfiles: A framework for managing static files
As you create your own applications, you'll add them to this list.
Templates and Static Files
You can configure how Django finds and loads templates and static files:
# Templates configuration
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'], # Look for templates in a project-level templates directory
'APP_DIRS': True, # Look for templates in app-level templates directories
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# Static files configuration
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static'] # Look for static files in a project-level static directory
Time Zone and Language
You can set the time zone and language for your project:
TIME_ZONE = 'America/New_York'
LANGUAGE_CODE = 'en-us'
Security Settings
Django provides various security settings, such as the secret key and debug mode:
# In development
SECRET_KEY = 'your-secret-key'
DEBUG = True
ALLOWED_HOSTS = []
# In production
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = ['your-domain.com', 'www.your-domain.com']
Important: Never keep DEBUG = True in a production environment, and never expose your SECRET_KEY in version control or public repositories.
Configuring your Django project is like customizing a new car – you adjust the settings to match your preferences, requirements, and the conditions you'll be driving in (development vs. production).
Running the Development Server
Django comes with a built-in development server that makes it easy to test your project during development. To start the server, navigate to your project directory (where manage.py is located) and run:
python manage.py runserver
By default, the server runs on port 8000. You can specify a different port if needed:
python manage.py runserver 8080
Once the server is running, you can access your project at http://127.0.0.1:8000/ (or the port you specified). You should see the Django welcome page:
The development server automatically reloads when you make changes to your code, so you don't need to restart it manually in most cases.
Note: The development server is not suitable for production use. It's designed for development purposes only and doesn't have the performance or security features needed for a production environment.
Running the development server is like test-driving your car in a controlled environment before taking it on the road. It gives you a chance to see how your project behaves and make adjustments as needed.
Creating a Superuser
Django's admin site is one of its most powerful features. To access it, you need to create a superuser account:
python manage.py createsuperuser
You'll be prompted to enter a username, email address, and password. Once the superuser is created, you can access the admin site at http://127.0.0.1:8000/admin/ and log in with your credentials.
However, before you can log in, you need to create the database tables required by the built-in Django apps. Run the following command:
python manage.py migrate
This command applies all the available migrations, creating the necessary database tables.
Creating a superuser is like getting the master key to your application. It gives you full access to the admin interface, where you can manage your data, users, and more.
Project Management Commands
Django's manage.py script provides various commands for managing your project. Here are some of the most commonly used ones:
-
python manage.py runserver: Starts the development server -
python manage.py migrate: Applies database migrations -
python manage.py makemigrations: Creates new migrations based on changes to your models -
python manage.py createsuperuser: Creates a superuser for the admin site -
python manage.py shell: Opens a Python shell with the Django environment loaded -
python manage.py startapp: Creates a new Django application within the project -
python manage.py collectstatic: Collects static files into a single directory -
python manage.py test: Runs tests
These commands are like the various tools in your toolbox – each one helps you perform a specific task in your Django project.
Django Apps vs. Projects
In Django, there's a distinction between "projects" and "apps":
- Project: A collection of configurations and apps for a particular website. A project can contain multiple apps.
- App: A web application that does something – e.g., a blog system, a database of public records, or a simple poll app.
This relationship is illustrated below:
Think of a Django project as a television network, and apps as individual TV shows. The network (project) provides the infrastructure and platform, while each show (app) has its own content, characters, and purpose, but they all air on the same network.
Creating a Django App
To create a new app within your project:
python manage.py startapp myapp
This creates a new directory with the following structure:
myapp/
├── __init__.py
├── admin.py
├── apps.py
├── migrations/
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
To use this app in your project, you need to add it to the INSTALLED_APPS list in your settings.py file:
INSTALLED_APPS = [
# Django built-in apps
'django.contrib.admin',
'django.contrib.auth',
# ...
# Your apps
'myapp',
]
Creating a Django app is like starting a new department within a company. The app has its own structure, responsibilities, and resources, but it operates within the larger framework of the project.
Best Practices for Project Setup
Here are some best practices to follow when setting up a Django project:
- Use virtual environments: Always use a virtual environment to isolate your project dependencies.
-
Version control: Initialize a Git repository for your project and create a
.gitignorefile to exclude unnecessary files. - Environment variables: Use environment variables for sensitive information like database credentials and the secret key.
-
Requirements file: Keep track of your project dependencies in a
requirements.txtfile:pip freeze > requirements.txt - Modular design: Break your project into smaller, focused apps instead of creating one monolithic app.
- Consistent naming: Use consistent naming conventions for files, classes, and functions.
- Documentation: Document your project, including setup instructions, app purpose, and API documentation.
Following these best practices is like building a house on a solid foundation – it might take a bit more time upfront, but it pays off in the long run with a more stable, maintainable project.
Practice Activity: Django Project Setup
Let's put what we've learned into practice by setting up a Django project from scratch:
Activity 1: Basic Project Setup
- Create a new virtual environment for your project
- Install Django
- Create a new Django project called "blogsite"
- Create a new app called "blog"
- Add the "blog" app to the INSTALLED_APPS setting
- Run the development server and verify that everything is working
Activity 2: Customize Project Settings
- Change the time zone and language settings to match your locale
- Configure the templates and static files settings
- Create a .gitignore file for your project
- Generate a requirements.txt file
Activity 3: Database and Admin Setup
- Run the migrate command to set up the database
- Create a superuser account
- Run the development server and log in to the admin site
- Explore the admin interface to understand what's available by default
Common Issues and Solutions
During Django project setup, you might encounter some common issues. Here are solutions to these problems:
Port Already in Use
If you see an error like "port is already in use," another process is using the port you're trying to run the development server on. You can either:
- Find and terminate the process using that port
- Use a different port:
python manage.py runserver 8001
Database Migrations
If you see warnings about unapplied migrations when running the server, you need to run:
python manage.py migrate
Import Errors
If you see import errors, ensure that:
- Your virtual environment is activated
- You've installed all the required packages
- Your Python path is set correctly
Settings Module Not Found
If Django can't find your settings module, ensure that:
- You're running commands from the correct directory (where
manage.pyis located) - Your
DJANGO_SETTINGS_MODULEenvironment variable is set correctly (if you're not usingmanage.py)
Summary
In this lecture, we've covered the essential steps and concepts for setting up a Django project:
- Creating and using Python virtual environments
- Installing Django
- Creating a new Django project and understanding its structure
- Configuring key project settings
- Running the development server
- Creating a superuser for the admin site
- Managing the project with management commands
- Understanding the difference between projects and apps
- Following best practices for project setup
Setting up a Django project is like preparing the foundation and framework of a building. It might not be the most exciting part of the process, but it's crucial for the stability and success of your web application.
In the next lecture, we'll dive deeper into Django applications and explore how to create and structure them for your project.