def create_blog(request): """ Create a new blog. """ serializer = BlogSerializer(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)
def list_blogs(request): """ List blogs. """ next_page = 1 previous_page = 1 blogs = Blog.objects.all() page = request.GET.get('page', 1) paginator = Paginator(blogs, 10) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) serializer = BlogSerializer(data, context={'request': request}, many=True) if data.has_next(): next_page = data.next_page_number() if data.has_previous(): previous_page = data.previous_page_number() return Response({ 'data': serializer.data, 'count': paginator.count, 'numpages': paginator.num_pages, 'nextlink': '/api/blogs/?page=' + str(next_page), 'prevlink': '/api/blogs/?page=' + str(previous_page) })
def test_get_all_puppies(self): # get API response response = client.get(reverse('list_blogs')) # get data from db blogs = Blog.objects.all() serializer = BlogSerializer(blogs, many=True) self.assertEqual(response.data['data'], serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def blog_detail(request, pk): """ Retrieve, update or delete a code snippet. """ if request.user.is_authenticated: try: blog = Blog.objects.get(pk=pk) except Blog.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = BlogSerializer(blog) return Response(serializer.data) elif request.method == 'PUT': serializer = BlogSerializer(blog, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': blog.delete() return Response({'message': 'Blog were deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) return Response({'msg': "login required"}, status=status.HTTP_403_FORBIDDEN)
class WriterSerializer(serializers.ModelSerializer): pub_blogs = BlogSerializer(many=True) arch_blogs = BlogSerializer(many=True) saved_blogs = BlogSerializer(many=True) followers = MiniWriterSerializer(many=True) following = MiniWriterSerializer(many=True) class Meta: model = get_user_model() fields = [ "pk", "name", "username", "email", "bio", "dp", "is_superuser", "followers", "following", "pub_blogs", "arch_blogs", "saved_blogs", ]
def get(self, request, **kwargs): blog = Blog.objects.get(pk=kwargs["blog_pk"]) user = get_user_model().objects.get(pk=kwargs["writer_pk"]) if user in blog.saves.all(): blog.saves.remove(user) message( f"{user.name} ({user.pk}) unsaved the blog '{blog.title}' ({blog.pk})" ) else: blog.saves.add(user) message( f"{user.name} ({user.pk}) saved the blog '{blog.title}' ({blog.pk})" ) serializer = BlogSerializer(blog) return Response(status=status.HTTP_200_OK, data=serializer.data)
def blog_view(request): if request.method == 'GET': blogs = BlogModel.objects.all() serializer = BlogSerializer(blogs, many=True) return Response({ 'success': True, 'message': 'Get request fulfilled!! ', 'data': serializer.data }) if request.method == 'POST': return Response({ 'success': True, 'message': 'Post request fulfilled!!', 'data': '' }) return Response({ 'success': False, 'message': 'Invalid request', 'data': '' })
def blog_list(request): """ List all code contacts, or delete a contact. """ if request.user.is_authenticated: if request.method == 'GET': blogs = Blog.objects.all() serializer = BlogSerializer(blogs, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = BlogSerializer(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) else: return Response(status=status.HTTP_204_NO_CONTENT) return Response({'msg': "login required"}, status=status.HTTP_403_FORBIDDEN)
def get(self, request, format=None): blogs = BlogSerializer(Blog.objects.all(), many=True).data return Response(blogs)
def bo_add_blog_json_function(request): # parser_classes = (MultiPartParser, FormParser) input_json = request output_json = {} try: # ###### insert into blog ###### add_blog_param_var = { 'blog_title': input_json['blog_title'], 'blog_status': 1, 'added_by': str(input_json['blog_title']), 'last_modified_by': str(input_json['blog_title']) } blog_serializer_var = BlogSerializer(data=add_blog_param_var) if blog_serializer_var.is_valid(raise_exception=True): blog_serializer_var.save() # ###### insert into meta tag ###### meta_tag_list = [] for x in input_json['meta_tag_list']: meta_tag_list.append({ 'type_id': x['type_id'], 'content': x['tag_content'], 'added_by': 'admin', 'last_modified_by': 'admin', 'status': 1 }) meta_tag_serializer_var = MetaTagSerializer(data=meta_tag_list, many=True) if meta_tag_serializer_var.is_valid(raise_exception=True): inserted_meta_tag_list = meta_tag_serializer_var.save() # ###### insert into blog to meta tag mapping (one to many) ###### blog_to_meta_tag_map_params_var = [] for i in inserted_meta_tag_list: blog_to_meta_tag_map_params_var.append({ 'blog_id': blog_serializer_var.data['blog_id'], 'tag_id': i.tag_id, 'status': 1, 'added_by': str(input_json['blog_title']), 'last_modified_by': str(input_json['blog_title']) }) blog_to_meta_tag_map_serializer_var = BlogToMetaTagMappingSerializer( data=blog_to_meta_tag_map_params_var, many=True) if blog_to_meta_tag_map_serializer_var.is_valid( raise_exception=True): blog_to_meta_tag_map_serializer_var.save() # ###### insert into paragraphs ###### paragraph_list = [] for x in input_json['paragraph_list']: paragraph_list.append({ 'paragraph_body': x['paragraph_body'], 'added_by': 'admin', 'last_modified_by': 'admin', 'status': 1, }) add_paragraph_serializer_var = ParaGraphSerializer( data=paragraph_list, many=True) if add_paragraph_serializer_var.is_valid(raise_exception=True): inserted_paragraph_list = add_paragraph_serializer_var.save( ) # ###### insert into blog to paragraph mapping (one to many) ###### blog_to_paragraph_map_params_var = [] for i in inserted_paragraph_list: blog_to_paragraph_map_params_var.append({ 'blog_id': blog_serializer_var.data['blog_id'], 'paragraph_id': i.paragraph_id, 'status': 1, 'added_by': str(input_json['blog_title']), 'last_modified_by': str(input_json['blog_title']) }) blog_to_paragraph_map_serializer_var = BlogToParagraphMappingSerializer( data=blog_to_paragraph_map_params_var, many=True) if blog_to_paragraph_map_serializer_var.is_valid( raise_exception=True): blog_to_paragraph_map_serializer_var.save() # ###### insert into media ###### media_list = [] for x in input_json['paragraph_list']: media_list.append({ 'file_content': x['file_content'], 'file_caption': 'image', 'added_by': 'admin', 'last_modified_by': 'admin', 'status': 1 }) media_id_serializer_var = MediaSerializer( data=media_list, many=True) if media_id_serializer_var.is_valid( raise_exception=True): media_id_list = media_id_serializer_var.save() # ###### insert into paragraph to media mapping (one to many) ###### paragraph_to_media_map_params_var = [] j = 0 for i in media_id_list: paragraph_to_media_map_params_var.append({ 'paragraph_id': inserted_paragraph_list[j].paragraph_id, 'media_id': i.media_id, 'status': 1, 'added_by': str(input_json['blog_title']), 'last_modified_by': str(input_json['blog_title']) }) j = j + 1 paragraph_to_media_map_serializer_var = ParagraphToMediaMappingSerializer( data=paragraph_to_media_map_params_var, many=True) if paragraph_to_media_map_serializer_var.is_valid( raise_exception=True): paragraph_to_media_map_serializer_var.save() output_json['Status'] = "Success" output_json['Message'] = "Successfully added blog." return output_json except Exception as ex: output_json['Status'] = "Failure" output_json['Message'] = " Some internal issue blog not created successfully.Exception encountered: " + \ str(ex) return output_json
def list(self, request): queryset = BlogModel.objects.all() serializer = BlogSerializer(queryset, many=True) return Response(serializer.data)
def retrieve(self, request, pk=None): queryset = BlogModel.objects.all() if pk is not None: blog = get_object_or_404(queryset, pk=pk) serializer = BlogSerializer(blog) return Response(serializer.data)
def cool_blogs(self, request, pk=None): # Apply some business logic to get list of cool blog posts blogs = BlogModel.objects.filter(pk=2) sr = BlogSerializer(blogs, many=True) return Response({'data': sr.data})