Prompt Detail:
Sure, here is an example of how you can create a Django API for a todo React website with user authentication and CRUD (create, read, update, delete) functionality:
- Install Django Rest Framework:
You can install Django Rest Framework using pip:
pip install djangorestframework
- Create a new Django app:
python manage.py startapp todo_api
- Add the app to the INSTALLED_APPS in settings.py:
cssINSTALLED_APPS = [ ... 'rest_framework', 'todo_api',]
- Create a User model:
pythonfrom django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
- Create a serializer for the User model:
pythonfrom rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
- Create views for registering new users, logging in, creating, reading, updating and deleting todos:
pythonfrom django.shortcuts import get_object_or_404
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from rest_framework_simplejwt.views import TokenObtainPairView
from .models import User, Todo
from .serializers import UserSerializer, TodoSerializer
class RegisterView(generics.CreateAPIView):
queryset = User.objects.all()
permission_classes = [permissions.AllowAny]
serializer_class = UserSerializer
class LoginView(TokenObtainPairView):
pass
class TodoListView(generics.ListCreateAPIView):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class TodoDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
permission_classes = [permissions.IsAuthenticated]
def get_object(self):
obj = get_object_or_404(Todo, id=self.kwargs['pk'], user=self.request.user)
return obj
- Add URLs for the views:
pythonfrom django.urls import path
from rest_framework_simplejwt.views import TokenRefreshView
from .views import RegisterView, LoginView, TodoListView, TodoDetailView
urlpatterns = [
path('register/', RegisterView.as_view(), name='register'),
path('login/', LoginView.as_view(), name='login'),
path('refresh/', TokenRefreshView.as_view(), name='refresh'),
path('todos/', TodoListView.as_view(), name='todo-list'),
path('todos/<int:pk>/', TodoDetailView.as_view(), name='todo-detail'),
]
This code creates four endpoints:
- /register/ - for registering new users
- /login/ - for logging in
- /todos/ - for creating and reading todos
- /todos/int:pk/ - for updating and deleting todos
Note that this is just an example and you may need to modify it to fit your specific needs. You should also add appropriate error handling and authentication mechanisms to ensure the security and robustness of your API.