from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from apps.api.serializers import LineSerializer, PostSerializer, UserSerializer from apps.billboard.models import Line, Post from apps.lyric.models import User class PostDetailAPI(APIView): def get(self, request, post_id): post = get_object_or_404(Post, id=post_id) serializer = PostSerializer(post) return Response(serializer.data) class PostLinesAPI(APIView): def post(self, request, post_id): post = get_object_or_404(Post, id=post_id) serializer = LineSerializer(data=request.data, context={"post": post}) if serializer.is_valid(): serializer.save(post=post, author=request.user) return Response(serializer.data, status=201) return Response(serializer.errors, status=400) class PostsAPI(APIView): def get(self, request): posts = Post.objects.filter(owner=request.user) serializer = PostSerializer(posts, many=True) return Response(serializer.data) def post(self, request): text = request.data.get("text", "") post = Post.objects.create(owner=request.user, title=text[:35]) Line.objects.create(text=text, post=post, author=request.user) serializer = PostSerializer(post) return Response(serializer.data, status=201) class UserSearchAPI(APIView): def get(self, request): q = request.query_params.get("q", "") users = User.objects.filter( username__icontains=q, searchable=True, ) serializer = UserSerializer(users, many=True) return Response(serializer.data)