Coupling Django and React using DRF

Bharat Saraswat

JavaScript Developer

Github: bhansa

StackOverflow: bhansa

Twitter: @bharat293

Why Django and react?

  • Why not?
  • Django Rest Framework is great for API developement
  • React is nice for frontend

Lifecycle of a django app

  • Create your app
  • Register you app
  • Create your models
  • register your models
  • Create your views
  • Configure urls

Source: MDN

$ django-admin startproject backend

$ python manage.py startapp blog
$ python manage.py migrate
$ python manage.py runserver

Let's create our backend

# backend/setting.py

INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'blog' # add our app here 
      ]

Register our app

# backend/blog/models.py

from django.conf import settings
from django.db import models
from django.utils import timezone 

# Create your models here.

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default = timezone.now)
    published_date = models.DateTimeField(blank = True, null = True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()
    
    def __str__(self):
        return self.title

Define our Post model

$ python manage.py makemigrations blog
$ python manage.py migrate blog

and finally, migrate our models

django and react using DRF

By Bharat Saraswat

django and react using DRF

  • 825