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.
Thank you for reading this post, don't forget to subscribe!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:
1 2 |
python -m venv myenv # Create a virtual environment source myenv/bin/activate # Activate it |
On Windows:
1 2 |
python -m venv myenv # Create a virtual environment myenv\Scripts\activate # Activate it |
Once activated, install Django:
1 2 3 4 5 6 |
pip install django or pip freeze pip install django==4.2.18 or pip ininstall django==4.0.3 |
Verify the installation:
1 2 |
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:
1 |
django-admin startproject myproject |
This generates the following structure:
1 2 3 4 5 6 7 8 9 |
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:
1 2 |
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:
1 |
python manage.py startapp myapp |
This generates:
1 2 3 4 5 6 7 8 |
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
:
1 2 3 4 |
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:
1 2 3 4 |
from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") |
Mapping URLs to Views
1. Create urls.py
inside myapp
:
1 2 3 4 5 6 |
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] |
2. Include it in the project’s urls.py
:
1 2 3 4 5 6 7 |
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
:
1 |
mkdir myapp/templates |
Add home.html
inside it:
1 2 3 4 5 6 7 8 9 |
<!DOCTYPE html> <html> <head> <title>Welcome to Django!</title> </head> <body> <h1>{{ message }}</h1> </body> </html> |
Update views.py
to render the template:
1 2 3 4 |
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
:
1 2 3 4 5 6 7 8 9 |
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:
1 2 |
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:
1 |
python manage.py createsuperuser |
Follow the prompts to set up an admin account.
Register the model in admin.py
:
1 2 3 4 |
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
:
1 2 3 4 5 6 |
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
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!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:
1 2 |
from django.contrib.messages import constants as messages import os |
1. Template Configuration
Ensure Django can find your template files:
1 2 3 4 5 6 7 8 |
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
1 2 3 4 5 6 7 8 9 10 |
# 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
1 2 3 4 5 |
# For development only - restrict in production! ALLOWED_HOSTS = ['*'] # In production use: # ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com'] |
4. Email Configuration (Gmail Example)
1 2 3 4 5 6 |
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = 'your_app_password' # Use app-specific password |
5. Django Messages Framework
1 2 3 4 5 6 7 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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
1 2 3 4 5 6 7 8 9 10 |
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) |
Recommended Resources
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