You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
from django.db import models
from django.utils import timezone
class Task(models.Model):
STATUS_CHOICES = (
('BL', 'Backlog'),
('IP', 'In-progress'),
('DN', 'Done'),
)
title = models.CharField(max_length=200)
description = models.TextField()
status = models.CharField(max_length=2, choices=STATUS_CHOICES, default='BL')
completed_at = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
if self.status == 'DN' and not self.completed_at:
self.completed_at = timezone.now()
elif self.status != 'DN':
self.completed_at = None
super().save(*args, **kwargs)
After defining the models, you need to create and apply migrations to update the database schema accordingly.
Run the following commands:
python3 manage.py makemigrations
python3 manage.py migrate
Register Task model to admin panel in "todolist/admin.py" file
from .models import Task
admin.site.register(Task)
Step 5: Create the serializers and views for CRUD operation
You'll need to create a serializer class for the Task model to handle serialization and deserialization of the data.
Make a newfile called "serializers.py"
touch todolist/serializers.py
Add below lines to it :
from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = '__all__'
In "todolist/views.py" file
Import necessary modules:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Task
from .serializers import TaskSerializer
Create an API view for creating a task:
class TaskCreateAPI(APIView):
def post(self, request):
serializer = TaskSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
"tasks/": This pattern matches the endpoint for retrieving a list of tasks. It maps to the TaskListAPI view through the as_view() method. You can access the list of tasks using /api/tasks/ URL.
"tasks/create/": This pattern matches the endpoint for creating a new task. It maps to the TaskCreateAPI view through the as_view() method. You can use the //api/tasks/create/ URL to create a new task.
"tasks/int:pk/": This pattern matches the endpoint for retrieving, updating, or deleting a specific task. The int:pk captures the primary key (pk) of the task. It maps to the TaskDetailAPI view. You can access a specific task using /api/tasks/<task_id>/, where <task_id> is the primary key of the task.
Step 7: Create a superuser
python3 manage.py createsuperuser
Step 8: Run project and check access to admin panel :