Django is one of the most popular web frameworks written in Python. It enables developers to build secure, maintainable, and scalable web applications rapidly. Whether you are a beginner exploring web development or an experienced Python programmer wanting to move to full-stack development, Django offers a robust and elegant way to create web projects.
This comprehensive guide will walk you step by step through creating your first Django project—from installation to running your first web application.
1. Introduction to Django
Before jumping into project creation, it’s important to understand what Django is and why it’s widely used.
Django is a high-level Python web framework that follows the Model-View-Template (MVT) architectural pattern. It was designed to help developers take applications from concept to completion as quickly as possible while promoting clean, pragmatic design and reusable code.
1.1 Key Features of Django
- Rapid Development: Django automates many common web development tasks such as authentication, database operations, and URL routing.
- Security: It provides protection against common web vulnerabilities like SQL injection, XSS, and CSRF.
- Scalability: Django is used by large-scale companies such as Instagram and Pinterest because it can handle heavy traffic and large amounts of data.
- Versatility: Suitable for small projects and enterprise-level applications alike.
- Built-in Admin Panel: Django’s automatic admin interface allows you to manage your app’s data without extra coding.
- ORM (Object Relational Mapper): It enables you to interact with databases using Python code instead of SQL queries.
2. Prerequisites
Before starting, make sure you have the following installed and configured:
2.1 Python
Django is a Python framework, so Python must be installed on your system.
Check your Python version by running:
python --version
or
python3 --version
If Python is not installed, download it from the official website: https://www.python.org/downloads/
Django supports Python 3.8 and above (as of Django 5.0).
2.2 pip
pip is Python’s package manager. It usually comes with Python installation. You can check it with:
pip --version
If pip is missing, install it following the Python documentation.
2.3 Virtual Environment (venv)
Using a virtual environment is recommended for every Django project. It keeps project dependencies isolated and avoids version conflicts between multiple projects.
You can create one using:
python -m venv env
Activate it:
- On Windows:
env\Scripts\activate - On macOS/Linux:
source env/bin/activate
Once activated, you’ll see (env) in your terminal prompt, meaning you’re inside the virtual environment.
3. Installing Django
Once your environment is ready, the next step is installing Django.
Run the following command:
pip install django
This will download and install the latest version of Django from the Python Package Index (PyPI).
You can verify installation with:
django-admin --version
If the command returns a version number, Django is successfully installed.
4. Creating a New Django Project
Now that Django is installed, let’s create your first Django project.
4.1 The django-admin Tool
Django comes with a command-line utility called django-admin that helps you create and manage projects.
To create a new project, use:
django-admin startproject myproject
This will create a directory called myproject containing several files.
4.2 Project Structure
Open the myproject folder to explore its structure:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
Here’s what each file does:
- manage.py: Command-line utility for interacting with your project (running the server, creating apps, migrating the database, etc.).
- init.py: Indicates that this directory is a Python package.
- settings.py: Contains all configuration settings for your Django project (database, apps, middleware, etc.).
- urls.py: Defines URL patterns for routing requests.
- asgi.py/wsgi.py: Entry points for deploying the project with ASGI or WSGI servers.
5. Running the Development Server
To verify everything is set up correctly, navigate to your project folder and run:
python manage.py runserver
You’ll see output similar to:
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK or CTRL-C.
Now open your browser and go to http://127.0.0.1:8000/
You’ll see Django’s default welcome page:
“The install worked successfully! Congratulations!”
This confirms that Django is working properly.
6. Understanding the Django App Concept
A Django project can contain multiple apps, each responsible for a specific functionality. For example, in an e-commerce project, you might have separate apps for users, products, and orders.
Let’s create your first Django app.
7. Creating Your First App
Inside the project directory, run:
python manage.py startapp blog
This command creates a new folder named blog with the following structure:
blog/
admin.py
apps.py
models.py
tests.py
views.py
__init__.py
migrations/
7.1 Understanding the App Files
- models.py: Defines your database structure using Python classes.
- views.py: Contains functions or classes that handle requests and return responses.
- admin.py: Registers models for Django’s built-in admin interface.
- apps.py: Configures app metadata.
- tests.py: Used to write automated tests.
- migrations/: Stores files that track database schema changes.
8. Registering the App in Settings
For Django to recognize the new app, you must add it to the INSTALLED_APPS list in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # Add your app here
]
9. Creating Your First View
In blog/views.py, add the following code:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, world! Welcome to my first Django app.")
This is a simple view that returns a plain text response.
10. Setting Up URLs
To make the view accessible through the browser, you need to set up URL routing.
10.1 Create blog/urls.py
Inside the blog directory, create a new file named urls.py and add:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
10.2 Include App URLs in Project URLs
Open myproject/urls.py and modify it like this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
Now, when you navigate to http://127.0.0.1:8000/, you’ll see your message:
“Hello, world! Welcome to my first Django app.”
11. Working with Templates
Django uses templates to render HTML pages dynamically.
11.1 Create a Templates Folder
Inside your blog app, create a folder named templates, then another folder inside it named blog.
The structure should look like:
blog/
templates/
blog/
home.html
11.2 Create home.html
Inside home.html, add:
<!DOCTYPE html>
<html>
<head>
<title>My First Django App</title>
</head>
<body>
<h1>Welcome to My First Django Project!</h1>
<p>This is rendered using Django templates.</p>
</body>
</html>
11.3 Update the View
Modify your views.py to render the template:
from django.shortcuts import render
def home(request):
return render(request, 'blog/home.html')
Now refresh the browser, and you’ll see your HTML page rendered beautifully.
12. Setting Up the Database
Django uses SQLite by default, but you can configure other databases like PostgreSQL or MySQL in settings.py.
To initialize the database, run:
python manage.py migrate
This command applies all default migrations (for authentication, sessions, etc.).
13. Creating Models
Let’s create a simple blog post model.
In blog/models.py, write:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
This defines a model with three fields—title, content, and date_posted.
Now create and apply migrations:
python manage.py makemigrations
python manage.py migrate
14. Using the Django Admin Panel
14.1 Creating a Superuser
To access the admin dashboard, create a superuser:
python manage.py createsuperuser
Enter username, email, and password when prompted.
14.2 Registering the Model
In blog/admin.py, add:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Run the server again and go to:
http://127.0.0.1:8000/admin/
Log in using your superuser credentials.
You’ll see your Post model listed—allowing you to add, edit, and delete posts directly from the admin interface.
15. Displaying Posts on the Website
Modify your views.py to display posts from the database:
from django.shortcuts import render
from .models import Post
def home(request):
posts = Post.objects.all()
return render(request, 'blog/home.html', {'posts': posts})
Update your home.html to show them:
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Blog Posts</h1>
{% for post in posts %}
<div>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<small>Posted on {{ post.date_posted }}</small>
</div>
<hr>
{% empty %}
<p>No posts yet.</p>
{% endfor %}
</body>
</html>
Now, any posts you add from the admin panel will automatically appear on your homepage.
16. Understanding Static Files
Static files (CSS, JavaScript, images) are essential for styling your web pages.
16.1 Create Static Folder
Inside your app, create a folder named static/blog.
Example structure:
blog/
static/
blog/
style.css
16.2 Link Static Files in Templates
In home.html, link the CSS file:
{% load static %}
<link rel="stylesheet" href="{% static 'blog/style.css' %}">
And add some styles in style.css:
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
padding: 20px;
}
h1 {
color: #333;
}
div {
background: white;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
Now your page looks much better.
17. URL Namespacing
If you have multiple apps, Django allows you to namespace URLs to avoid conflicts.
In your blog/urls.py, add:
app_name = 'blog'
Now you can reference URLs using blog:home in templates or redirects.
18. Adding Another Page
Let’s add an “About” page.
In views.py:
def about(request):
return render(request, 'blog/about.html')
In urls.py:
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
]
Create about.html inside templates/blog:
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<h1>About This Blog</h1>
<p>This is my first Django project. It’s built to demonstrate basic Django concepts.</p>
</body>
</html>
Now visit http://127.0.0.1:8000/about/ to see your new page.
19. Django’s Project Lifecycle Overview
Every time a user makes a request, Django follows this process:
- The request enters through the WSGI/ASGI interface.
- Django’s URL dispatcher matches the requested URL to a view.
- The view processes data and interacts with the model if necessary.
- The template renders the final HTML page.
- The response is sent back to the user.
Understanding this cycle is key to mastering Django.
20. Debug Mode and Error Pages
When DEBUG = True in settings.py, Django displays detailed error pages.
Set DEBUG = False in production to hide sensitive information.
21. Deploying Your Django Project
Once development is done, you can deploy your project on cloud platforms like:
- PythonAnywhere
- Heroku
- AWS Elastic Beanstalk
- DigitalOcean
Deployment involves setting up a production database, static files, and a web server like Gunicorn or uWSGI with Nginx.
22. Common Django Commands
Here are some essential Django commands to remember:
| Command | Description |
|---|---|
django-admin startproject projectname | Creates a new project |
python manage.py startapp appname | Creates a new app |
python manage.py runserver | Runs the development server |
python manage.py makemigrations | Creates migration files |
python manage.py migrate | Applies migrations |
python manage.py createsuperuser | Creates an admin user |
python manage.py shell | Opens Django shell |
python manage.py collectstatic | Collects static files for production |
Leave a Reply