Select a Subtopic
Day 21: Django Framework
Introduction to Django
Django is a high-level Python web framework that allows developers to build robust web applications quickly. It's highly recommended for building database-driven web applications. Django provides a lot of functionality out-of-the-box, such as an admin interface, authentication, and form handling.
Why Django?
- Rapid development with built-in features.
- Secure and scalable.
- Supports a wide range of databases.
- Rich ecosystem of libraries and plugins.
1. Setting Up Django
Step 1: Install Django
If you haven't already, install Django using pip
:
pip install django
Step 2: Create a Django Project
After installing Django, create a new project. A Django project is a collection of settings, configurations, and applications. Run the following command:
django-admin startproject myproject
This will create a folder myproject
with the basic structure:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
Step 3: Run the Development Server
Navigate into the project directory and run the development server:
cd myproject python manage.py runserver
You should see output that says:
Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
Open your browser and visit http://127.0.0.1:8000/
to see the Django welcome page!
2. Creating a Django App
Step 1: Create an App
Inside the project directory, run:
python manage.py startapp blog
This creates a folder blog
with the following structure:
blog/
__init__.py
admin.py
apps.py
models.py
views.py
tests.py
migrations/
Step 2: Add the App to the Project
Open the myproject/settings.py
file and add 'blog'
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # Add this line
]
3. Creating Models in Django
Step 1: Define a Blog Post Model
In the blog/models.py
file, define a BlogPost
model:
from django.db import models
class BlogPost(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
Step 2: Migrate the Model to the Database
After defining the model, run the migration commands to create the table in the database:
python manage.py makemigrations python manage.py migrate
4. Creating Views in Django
Step 1: Create a Simple View
In the blog/views.py
file, create a view that displays all blog posts:
from django.shortcuts import render
from .models import BlogPost
def blog_list(request):
posts = BlogPost.objects.all() # Retrieve all blog posts from the database
return render(request, 'blog/blog_list.html', {'posts': posts})