Environment Configuration
Ensure Python is installed on your system. It is recommended to create a virtual environment before installing Django to manage dependencies effectively.
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install django
Verify the installation:
python -m django --version
Project Initialization
A Django project represents the entire web application. Generate a new project structure using the command line:
django-admin startproject mysite
cd mysite
Launch the development server to verify the setup:
python manage.py runserver
Application Creation
While a project encompasses the whole configuration, an app is a self-contained module designed for reusability (e.g., a blog, a polling system). Create a new app:
python manage.py startapp blog
Remember to add the newly created app to the INSTALLED_APPS list in mysite/settings.py.
Handling HTTP Requests
Open blog/views.py and define a simple view to handle incoming requests and return a response:
from django.http import HttpResponse
def index(request):
return HttpResponse("Welcome to the Django Application!")
Wire this view to a URL by creating a urls.py file within the blog directory and including it in the main project URLs.
Database Models and ORM
The Model layer serves as an abstraction between views and the database, translating Python classes into database tables. Define a data structure for blog posts in blog/models.py:
from django.db import models
class BlogPost(models.Model):
headline = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.headline
Generate and apply the database schema migrations:
python manage.py makemigrations
python manage.py migrate
Interactive Shell
The Django shell allows for direct interaction with models, which is ideal for debugging and quick data manipulation without running the full server:
python manage.py shell
from blog.models import BlogPost
BlogPost.objects.create(headline="First Entry", content="This is the initial post content.")
Administration Interface
Django provides a built-in admin panel for managing data. First, create a superuser account:
python manage.py createsuperuser
Register the BlogPost model in blog/admin.py to make it visible in the admin dashboard:
from django.contrib import admin
from .models import BlogPost
admin.site.register(BlogPost)
Start the server and navigate to /admin/ to log in and manage records.
Serving Dynamic Data
Update the view to fetch records from the database and pass them to a template:
from django.shortcuts import render
from .models import BlogPost
def post_list(request):
all_posts = BlogPost.objects.all()
return render(request, 'blog/list.html', {'posts': all_posts})
Frontend Integration with Bootstrap
Utilize the Bootstrap framework for responsive design. Below is a layout for displaying the list of posts using a 12-column grid system.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django Blog</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<div class="row">
<div class="col-md-8">
<h2>Latest Posts</h2>
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">Post Title</h5>
<p class="card-text">Excerpt of the blog post content goes here.</p>
</div>
</div>
</div>
<div class="col-md-4">
<h4>Sidebar</h4>
<ul class="list-group">
<li class="list-group-item">Recent Item 1</li>
<li class="list-group-item">Recent Item 2</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Template Engine Syntax
Django templates allow embedding dynamic logic within HTML.
Variable Rendering:
<p>Current timestamp: {{ current_time }}</p>
Iterating over QuerySets:
<ul>
{% for post in posts %}
<li>{{ post.headline }}</li>
{% endfor %}
</ul>
Conditional Logic:
{% if user.is_authenticated %}
<p>Welcome back!</p>
{% else %}
<p>Please log in.</p>
{% endif %}