def serializer_put(request, requested_blog_id): blog = Blog.objects.get(id=requested_blog_id) serializer = BlogSerializer(blog, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
def post(self, request): serializer = BlogSerializer(data=request.data) if serializer.is_valid(): serializer.save() return create_response(data=serializer.data, status=status.HTTP_201_CREATED) return create_response(error=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request, format=None): payload = request.data payload['user_id'] = request.user.id serializer = BlogSerializer(data=request.data) if (serializer.is_valid()): serializer.save() obj = {"success": True, "message": "Blog created Successfully!"} return Response(obj, status=status.HTTP_201_CREATED) obj = {"success": False, "message": serializer.errors} return Response(obj, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None, **kwargs): data = request.data data['author'] = self.request.user.id serializer = BlogSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({"blog": serializer.data})
def blog_list_api(request): """ List all code blogs, or create a new blog. """ if request.method == 'GET': snippets = Blog.objects.all() serializer = BlogSerializer(snippets, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = BlogSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def get(self, request): getBlogs = Blog.objects.all() try: blogSerializer = BlogSerializer(getBlogs, many=True) return Response(blogSerializer.data, status=status.HTTP_200_OK) except: return Response(blogSerializer.errors, status.HTTP_403_FORBIDDEN)
class AuthorBlogSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) blogs = BlogSerializer(read_only=True, many=True, source='blog_set') user_details = UserSerializer(source='parent_user') class Meta: model = AppUser fields = '__all__'
def test_fields(self): serializer = BlogSerializer() self.assert_fields_required(True, serializer, self.required_fields) self.assert_fields_required(False, serializer, self.not_required_fields) self.assertEqual( len(serializer.fields), len(self.required_fields) + len(self.not_required_fields))
def list(self, request): blogs = Blog.objects.filter(created_by=request.user.id) data = BlogSerializer(blogs, many=True).data return response.Response({ 'data': data, 'user': request.user.username, 'id': request.user.id })
def blog_detail(request, pk): try: blog = Blog.objects.get(pk=pk) except blog.DoesNotExist: return JsonResponse({'message': 'The blog does not exist'}, status=status.HTTP_404_NOT_FOUND) # find blog by pk (id) if request.method == 'GET': blog_serializer = BlogSerializer(blog) return JsonResponse(blog_serializer.data) elif request.method == 'PUT': blog_data = JSONParser().parse(request) blog_serializer = BlogSerializer(blog, data=blog_data) if blog_serializer.is_valid(): blog_serializer.save() return JsonResponse(blog_serializer.data) return JsonResponse(blog_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # GET / PUT / DELETE blog elif request.method == 'DELETE': blog.delete() return JsonResponse({'message': 'blog was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT)
def get(self, request, site): try: blog = Blog.objects.get(site=site) except Blog.DoesNotExist: return create_response(error={"message": "Blog does not exist"}, status=status.HTTP_404_NOT_FOUND) serializer = BlogSerializer(blog) return create_response(data=serializer.data, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs): blogSerializer = BlogSerializer(data=request.data) if blogSerializer.is_valid(): blog = blogSerializer.save() for image in self.request.FILES.getlist('image'): blogImageSerializer = BlogImageSerializer(data={ 'blog': blog.id, 'image': image }) if blogImageSerializer.is_valid(): blogImageSerializer.save() else: return Response(blogImageSerializer.errors, status.HTTP_403_FORBIDDEN) else: return Response(blogImageSerializer.errors, status.HTTP_403_FORBIDDEN) return Response(blogSerializer.data, status.HTTP_201_CREATED)
def list(self, request, format=None): user = request.user queryset = Blog.objects.filter(user_id=user.id).all() serializer = BlogSerializer(queryset, many=True) obj = { "success": True, "data": serializer.data, } return Response(obj, status=status.HTTP_200_OK)
def blog_list_published(request): # Find all Blogs with published = True blogs = Blog.objects.filter(published=True) if request.method == 'GET': blogs_serializer = BlogSerializer(blogs, many=True) return JsonResponse(blogs_serializer.data, safe=False)
def update(self, request, pk=None): user = request.user queryset = Blog.objects.filter(user_id=user.id).get(pk=pk) if not queryset: obj = {"success": False, "message": "Blog Not Found!"} return Response(obj, status=status.HTTP_401_UNAUTHORIZED) payload = request.data payload['user_id'] = user.id serializer = BlogSerializer(queryset, data=payload) if (serializer.is_valid()): serializer.save() obj = {"success": True, "message": "Blog Updated Successfully!"} return Response(obj, status=status.HTTP_201_CREATED) obj = { "success": False, "message": serializer.errors, } return Response(obj, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None, **kwargs): """ Return a list of all blogs or questions or both. """ type_ = self.request.query_params.get('type', None) tag_name = self.request.query_params.get('tag_name', None) # Tagged item type specified if type_ != None and tag_name != None: target_type = ContentType.objects.get( app_label=type_, model=type_) items = target_type.model_class().objects.filter( tags__tag_name__contains=tag_name) if type_ == "blog": return Response([BlogSerializer(blog).data for blog in items]) elif type_ == "question": return Response([QuestionSerializer(question).data for question in items]) else: return Response("Unknow tagged item type", status=status.HTTP_400_BAD_REQUEST) # Tagged item type specified, return all elif type_ == None and tag_name != None: blogs = Blog.objects.filter(tags__tag_name__contains=tag_name) data = {"blogs": [BlogSerializer(blog).data for blog in blogs]} questions = Question.objects.filter(tags__tag_name__contains=tag_name) data.update({"questions": [QuestionSerializer(question).data for question in questions]}) return Response(data) # invalid parameters elif type_ != None and tag_name == None: return Response("tag name is not provided", status=status.HTTP_400_BAD_REQUEST) else: return Response("no query parameter is provided", status=status.HTTP_400_BAD_REQUEST)
def blog_list(request, **kwargs): """ List all code snippets, or create a new snippet. """ qs = request.META['QUERY_STRING'] q, l = qs.split("=") if request.method == 'GET': if (qs): snippets = Blog.objects.all()[:int(l)] else: snippets = Blog.objects.all() serializer = BlogSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False)
def blog_collection(request): if request.method == 'GET': blogs = Blog.objects.all() serializer = BlogSerializer(blogs, many=True) return Response(serializer.data) elif request.method == 'POST': data = {'title': request.data.get('title'), 'content': request.data.get('content')} serializer = BlogSerializer(data=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 retrieve(self, request, pk, format=None): user = request.user queryset = Blog.objects.filter(user_id=user.id).get(pk=pk) if not queryset: obj = {"success": False, "message": "Blog Not Found!"} return Response(obj, status=status.HTTP_401_UNAUTHORIZED) serializer = BlogSerializer(queryset) obj = { "success": True, "data": serializer.data, } return Response(obj, status=status.HTTP_200_OK)
def retrieve(self, request, *args, **kwargs): # get user instance = self.get_object() serializer = self.get_serializer(instance) # get recent blogs queryset_blogs = Blog.objects.filter( user=instance.user).order_by('-pub_date')[:3] serializer_blogs = BlogSerializer(queryset_blogs, context={'request': request}, many=True) return Response({ 'user': serializer.data, 'blogs': serializer_blogs.data })
def blog_list_api(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': blogs = Blog.objects.all() serializer = BlogSerializer(blogs, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = BlogSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def to_representation(self, value): if isinstance(value, Post): serializer = PostSerializer(value) elif isinstance(value, Comment): serializer = CommentSerializer(value) elif isinstance(value, Like): serializer = LikeSerializer(value) elif isinstance(value, Blog): serializer = BlogSerializer(value) elif isinstance(value, Submission): serializer = SubmissionSerializer(value) elif isinstance(value, Message): serializer = MessageSerializer(value) else: return value.__str__() return serializer.data
def blog_list(request): """" List all blogs """ if request.method =="GET": blogs=Blog.objects.all() serializer=BlogSerializer(blogs,many=True) return JsonResponse(serializer.data, safe=False) elif request.method =="POST": data = JSONParser().parse(request) serializer=BlogSerializer(data=data) if serializer.is_valid(): serializer.save() print(data) return JsonResponse(serializer.data, status=201) return JsonResponse (serializer.errors, status=400)
def blog_detail(request, pk): # find blog by id try: blog = Blog.objects.get(pk=pk) # retrive a single blog if request.method == 'GET': blog_serializer = BlogSerializer(blog) return JsonResponse(blog_serializer.data) # Update a Blog by the id in the request elif request.method == 'PUT': blog_data = JSONParser().parse(request) blog_serializer = BlogSerializer(blog, data=blog_data) if blog_serializer.is_valid(): blog_serializer.save() return JsonResponse(blog_serializer.data) return JsonResponse(blog_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Delete a Blog with the specified id elif request.method == 'DELETE': blog.delete() return JsonResponse({'message':'Blod was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) except Blog.DoesNotExist: return JsonResponse({'message':'The blog does not exist'}, status=status.HTTP_404_NOT_FOUND)
def type_blog(self, request, pk): blog_type = get_object_or_404(BlogType, pk=pk) blogs_all_list = Blog.objects.filter(blog_type=blog_type).all() paginator = CustomPagination() page = paginator.paginate_queryset(blogs_all_list, request) serializer = BlogSerializer(page, many=True, context={'request': request}) data = serializer.data return Response({ 'links': { 'next': paginator.get_next_link(), 'previous': paginator.get_previous_link() }, 'count': paginator.page.paginator.count, 'results': data, 'page_size': paginator.page_size, 'current_page': paginator.page.number, 'id': pk, 'type_name': blog_type.type_name })
def get(self, request, id): paginator = PageNumberPagination() tag = Tag.objects.get(id=id) tag_serializer = TagSerializer(tag) query = request.GET.get('q', ' ') if query == 'courses': courses = Course.objects.filter(tags=tag) course_result_page = paginator.paginate_queryset(courses, request) course_serializer = CourseSerializer(course_result_page, many=True) return Response( { "tag": tag_serializer.data, "courses": course_serializer.data }, HTTP_200_OK) elif query == 'blogs': blogs = Blog.objects.filter(tags=tag) blog_result_page = paginator.paginate_queryset(blogs, request) blog_serializer = BlogSerializer(blogs, many=True) return Response( { "tag": tag_serializer.data, "blogs": blog_serializer.data }, HTTP_200_OK) elif query == 'clips': clips = Clip.objects.filter(tags=tag) clip_result_page = paginator.paginate_queryset(clips, request) clip_serializer = ClipSerializer(clips, many=True) return Response( { "tag": tag_serializer.data, "clips": clip_serializer.data }, HTTP_200_OK) else: return Response({"tag": tag_serializer.data}, HTTP_200_OK)
def search(self, request): search_text = request.GET.get('q') raw_sql = f"select * from blog_blog where match(title, content) AGAINST ('{search_text}' IN BOOLEAN MODE)" blogs = Blog.objects.raw(raw_sql) if not search_text: blogs = [] paginator = CustomPagination() page = paginator.paginate_queryset(list(blogs), request) serializer = BlogSerializer(page, many=True, context={'request': request}) data = serializer.data return Response({ 'links': { 'next': paginator.get_next_link(), 'previous': paginator.get_previous_link() }, 'count': paginator.page.paginator.count, 'results': data, 'page_size': paginator.page_size, 'current_page': paginator.page.number, 'search_text': search_text, })
def blog_detail_api(request, blog_id): """ Retrieve, update or delete a code snippet. """ try: blog = Blog.objects.get(id=blog_id) except Blog.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = BlogSerializer(blog) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = BlogSerializer(blog, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': blog.delete() return HttpResponse(status=204)
def blogs_list(request): # GET list of blogs, POST a new blog, DELETE all blogs if request.method == 'POST': blog_data = JSONParser().parse(request) blog_serializer = BlogSerializer(data=blog_data) if blog_serializer.is_valid(): blog_serializer.save() return JsonResponse(blog_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(blog_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'GET': blogs = Blog.objects.all() title = request.GET.get('title', None) if title is not None: blogs = blogs.filter(title__icontains=title) blogs_serializer = BlogSerializer(blogs, many=True) return JsonResponse(blogs_serializer.data, safe=False)
def blog_list(request): # retrive all blogs if request.method == 'GET': blogs = Blog.objects.all() title = request.GET.get('title', None) if title is not None: blogs = blogs.filter(title_icontains=title) blogs_serializer = BlogSerializer(blogs, many=True) return JsonResponse(blogs_serializer.data, safe=False) # 'safe=False' for objects serialization # delete all blogs elif request.method == 'DELETE': count = Blog.objects.all().delete() return JsonResponse({'message': '{} Blogs were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT) # Create and save new blog elif request.method == 'POST': blog_data = JSONParser().parse(request) blog_serializer = BlogSerializer(data=blog_data) if blog_serializer.is_valid(): blog_serializer.save() return JsonResponse(blog_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(blog_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def cool_blogs(self, request, pk=None): blogs = BlogModel.objects.filter(pk=pk) sr = BlogSerializer(blogs, many=True) return Response({'data': sr.data})