Skip to main content

Django First Project

Introduction

Creating your first Django project is an exciting step in your web development journey! Django is a powerful Python web framework that follows the "batteries-included" philosophy, providing almost everything developers need to build robust web applications out of the box.

In this tutorial, we'll walk through setting up a complete Django project from scratch. By the end, you'll have a basic working web application and understand the fundamental components of a Django project.

Prerequisites

Before we begin, make sure you have:

  • Python 3.8+ installed
  • Basic knowledge of Python
  • Familiarity with command-line operations
  • A text editor or IDE (like VS Code, PyCharm, etc.)

Step 1: Setting Up a Virtual Environment

It's a best practice to create a virtual environment for each Django project to keep dependencies isolated.

bash
# Create a new directory for your project
mkdir my_django_project
cd my_django_project

# Create a virtual environment
python -m venv venv

# Activate the virtual environment
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate

Your command prompt should now show the virtual environment name, indicating it's active:

(venv) C:\Users\username\my_django_project>  # Windows
(venv) username@computer:~/my_django_project$ # macOS/Linux

Step 2: Installing Django

With the virtual environment activated, install Django using pip:

bash
pip install django

Verify the installation:

bash
python -m django --version

Output:

4.2.7  # Your version might differ

Step 3: Creating a Django Project

Now, let's create our Django project:

bash
django-admin startproject mysite .

The dot (.) at the end is important! It tells Django to create the project in the current directory instead of creating a new directory.

This command creates a mysite directory and several files:

my_django_project/
├── manage.py
└── mysite/
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py

Step 4: Understanding the Project Structure

Let's examine the files Django created:

manage.py

This is a command-line utility that lets you interact with your Django project. You'll use it for running the development server, creating applications, and working with the database.

mysite/ (Project Package)

This inner directory is the actual Python package for your project:

  • __init__.py: An empty file that tells Python this directory should be considered a Python package.
  • settings.py: Contains all the configuration settings for your project.
  • urls.py: The URL declarations for your project; essentially your project's "table of contents."
  • asgi.py: An entry point for ASGI-compatible web servers to serve your project.
  • wsgi.py: An entry point for WSGI-compatible web servers to serve your project.

Step 5: Running the Development Server

Let's verify our project is working correctly:

bash
python manage.py runserver

You should see output similar to:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silences).

You have 18 unapplied migrations. Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

March 09, 2023 - 15:50:53
Django version 4.2.7, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Open your web browser and navigate to http://127.0.0.1:8000/. You should see Django's default success page:

Django Success Page

Note: Don't worry about the migration warnings for now. We'll address them in a later tutorial.

Step 6: Creating a Django App

In Django, a project (what we just created) is a collection of apps. An app is a web application that does something specific, like a blog, a poll system, or a wiki.

Let's create our first app:

bash
python manage.py startapp polls

This creates a polls directory with this structure:

polls/
├── __init__.py
├── admin.py
├── apps.py
├── migrations/
│ └── __init__.py
├── models.py
├── tests.py
└── views.py

Step 7: Creating a View

Now, let's create a simple view. Open polls/views.py and modify it:

python
from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

Step 8: Creating a URL Configuration for the App

Create a new file called urls.py in the polls directory:

python
from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
]

Step 9: Including the App URLs in the Project URLs

Open mysite/urls.py and modify it:

python
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]

Step 10: Registering the App

Open mysite/settings.py and add 'polls' to the INSTALLED_APPS list:

python
INSTALLED_APPS = [
'polls.apps.PollsConfig', # Add this line
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Step 11: Running the Server Again

Run the server again to see your changes:

bash
python manage.py runserver

Now, visit http://127.0.0.1:8000/polls/ in your browser. You should see the message:

Hello, world. You're at the polls index.

Real-World Application: A Simple Poll App

Let's extend our app to store and display poll questions.

Step 1: Define Models

Edit polls/models.py:

python
from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question_text

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self):
return self.choice_text

Step 2: Create and Apply Migrations

When you change your models, Django tracks these changes through migrations:

bash
python manage.py makemigrations polls

This creates migration files. You should see:

Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Question
- Create model Choice

Now, apply these migrations:

bash
python manage.py migrate

Step 3: Experiment with the API

Django includes a convenient Python shell:

bash
python manage.py shell

Inside the shell:

python
# Import our models
from polls.models import Choice, Question
from django.utils import timezone

# Create a new question
q = Question(question_text="What's your favorite programming language?", pub_date=timezone.now())
q.save()

# Access the ID
q.id # Output: 1

# Create choices for this question
q.choice_set.create(choice_text='Python', votes=0)
q.choice_set.create(choice_text='Java', votes=0)
q.choice_set.create(choice_text='JavaScript', votes=0)

# Count the choices
q.choice_set.count() # Output: 3

# Exit the shell
exit()

Step 4: Update the Views

Let's modify polls/views.py to display our questions:

python
from django.http import HttpResponse
from .models import Question

def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q in latest_question_list])
return HttpResponse(output)

def detail(request, question_id):
return HttpResponse(f"You're looking at question {question_id}.")

def results(request, question_id):
return HttpResponse(f"You're looking at the results of question {question_id}.")

def vote(request, question_id):
return HttpResponse(f"You're voting on question {question_id}.")

Step 5: Update the URLs

Update polls/urls.py:

python
from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]

Summary

Congratulations! You've created your first Django project and app. Here's what we've learned:

  1. How to set up a Django project environment
  2. Understanding Django's project structure
  3. Creating and configuring Django apps
  4. Writing views and mapping URLs
  5. Working with Django models and the database

This is just the beginning of what Django can do. In future tutorials, we'll explore more advanced features like templates, forms, authentication, and the Django admin interface.

Additional Resources

Exercises

  1. Modify the index view to show the publication date alongside each question.
  2. Create a new app within the same project (e.g., a blog app).
  3. Add a detail view that shows the choices for a specific question.
  4. Create a custom method on the Question model that returns whether the question was published in the last 24 hours.

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)