I 💚 Python
Outline challenges and tradeoffs of a decoupled approach.
By the end of the talk you should be able to configure a new Django REST project with a front-end library for interacting with the API.
Exposing data and contents "outside" Django templates, with the help of a REST API.
Decoupling Django means exposing your models as JSON.
Because of flexibility... Back-end and front-end developers can work in isolation. Also, no need to fight build tools.
But a decoupled approach can give a lot of headaches! Code duplication, more testing, more developers.
A decoupled approach imposes challenges!
These are good signs that you will benefit from decoupling:
These are good signs that you don't need to decouple:
Django REST framework is a Django application for building REST APIs on top of Django.
pip install djangorestframework
But first ... Django models!
Serializers are a layer between Django models and the outside world (they mirror Django forms).
from rest_framework import serializers from .models import Link
class Meta: model = Link fields = ('title', 'url', 'tags')
tags = serializers.StringRelatedField(many=True)
fields = '__all__' # Don't do that
Views in DRF can be written as plain functions.
But even better with Generic Views.
After creating a serializer and a view we can expose the API endpoint.
React is a front-end library for building composable, reusable, user interfaces.
npm i react react-dom
A closer look at two practical approaches ...
Approach #1: A CRA React app in app_name/
But when running npm run build you get these files:
Approach #2: a custom webpack project in app_name/
We have control over the bundle path! Ok for development:
But now ... how about splitChunks and code splitting?
With splitChunks you can aggressively split your bundle. Ending up with a lot of files ...
How do we inject these files into our Django template?
Maybe we can build a "django-webpacker"?
Fully decoupled front-end! Best of both worlds, you don't fight tools.
Don't forget to enable django-cors-headers! https://github.com/ottoyiu/django-cors-headers/
Authentication plays an important role in a decoupled setup.
pip install djangorestframework_simplejwt
A lot of options for testing the front-end:
A lot of options for testing the API too:
Django REST framework is great!
You may want to investigate more advanced topics: