Advertisement
shinhosuck1973

Django-Rest-Framework-CRUD-function-views.py

Mar 7th, 2024 (edited)
627
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.80 KB | None | 0 0
  1. #VIEWS.PY
  2. @api_view(['GET'])
  3. @permission_classes([AllowAny])
  4. def topics_view(request):
  5.     topics = Topic.objects.all().prefetch_related('author')
  6.     serializer = TopicSerializer(topics, many=True)
  7.     return Response(serializer.data, status=status.HTTP_200_OK)
  8.    
  9.  
  10. @api_view(['GET'])
  11. @permission_classes([AllowAny])
  12. def topic_detail_view(request, id):
  13.     try:
  14.         topic = Topic.objects.get(id=id)
  15.     except Topic.DoesNotExist:
  16.         message = {'error': 'Topic not found'}
  17.         return Response(message, status=status.HTTP_400_BAD_REQUEST)
  18.     serializer = TopicSerializer(topic)
  19.     return Response(serializer.data, status=status.HTTP_200_OK)
  20.  
  21.  
  22. @api_view(['POST'])
  23. @permission_classes([IsAuthenticated])
  24. @authentication_classes([TokenAuthentication])
  25. @parser_classes([MultiPartParser, FormParser])
  26. def create_topic_view(request, format=None):
  27.     serializer = TopicSerializer(data=request.data)
  28.  
  29.     if serializer.is_valid():
  30.         new_topic = serializer.save()
  31.         new_topic.image_url = f'{fetch_host(request)}{new_topic.image.url}'
  32.         new_topic.user_created_topic = True
  33.         new_topic.save()
  34.  
  35.         message = {**serializer.data, 'message':'Successfully created'}
  36.         return Response(message, status=status.HTTP_201_CREATED)
  37.     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  38.  
  39.  
  40. @api_view(['PUT'])
  41. @permission_classes([IsAuthenticated])
  42. @authentication_classes([TokenAuthentication])
  43. @parser_classes([MultiPartParser, FormParser])
  44. def update_topic_view(request, id, format=None):
  45.     try:
  46.         topic = Topic.objects.get(id=id, author=request.user)
  47.     except Topic.DoesNotExist:
  48.         message = {'error': 'Topic not found.'}
  49.         return Response(message, status=status.HTTP_404_NOT_FOUND)
  50.  
  51.     serializer = TopicSerializer(topic, data=request.data)
  52.  
  53.     if serializer.is_valid():
  54.         serializer.save()
  55.         message = {**serializer.data, 'message':'Successfully created'}
  56.         return Response(message, status=status.HTTP_202_ACCEPTED)
  57.     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  58.  
  59.  
  60. @api_view(['POST'])
  61. @permission_classes([IsAuthenticated])
  62. @authentication_classes([TokenAuthentication])
  63. def delete_topic_view(request, id):
  64.     try:
  65.         topic = Topic.objects.get(id=id)
  66.     except Topic.DoesNotExist:
  67.         message = {'error': 'Topic not found.'}
  68.         return Response(message, status=status.HTTP_404_NOT_FOUND)
  69.    
  70.     topic.delete()
  71.  
  72.     message = {'message': f'{topic.name} has been deleted successfully.'}
  73.     return Response(message, status=status.HTTP_204_NO_CONTENT)
  74.  
  75.  
  76. @api_view(['GET'])
  77. @permission_classes([AllowAny])
  78. def post_list_view(request):
  79.     posts = Post.objects.all().prefetch_related('like', 'topic', 'author')
  80.     serializer = PostSerializer(posts, many=True)
  81.     return Response(serializer.data, status=status.HTTP_200_OK)
  82.  
  83.  
  84. @api_view(['GET'])
  85. @permission_classes([AllowAny])
  86. def post_detail_view(request, id):
  87.     try:
  88.         post = Post.objects.prefetch_related('topic', 'author', 'like').get(id=id)
  89.     except Post.DoesNotExist:
  90.         error = {'message':'Post not found.'}
  91.         return Response(error, status=status.HTTP_404_NOT_FOUND)
  92.    
  93.     serializer = PostSerializer(post)
  94.     author_profile_image_url = post.author.profile.image_url
  95.     usernames = [user.username for user in post.like.all()]
  96.  
  97.     data = {
  98.         **serializer.data,
  99.         'author_profile_image_url': author_profile_image_url,
  100.         'like':usernames,
  101.     }
  102.     return Response(data, status=status.HTTP_200_OK)
  103.  
  104.  
  105. @api_view(['POST'])
  106. @permission_classes([IsAuthenticated])
  107. @authentication_classes([TokenAuthentication])
  108. @parser_classes([MultiPartParser, FormParser])
  109. def create_post_view(request, format=None):
  110.     try:
  111.         topic = Topic.objects.get(name__iexact=request.data.get('topic'))
  112.     except Topic.DoesNotExist:
  113.         message = {'error': 'Topic not found.'}
  114.         return Response(message, status=status.HTTP_404_NOT_FOUND)
  115.    
  116.     serializer = PostSerializer(data=request.data)
  117.     if serializer.is_valid():
  118.         new_post = serializer.save()
  119.         new_post.author = request.user
  120.         new_post.topic = topic
  121.         new_post.image_url = f'{fetch_host(request)}{new_post.image.url}'
  122.         new_post.save()
  123.  
  124.         new_post.topic.update_total_post()
  125.  
  126.         message = {**serializer.data, 'message':'Successfully created'}
  127.         return Response(message, status=status.HTTP_201_CREATED)
  128.     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  129.  
  130.  
  131. @api_view(['PUT'])
  132. @permission_classes([IsAuthenticated])
  133. @authentication_classes([TokenAuthentication])
  134. @parser_classes([MultiPartParser, FormParser])
  135. def update_post_view(request, id, format=None):
  136.     user = request.user
  137.     post = Post.objects.filter(id=id, author=user).first()
  138.  
  139.     if post == None:
  140.         message = {'error': 'Post not found.'}
  141.         return Response(message, status=status.HTTP_404_NOT_FOUND)
  142.    
  143.     else:
  144.         serializer = PostSerializer(post, data=request.data)
  145.         if serializer.is_valid():
  146.             updated_post = serializer.save()
  147.             if serializer.validated_data.get('image'):
  148.                 updated_post.image_url = f'{fetch_host(request)}{updated_post.image.url}'
  149.             updated_post.save()
  150.  
  151.             message = {**serializer.data, 'message':'Successfully updated'}
  152.             return Response(message, status=status.HTTP_202_ACCEPTED)
  153.         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  154.  
  155.  
  156. @api_view(['DELETE'])
  157. @permission_classes([IsAuthenticated])
  158. @authentication_classes([TokenAuthentication])
  159. def delete_post_view(request, id):
  160.     user = request.user
  161.     post = Post.objects.filter(id=id, author=user).first()
  162.  
  163.     if post == None:
  164.         message = {'error':"Post not found"}
  165.         return Response(message, status=status.HTTP_404_NOT_FOUND)
  166.  
  167.     else:
  168.         post.delete()
  169.         post.topic.update_total_post()
  170.         message = {'message': f'Post has been deleted successfully.'}
  171.     return Response(message, status=status.HTTP_200_OK)
  172.  
  173.  
  174. @api_view(['POST'])
  175. @permission_classes([IsAuthenticated])
  176. @authentication_classes([TokenAuthentication])
  177. def update_post_like_view(request, id):
  178.     user = request.user
  179.  
  180.     try:
  181.         post = Post.objects.prefetch_related('like').get(id=id)
  182.     except Post.DoesNotExist:
  183.         message = {'error':'Post not found'}
  184.         return Response(message, status=status.HTTP_404_NOT_FOUND)
  185.    
  186.     if user not in post.like.all():
  187.         post.like.add(user)
  188.         post.save()
  189.         message = {'message': 'Submmision was successfull.'}
  190.         return Response(message, status=status.HTTP_200_OK)
  191.     message = {'error': 'You have already submited.'}
  192.     return Response(message, status=status.HTTP_400_BAD_REQUEST)
  193.  
  194.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement