Django is one of the most popular Python web frameworks, designed to help developers build secure, scalable, and maintainable web applications quickly. Known for its “batteries-included” approach, Django provides built-in features like authentication, database management (ORM), and an admin panel, reducing the need for third-party libraries.
Whether you’re building a simple blog, an e-commerce site, or a RESTful API, Django’s clean architecture and extensive documentation make it an excellent choice for beginners and professionals alike.
In this guide, we’ll cover:
- Setting up a Django development environment
- Creating your first Django project and app
- Understanding Django’s MVT (Model-View-Template) architecture
- Working with databases using Django’s ORM
- Rendering dynamic templates
- Deploying a basic Django application
By the end, you’ll have a solid foundation to start building your own Django-powered web applications.
Prerequisites
Before diving into Django, ensure you have: Python installed (3.9 or later recommended)
Basic Python knowledge (functions, classes, modules)
A code editor (VS Code, PyCharm, or Sublime Text)
Familiarity with the command line
Step 1: Setting Up a Virtual Environment
Before installing Django, it’s best practice to create a virtual environment to isolate dependencies:
On macOS/Linux:
python -m venv myenv # Create a virtual environment
source myenv/bin/activate # Activate it
On Windows:
python -m venv myenv # Create a virtual environment
myenv\Scripts\activate # Activate it
Once activated, install Django:
pip install django
or
pip freeze
pip install django==4.2.18
or
pip ininstall django==4.0.3
Verify the installation:
django-admin --version
# Output should be the latest Django version (e.g., 5.0)
Step 2: Creating a Django Project
A Django project is the entire web application, while apps are modular components within it (e.g., a blog app, user authentication app).
To create a new project:
django-admin startproject myproject
This generates the following structure:
myproject/
│
├── manage.py # Command-line utility
└── myproject/ # Main project package
├── __init__.py
├── settings.py # Project configurations
├── urls.py # URL routing
├── asgi.py # ASGI config (async support)
└── wsgi.py # WSGI config (deployment)
Running the Development Server
Navigate into your project and start the server:
cd myproject
python manage.py runserver
Visit http://127.0.0.1:8000/
in your browser—you should see Django’s default welcome page!
Step 3: Creating Your First Django App
A Django project can contain multiple apps. Let’s create one:
python manage.py startapp myapp
This generates:
myapp/
├── migrations/ # Database migrations
├── __init__.py
├── admin.py # Admin panel config
├── apps.py
├── models.py # Database models
├── tests.py
└── views.py # Business logic
Registering the App
Add your app to INSTALLED_APPS
in myproject/settings.py
:
INSTALLED_APPS = [
...
'myapp',
]
Step 4: Creating a Simple View
A view in Django processes HTTP requests and returns responses. Open myapp/views.py
and add:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
Mapping URLs to Views
1. Create urls.py
inside myapp
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
2. Include it in the project’s urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Now, visiting http://127.0.0.1:8000/
should display “Hello, Django!”
Step 5: Using Templates for Dynamic HTML
Django uses templates to render dynamic HTML.
Create a templates
folder in myapp
:
mkdir myapp/templates
Add home.html
inside it:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Django!</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
Update views.py
to render the template:
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'message': 'Hello from Django!'})
Now, the page will display “Hello from Django!” in styled HTML.
Step 6: Working with Django Models (Database)
Django’s ORM (Object-Relational Mapper) allows you to define database models using Python classes.
Creating a Model
Let’s create a Post
model for a blog in myapp/models.py
:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Running Migrations
Django needs to create database tables for your models:
python manage.py makemigrations # Generates migration files
python manage.py migrate # Applies migrations to the database
Using Django’s Admin Panel
Django comes with a built-in admin interface.
Create a superuser:
python manage.py createsuperuser
Follow the prompts to set up an admin account.
Register the model in admin.py
:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Access the admin panel at http://127.0.0.1:8000/admin/
Log in and manage your Post
entries.
Step 7: Displaying Data in Templates
Let’s fetch posts from the database and display them.
Update views.py
:
from django.shortcuts import render
from .models import Post
def home(request):
posts = Post.objects.all()
return render(request, 'home.html', {'posts': posts})
Modify home.html
:
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }} - {{ post.created_at }}</li>
{% endfor %}
</ul>
</body>
</html>
Now, any posts added via the admin panel will appear here!
Next Steps & Further Learning
You’ve built a basic Django app! To expand your knowledge:
- User Authentication: Use Django’s built-in
auth
system. - Forms: Learn how to handle user input.
- Class-Based Views (CBVs): A more structured way to write views.
- Deployment: Host your app on platforms like Render, Railway, or PythonAnywhere.
Here’s a well-structured addition to your Django guide focusing on settings.py
configurations, formatted for clarity and SEO optimization:
Essential Django settings.py Configurations for Production
When building Django applications, properly configuring your settings.py
file is crucial for security, performance, and functionality. Here are key modifications you should implement:
from django.contrib.messages import constants as messages
import os
1. Template Configuration
Ensure Django can find your template files:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # Add this line
'APP_DIRS': True,
...
},
]
2. Static & Media Files Setup
# Static files (CSS, JavaScript, Images)
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static') # For production
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'myproject/static'), # Development static files
]
# Media files (User uploads)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
3. Security Settings
# For development only - restrict in production!
ALLOWED_HOSTS = ['*']
# In production use:
# ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
4. Email Configuration (Gmail Example)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = "your@gmail.com"
EMAIL_HOST_PASSWORD = 'your_app_password' # Use app-specific password
5. Django Messages Framework
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.ERROR: 'danger', # Bootstrap compatibility
messages.SUCCESS: 'success',
messages.WARNING: 'warning',
}
Configuring URLs in Django: Static & Media Files Setup
Basic URL Configuration (urls.py
)
Every Django project needs proper URL routing. Here’s how to set up your main urls.py
file:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls), # Django admin interface
path('', include('myapp.urls')), # Include your app's URLs
]
# This serves static files during development (DEBUG=True)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
or
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls), # Django admin interface
path('', include('myapp.urls')), # Include your app's URLs
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Bonus: Common Use Case Scenarios (Extended)
Task | Command |
---|---|
Create a Django project | django-admin startproject mysite |
Create a Django app | python manage.py startapp blog |
Run the development server | python manage.py runserver |
Run server on custom IP & port | python manage.py runserver 0.0.0.0:8001 |
Make migrations | python manage.py makemigrations |
Apply migrations | python manage.py migrate |
Show all migrations | python manage.py showmigrations |
Create superuser for admin panel | python manage.py createsuperuser |
Load initial data from fixture file | python manage.py loaddata data.json |
Dump data to a fixture file | python manage.py dumpdata > data.json |
Reset database (dangerous in prod!) | python manage.py flush |
Check project for errors | python manage.py check |
Run automated tests | python manage.py test |
Start an interactive Django shell | python manage.py shell |
Start shell with IPython | python manage.py shell --interface=ipython |
Change admin password | python manage.py changepassword username |
List available management commands | python manage.py help |
View help for a specific command | python manage.py help <command> |
Create a new custom management command | Create file in app/management/commands/ |
Run custom management command | python manage.py <your_custom_command> |
Collect static files (for deployment) | python manage.py collectstatic |
Clear compiled static cache | python manage.py clearsessions |
Check missing migrations | python manage.py makemigrations --dry-run |
Conclusion
Django is a powerful, flexible framework that simplifies web development. In this guide, we covered: Setting up a Django project
Creating views & URL routing
Working with templates
Database models & the admin panel
Now, try building a blog, to-do app, or a simple CRM to practice!
Got questions? Drop them in the comments below!
#Django #Python #WebDevelopment #Programming #BeginnersGuide