A complete guide to learning and building projects with Python & Django — the powerful backend framework trusted by developers for creating dynamic, secure, and scalable web applications. From setup to deployment, master Django Models, Views, Templates, REST API, and authentication systems.
A Django app is a self-contained module that performs a specific function within a Django project. It can be reused across different projects. To create a Django app, follow these steps:
python manage.py startapp app_name
where app_name
is your desired app name.For example, if you want to create an app called 'blog', you would run
python manage.py startapp blog
. This app can now manage blog-related functionalities.
Migrations in Django are used to propagate changes you make to your models (adding a field, deleting a model, etc.) into the database schema. To create and apply migrations, follow these steps:
models.py
.python manage.py makemigrations
to create a migration file.python manage.py migrate
to apply the migration to the database.This process ensures your database schema is synchronized with your models. For instance, if you add a new field published_date
to a model, running these commands updates the database accordingly.
Django class-based views provide an object-oriented way to handle requests. They encapsulate behavior in classes rather than functions. Here's how to create one:
django.views
.View
.get()
and post()
to handle requests.Example:
from django.views import View
class MyView(View):
def get(self, request):
return HttpResponse('Hello, World!')
This view responds to GET requests with a simple message.
Django's admin interface provides a web interface for managing your site's data. To use it:
INSTALLED_APPS
in settings.py
.python manage.py createsuperuser
to create an admin user.python manage.py runserver
./admin/
in your browser and log in with the superuser credentials.Once logged in, you can manage models registered in the admin interface. For instance, if you have a Blog
model, it will show up in the admin dashboard for easy management.
Django Rest Framework (DRF) is a powerful toolkit for building Web APIs in Django. It simplifies the process of creating RESTful APIs by providing features like serialization, authentication, and viewsets. Here's how to get started:
pip install djangorestframework
.'rest_framework'
to your INSTALLED_APPS
in settings.py
.For example, if you have a Post
model, your serializer might look like this:
from rest_framework import serializers
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
DRF allows you to quickly expose your Django models as APIs.
Custom middleware in Django is a way to process requests globally before they reach the view or after the view has processed them. To create custom middleware:
__init__
and __call__
methods or specific middleware methods like process_request
.MIDDLEWARE
setting in settings.py
.Example:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Code to execute for each request before the view
response = self.get_response(request)
return response
This middleware can be used for logging or modifying requests/responses.
Django signals allow certain senders to notify a set of receivers when certain actions have taken place. This is useful for decoupling applications. Here’s how to use signals:
django.dispatch
.connect
method.Example:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, **kwargs):
print('Model saved!')
This function runs every time an instance of MyModel
is saved.
Deploying a Django application involves several steps to ensure it runs smoothly in a production environment. Here’s a basic guide:
settings.py
for production (e.g., DEBUG = False
).For instance, to deploy on Heroku, you would:
heroku create
heroku addons:create heroku-postgresql
git push heroku master
This pushes your code to Heroku and sets up the database.
Django models are Python classes that define the structure of your database tables. They serve as the bridge between your application and the database, allowing you to create, retrieve, update, and delete records easily.
To define a model, you create a Python class that inherits from django.db.models.Model
. Each attribute of the class represents a database field. For example:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
In this example, the Book
model has three fields: title
, author
, and published_date
. After defining your model, you can create a migration with python manage.py makemigrations
and apply it with python manage.py migrate
.
Custom template filters in Django allow you to modify template variables before rendering them. This feature enhances the presentation of data in templates.
To create a custom filter, follow these steps:
templatetags/my_filters.py
.@register.filter
.Here’s an example of a custom filter that converts text to uppercase:
from django import template
register = template.Library()
@register.filter
def to_uppercase(value):
return value.upper()
After defining the filter, you can use it in your templates like this: {{ my_text|to_uppercase }}
.