0% found this document useful (0 votes)
73 views

Denis Ivy: Tutorial 01

This tutorial shows how to create a Django REST API using Django REST framework to perform CRUD operations on articles. The steps include: 1. Creating a Django project and app 2. Configuring the app to use Django REST framework 3. Defining Article models and serializers 4. Setting up API views using ModelViewSet to list, retrieve, create, update and delete articles 5. Configuring URLs to expose the API endpoints

Uploaded by

ritesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Denis Ivy: Tutorial 01

This tutorial shows how to create a Django REST API using Django REST framework to perform CRUD operations on articles. The steps include: 1. Creating a Django project and app 2. Configuring the app to use Django REST framework 3. Defining Article models and serializers 4. Setting up API views using ModelViewSet to list, retrieve, create, update and delete articles 5. Configuring URLs to expose the API endpoints

Uploaded by

ritesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Denis Ivy

Django-React Tutorial
TUTORIAL 01
1. pip install djangorestframework
2. add rest_framework on settings file

# all the codes below are to be added on API folder (or any app created within)

3. on views file

from django.shortcuts import render


from django.http import JsonResponse

from rest_framework.decorators import api_view


from rest_framework.response import Response

from .models import Task


from .serializers import TaskSerializer

# what this decorator allows is get the GET response from api
@api_view([‘GET’])
def apiOverview(request):
api_url = {
‘List’:/task-list/’,
‘Detail View’:’task-detail/<str:pk>/’,
‘create’:’task-create/’,
‘update’:/task-update/<str:pk>/,
‘Delete’:’/task-delete/<str:pk/’
}

return Response(api_url)

@api_view([‘GET’])
def taskList(request):
tasks = Task.objects.all()
seializer = TaskSerialzer(tasks, many=True)
return Response(seializer.data)

@api_view([‘GET’])
def taskDetail(request,pk):
tasks = Task.objects.get(id=pk)
seializer = TaskSerialzer(tasks, many=False)
return Response(seializer.data)

@api_view([‘POST])
def taskCreate(request):
seializer = TaskSerialzer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(seializer.data)

@api_view([‘POST])
def taskUpdate(request,pk):
tasks = Task.objects.get(id=pk)
seializer = TaskSerialzer(instance=task, data=request.data)

if serializer.is_valid():
serializer.save()

return Response(seializer.data)

@api_view([‘DELETE])
def taskDelete(request,pk):
tasks = Task.objects.get(id=pk)
task.delete()

return Response(‘Item successfully de)

4. on models file

from django.db import models

class Task(models.Model):
task=models.CharField(max_length=200)
completed = models.BooleanField(default=False)

def __str__(self):
return self.title

5. create a new file on the app named serializers.py

from rest_framework import serializers


from .models. import Task

class TaskSerializer(serializers.ModelSerializer):
class Meta:
model= Task
fields = ‘__all__’

6. on urls.py file
from django.urls import path
from .import views

urlpatterns = [
path(‘’, views.apiOverview, name=”api-overview”),
path(‘task-list/’, views.taskList, name=”task-list”),
path(‘task-detail/<str:pk>’, views.taskDetail, name=”task-detail”),
path(‘task-create/’, views.taskCreate, name=”task-create”),
path(‘task-update/<str:pk>’, views.taskUpdate, name=”task-update”),
path(‘task-delete/<str:pk>’, views.taskDelete, name=”task-delete”),

]
Just Django
Django-React Tutorial
TUTORIAL 01
Source: https://www.youtube.com/watch?v=uZgRbnIsgrA&t=395s

1. create virtual environment


2. activate the virtual environment
3. pip install django
4. pip install djangorestframework
5. django-admin startproject djreact .
6. python3 manage.py migrate
7. python3 manage.py startapp articles
8. add the following on the installed apps section of the settings:

INSTALLED_APPS = [
‘…’,
‘rest_framework’,
‘articles’
]

9. On the main urls.py file add the following

import django.urls import path, include

urlpatterns = [
‘…’,
path(api-auth/’, include(rest_framework.url)),
]

10. On the settings file add the following at the bottom of the file.

REST_FRAMEWORK = {
‘DEFAULT_PERMISSION_CLASSES’: [
‘rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly’
]
}

11. on the articles>models.py file add the following:

from django.db import models

class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()

def __str__(self):
return self.title

12. python3 manage.py makemigrations articles


13. python3 manage.py migrate articles
14. on articles>admin.pu add the following:

from .models import Article


admin.site.register(Article)

15. python3 manage.py createsuperuser


16. create 2 artcles from the admin panel

# NOW WHAT THIS TUTOR IS DOING IS HE IS CREATING ANOTEHR FOLDER TO WORK


WITH APIS WHICH I DON’T THINK WE WOULD REQIURE BUT LETS JUST CONTINUE THE
LECUTRE.

17. create a folder inside articles named api


18. initialize the folder by adding a file named __init__.py inside the api folder.
19. create another file named serializers.py inside the api folder.

from rest_framework import serializers


from aritcles.models import Article

class ArticleSerializer(serialzers.ModelSerializer):
class Meta:
model = Article
fields = (‘title’, ‘content’)

20. Inside api folder create a new file named views.py

from rest_framework import ListAPIView, RetrieveAPIView, CreateAPIView, UpdateAPIView,


DestroyAPIView

from articles.models import Article


from .serializers import ArticleSerializer

class ArticleListView(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

class ArticleDetailView(RetrieveAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

class ArticleCreateView(CreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

class ArticleUpdateView(UpdateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

class ArticleDeleteView(DestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

21. create a new file named urls.py inside api folder.

from django.urls import path


from .views import ArticleListView, ArticleDetailView, ArticleCreateView , ArticleUpdateView,
ArticleDeleteView

urlpatterns = [
path(‘’,ArticleListView.as_view()),
path(‘create’, ArticleCreateView.as_view()),
path(‘<pk>’, ArticleDetailView.as_view()),
path(‘<pk>/update/’, ArticleUpdateView.as_view()),
path(‘<pk>/delete/’, ArticleDeleteView.as_view()),
]

22. on the main url file add the following:

urlpatterns = [
‘…’,
path(‘api/’ include(‘articles.api.urls’))
]

23. pip install django-cors-headers


24. on INSTALLED_APPS of the settings file add the following:

INSTALLED_APPS = [
‘…’,
‘corsheaders’
]

25. on the MIDDLEWARE of the settings file add the following:

MIDDLEWARE = [
‘…’,
‘django.middleware.SecurityMiddleware’,
]

26. on the bottom of the settings files add the following line of code.

CORS_ORIGIN_ALLOW_ALL=True

the above line of code will white list all the sites to make requests
But if you need only a few sites to be white listed we need to do the following:

CORS_ORIGIN_WHITELIST = [
‘google.com’
‘localhost:8000’,
‘127.0.0.1:8080’,
‘hostname.example.com’
]

# NOW ON THE ABOVE SECTION WHAT WE SEE IS THE CLASS IS CONSTANTLY BEING
REPEATED THERE HAS GOT TO BE A BETTER WAY! WE WILL NOW UPDATE THE
ABOVE VIEW CODE AND URLS TO MAKE IT CLEANER.

27. Edit the urls file as below:

from rest_framework.routers import DefaultRouter


from articles.api.views import ArticleViewSet

router=DefaultRouter()
router.register(path(‘’, ArticleViewSet, base_name=”articles”)
urlpatterns = router.urls

28. Update the views file as below;

from rest_framework import viewsets

from articles.models import Article


from .serializers import ArticleSeralizer

class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()

# THE ABOVE DOES NOT ALLOW ANY MODIFICATION AS THE INDIVIDUAL CLASSES

You might also like