Skip to content

Latest commit

 

History

History
94 lines (71 loc) · 2.28 KB

3. App's.md

File metadata and controls

94 lines (71 loc) · 2.28 KB

📌 App's

  • Create the app ( will make a new folder ):
python3 manage.py startapp tasks_app
  • Add app name dependency to project "settings.py":
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tasks_app',        # new app
    'rest_framework',
    'corsheaders',
]
  • Create a model in the app "models.py" ( ORM ):
from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    done = models.BooleanField(default=False)

    def __str__(self):
        return self.title
  • Migrate to apply the model changes:
python manage.py makemigrations "tasks_app"

python manage.py migrate "task_app"
  • Add model to app "admin.py" ( to be acessible on Django admin page ):
from django.contrib import admin
from .models import Task

admin.site.register(Task)
  • Create app "serializers.py" ( Class that will convert python objects to JSON and vice versa ):
from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__' # All fields of model
  • Make a view for this model in the app "views.py" ( enpoint ):
from .serializers import TaskSerializer
from .models import Task
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

@api_view(['GET'])
def getTasks(request):
    tasks = Task.objects.all()                                      # Get all tasks from database
    serializer = TaskSerializer(tasks, many=True)                   # Convert to JSON (serialize)
    return Response(serializer.data, status=status.HTTP_200_OK)     # Return JSON to client
  • Configure the project "urls.py" to enable requests to the view by URL:
from django.contrib import admin
from django.urls import path
from tasks_app import views

urlpatterns = [
    path('admin/', admin.site.urls),                    # Admin Panel
    path('tasks/', views.getTasks, name='getTasks'),    # GET