0% found this document useful (0 votes)
10 views2 pages

Django React CheatSheet

This document provides a cheat sheet for building a full stack application using Django and React. It includes code snippets for creating a Todo model, serializer, viewset, URL routing, MongoDB setup, and React fetch examples for retrieving and adding todos. The cheat sheet serves as a quick reference for developers working with this technology stack.

Uploaded by

abbud5859
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views2 pages

Django React CheatSheet

This document provides a cheat sheet for building a full stack application using Django and React. It includes code snippets for creating a Todo model, serializer, viewset, URL routing, MongoDB setup, and React fetch examples for retrieving and adding todos. The cheat sheet serves as a quick reference for developers working with this technology stack.

Uploaded by

abbud5859
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Django + React Full Stack Cheat Sheet

1. Model
from django.db import models

class Todo(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)

2. Serializer
from rest_framework import serializers
from .models import Todo

class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = '__all__'

3. View (ViewSet)
from rest_framework import viewsets
from .models import Todo
from .serializers import TodoSerializer

class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer

4. URLs (Router)
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import TodoViewSet

router = DefaultRouter()
router.register('todos', TodoViewSet)

urlpatterns = [
path('', include(router.urls)),
]

5. MongoDB Setup (settings.py)


DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'todo_db',
}
}

6. React Fetch Example


const fetchTodos = async () => {
const res = await fetch('http://localhost:8000/api/todos/');
const data = await res.json();
setTodos(data);
};

const addTodo = async () => {


await fetch('http://localhost:8000/api/todos/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, completed: false })
});
};

You might also like