Photo by Sincerely Media on Unsplash
Django and Django Rest Framework Mastery: A Code-Driven Guide
A guide on how to systematically integrate Django rest framework with Django.
Table of contents
- Setting Up Your Django Project
- Building Models and Database Interaction
- Creation of Django Views
- Woking with Django Templates
- User Authentication and Authorization
- Django Rest Framework Introduction to the Project
- API Endpoints and CRUD Operations
- Update the Codes in your views.py file
- Authentication and Permissions in Django Rest Framework (DRF)
- Handling Serialization and Deserialization
- Pagination and Filtering
- Versioning and Customization
- Testing your Django Application and API
- Handling File Uploads and Media Files
- Optimizing Performance
- Deploying your application.
- Handling Static Files in urls.py
Setting Up Your Django Project
The first step of any Django Project is typically to create the project itself, and the application(s) it houses.
You can check the link below on how to set up a typical Django project and application. Creating Django application
pipenv install django
django-admin startproject myproject
Building Models and Database Interaction
Here, the focus is on defining models for the application using Django's Object-Relational Mapping (ORM). The code example showcases the creation of a simple model for an item with name and price field.
#models.py
from django.db import models
class Item(models.Model):
name=models.CharField(max_length=100)
price=models.DecimalField(max_digits=10,decimal_places=2)
NB
python manage.py makemigrations
and python manage.py migrate.
Creation of Django Views
This part explores the creation of Django views, essential for handling HTTP requests. The code utilizes class-based views, providing a reusable and organized structure. For instance, the example below, attempts to retrieve a list of items from the database and renders them using a Django template.
#views.py
from django.shortcuts import render
from django.views import View
from .models import Item
class ItemListView(View):
def get(self,request):
items=Item.objects.all()
return render(request,"item_list.html",{"items":items})
Woking with Django Templates
Django templates are introduced in this section for rendering dynamic HTML content. The code demonstrates how to design templates, use template inheritance, and pass context data from views. It enhances the separation of logic and presentation in web development.
<!---- items_list.html -->
<ul>
{% for item in items %}
<li> {{ item.name }} - ${{ item.price }} </li>
{% endfor %}
</ul>
User Authentication and Authorization
The code here focuses on setting up user authentication and authorization in a Django project. It involves configuring the INSTALLED_APPS in settings.py and implementing user registration and login functionalities.
#settings.py
INSTALLED_APPS=[
#...
'django.contrib.auth',
'django.contrib.contenttypes',
]
Django Rest Framework Introduction to the Project
This part initiates the integration of Django Rest Framework (DRF) into the project. The code includes installing DRF, and it introduces the concept of serializers and views in DRF, laying the foundation for building RESTful APIs.
pipenv install djangorestframework
Ensure you include Django rest framework in the list of installed apps in settings.py file of your project.
Ensure you also create a serializers.py file in your application folder where you have the likes of views.py, and models.py
files.
API Endpoints and CRUD Operations
DRF is utilized to create API endpoints for CRUD operations. The code features serializers and class-based views in DRF, illustrating how to handle GET and POST requests for item resources in the API.
#serializers.py
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model=Item
fields=['id','name','price']
Update the Codes in your views.py file
#views.py
#....
#....
from rest_framework import generics
class ItemListAPiView(generics.ListCreateAPIView):
queryset=Item.objects.all()
serializer_class=ItemSerializer
Authentication and Permissions in Django Rest Framework (DRF)
This section explains the implementation of token-based authentication in DRF, enhancing API security. The code demonstrates how to set authentication and permission classes in the DRF settings to control access to API views.
#settings.py
REST_FRAMEWOK={
'DEFAULT_AUTHENTICATION_CLASSES':[
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES':[
'rest_framework.permissions.IsAuthenticated',
],
}
Handling Serialization and Deserialization
The focus here is on the serialization and deserialization of data in DRF. The code showcases how to create serializers for complex data structures, validating incoming data, and transforming database records into JSON format.
#views.py
class ItemListApiView(generics.ListCreateAPIView):
#...
def perform_create(self,serializer):
serializer.save(user=self.request.user)
Pagination and Filtering
Pagination and filtering capabilities are added to the API to handle large datasets efficiently. The code introduces DRF's pagination and filtering options, demonstrating their application in the API views.
#views.py
from rest_framework import pagination
class ItemPagination(pagination.PageNumberPagination):
page_size=10
Versioning and Customization
This part covers the versioning of API endpoints in DRF and customizing various components. The code illustrates how to manage API versioning and customize serializers, views, and URL patterns.
#urls.py
from rest_framework.urlpatterns import format_suffix_patterns
from django.urls import path
from .views import ItemListApiView
urlpatterns=[
#...
path('api/items/',ItemListApiView.as_view(),name='item-list'),
]
Testing your Django Application and API
Testing practices are introduced, emphasizing the importance of unit tests for Django models, views, and API endpoints. The code includes examples of using DRF's testing tools for API testing, ensuring the reliability of the application.
#tests.py
from django.test import TestCase
from rest_framework.test import APIClient
class ItemAPitests(TestCase):
def test-api_returns_items(self):
client=APIClient()
response=client.get('/api/items/')
self.assertEqual(response.status_code,200)
Handling File Uploads and Media Files
This section explores the integration of file handling in the Django project, including file uploads and serving media files. The code demonstrates how to add an image field to a model and handle file uploads in DRF.
#models.py
class item(models.Model):
#...
image=models.ImageField(upload_to='item_images/',null=True,blank=True)
Optimizing Performance
The code showcases how to configure caching settings in settings.py to enhance the speed and responsiveness of the application.
#settings.py
CACHES={
'default':{
'BACKEND':'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION':'127.0.0.1:11211',
}
}
Deploying your application.
The code highlights configuring production settings, handling static files, and deploying the application using popular web server Gunicorn.
# settings.py
# Update DEBUG to False for production
DEBUG = False
# Set your production domain(s) for the 'ALLOWED_HOSTS' setting
ALLOWED_HOSTS = ['yourdomain.com']
# Use a secure secret key
SECRET_KEY = 'your_secure_secret_key'
# Configure database settings for production (e.g., use PostgreSQL)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_db_name',
'USER': 'your_db_user',
'PASSWORD': 'your_db_password',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Use secure connection (HTTPS)
SECURE_SSL_REDIRECT = True
# Set secure HTTP headers
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'
# Configure email settings for production (e.g., using SMTP)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'your_smtp_host'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your_smtp_user'
EMAIL_HOST_PASSWORD = 'your_smtp_password'
Handling Static Files in urls.py
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# Your existing URL patterns
]
# Serve static files during development
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Creating secret key for your Django app with Python
import secrets
def generate_secret_key():
# Generate a 50-character random string suitable for a Django secret key
return secrets.token_hex(25)
# Example usage
secret_key = generate_secret_key()
print(f"Generated Secret Key: {secret_key}")
NB
Deploying with Gunicorn
#Install gunicorn
pipenv install gunicorn
#Run gunicorn to server your Django Project
gunicorn your_project.wsgi:application
Here you have the basic template to follow in integrating a Django Project with Django Rest Framework from deployment up till production.
Feel free to comment, ask questions. I am also open to collaboration.