def post(self, request, format=None): data = JSONParser().parse(request) serializer = BookSerializer(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 get(self, request): if request.method == 'OPTIONS': return JsonResponse({}) user = request.user recommendations = get_recommend_books(user) r1 = BookSerializer(recommendations["desc"], many=True) r2 = BookSerializer(recommendations["title"], many=True) r3 = BookSerializer(recommendations["review"], many=True) r4 = BookSerializer(recommendations["others"], many=True) r5 = BookSerializer(recommendations["genres"], many=True) desc = [] if len(r1.data) == 0 else r1.data title = [] if len(r2.data) == 0 else r2.data review = [] if len(r3.data) == 0 else r3.data others = [] if len(r4.data) == 0 else r4.data genres = [] if len(r5.data) == 0 else r5.data info = { "desc": desc, "title": title, "review": review, "others": others, "genres": genres } return JsonResponse(info)
def create(self, request): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) time.sleep(2) return Response(serializer.errors, status=400)
def book_add(request): if request.method == 'POST': serializer = BookSerializer(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 put(self, request, pk, format=None): book = self.get_object(pk) serializer = BookSerializer(book, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def book_add(request): if request.method == 'POST': serializer = BookSerializer(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 put(self, request, pk, format=None): book = self.get_object(pk) serializer = BookSerializer(book, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): book_serializer = BookSerializer(data=request.data) if book_serializer.is_valid(): saved_book_data = book_serializer.save() return Response(book_serializer.data, status=status.HTTP_201_CREATED) return Response(book_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_create_valid_book_should_work(self): """ We check deserialization process of a dictionary where we get a valid object model with validations succeded """ serializer = BookSerializer(data=self.expected) # Check validations works self.assertEquals(serializer.is_valid(), True) # Check object created is what we expect self.assertEquals(serializer.object, self.book) self.assertEquals(serializer.data['author'], 'author')
def test_read_only_fields_should_not_being_altered(self): """ We check that read only fields of serializers are not altered """ serializer = BookSerializer(self.book, data={'total_rating': 5}, partial=True) self.assertEquals(serializer.is_valid(), True) instance = serializer.save() self.assertEquals(serializer.errors, {}) # Avg_rate should be unchanged self.assertEquals(instance.total_rating, Decimal('0.00'))
def test_update_valid_book_should_work(self): """ We check deserialization process of a dictionary where we update an existing object model. Validations must work """ serializer = BookSerializer(self.book, data=self.expected) # Check validations works self.assertEquals(serializer.is_valid(), True) # Check object updated is what we expect self.assertEquals(serializer.object, self.book) self.assertEquals(serializer.data['author'], 'author')
def update(self, request, pk=None): time.sleep(3) try: item = Book.objects.get(pk=pk) except Book.DoesNotExist: return Response(status=404) serializer = BookSerializer(item, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400)
def update(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = BookSerializer(queryset, data=request.data) if serializer.is_valid(): serializer.save() return make_formatted_response( status_code=status.HTTP_200_OK, data=serializer.data, message=f'The book {queryset.name} was updated successfully') return make_formatted_response(status_code=status.HTTP_400_BAD_REQUEST, error=serializer.errors)
def post(self, request): book = request.data.get('book') serializer = BookSerializer(data=book) if serializer.is_valid(raise_exception=True): book_saved = serializer.save() return Response( { 'success': 'Book \'{book}\' added successfully'.format( book=book_saved.__str__(), ), }, status=201, )
def put(self, request, pk=None): try: book = Book.objects.get(pk=pk) except Book.DoesNotExist: return Response({'message': 'The book does not exist'}, status=status.HTTP_404_NOT_FOUND) book_serializer = BookSerializer(book, data=request.data) if book_serializer.is_valid(): book_serializer.save() return Response(book_serializer.data) return Response(book_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_books_view(request): #request.data['teste'] #request.data['sell_price'] = calcular_valor_por_margem(request.data['margem'], request.data['cost_price']) if request.method == "POST": serializer = BookSerializer(data=request.data) data = {} if serializer.is_valid(): serializer.save() data['success'] = "Book created with success" return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, book_id): book = get_object_or_404(Book.objects.filter(id=book_id)) book_upd = request.data.get('book') serializer = BookSerializer(instance=book, data=book_upd) if serializer.is_valid(raise_exception=True): book_saved = serializer.save() return Response( { 'success': 'Book \'{book}\' updated successfully'.format( book=book_saved.__str__(), ), }, status=204, )
def post(self, request): form = GoogleBookAPISearchForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data url = self.construct_url(cleaned_data) resp = requests.get(url).json() if resp: volumes = resp.json()["items"] for volume in volumes: volume_info = self.prepare_to_serialize(volume) if volume_info: serializer = BookSerializer(data=volume_info) if serializer.is_valid(): serializer.save() return redirect(reverse("expand"))
class LibrarySessionSerializer(serializers.ModelSerializer): book = BookSerializer() class Meta: model = LibraryBook fields = ["id", "book"]
class STUserSerializer(serializers.ModelSerializer): user = UserSerializer() bought_books = BookSerializer(many=True) class Meta: model = STUser fields = ('id', 'name', 'user', 'phone', 'bought_books')
def get(self, request, format=None): books = Book.objects.filter(~Q(owner = self.request.user.id)) if request.GET.get('search'): books = books.filter(title__icontains=self.request.GET['search']) serializer = BookSerializer(books, many=True) return Response(serializer.data)
class ColumnConfigSerializer(serializers.ModelSerializer): book = BookSerializer() topic = TopicDetailSerializer() class Meta: model = ColumnConfig fields = ('book', 'topic')
def update_books_view(request, slug): try: book = Book.objects.get(slug=slug) except Book.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "PUT": serializer = BookSerializer(book, data=request.data) data = {} if serializer.is_valid(): serializer.save() data['success'] = "Book updated with success" return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserSerializer(serializers.ModelSerializer): book = BookSerializer(many=True) class Meta: model = User #fields = "__all__" fields = ['id', 'last_name', 'first_name', 'book']
def test_get_book(self): response = self.client.get( reverse("book-details", kwargs={"pk": self.book_id})) expected = Book.objects.get(pk=self.book_id) serialized = BookSerializer(expected) self.assertEqual(response.data.get('data'), serialized.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def get(self, request, id,format=None): try: book = Book.objects.get(id=id) except Book.DoesNotExist: return Response("", status=status.HTTP_400_BAD_REQUEST) serializer = BookSerializer(book) return Response(serializer.data)
def test_ok(self): book_1 = Books.objects.create( title='Test1 Titile1', author_name='Test1 author1', description='Test1 description1' ) book_2 = Books.objects.create( title='Test2 Titile2', author_name='222aaaaaaaaaaaaaaaa', description='Test2 description2' ) data = BookSerializer([book_1, book_2], many=True).data expected_data = [ { 'id': book_1.id, 'title': 'Test1 Titile1', 'author_name': 'Test1 author1', 'description': 'Test1 description1' }, { 'id': book_2.id, 'title': 'Test2 Titile2', 'author_name': '222aaaaaaaaaaaaaaaa', 'description': 'Test2 description2', } ] self.assertEqual(expected_data, data)
class OrderSerializer(serializers.ModelSerializer): book = BookSerializer() class Meta: model = Order fields = '__all__' read_only_fields = ('creator', )
class RentalSerializer(ModelSerializer): client = ClientSerializer(read_only=True) book = BookSerializer(read_only=True) class Meta: model = Rental fields = '__all__'
def book_list(request, format=None): if request.method == 'GET': books = book.objects.all() serializer = BookSerializer(books, many=True) return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_view_book_detail(self, book, client): """Test retrieve book detail""" response = client.get(detail_url(book.id)) serializer = BookSerializer(book) assert response.status_code == status.HTTP_200_OK assert response.data == serializer.data
def all_books_view(request): book = Book.objects.all() if request.method == "GET": serializer = BookSerializer(book, many=True) return Response(serializer.data)
def libros(self, request, pk=None): editorial = self.get_object() libros = Book.objects.filter(editorial__id=editorial.id) serialized = BookSerializer(libros, many=True) if not libros: return Response(status=status.HTTP_404_NOT_FOUND, data={'message': 'Esta editorial no tiene libros'}) return Response(status=status.HTTP_200_OK, data=serialized.data)
def search(self, request): q = request.query_params.get('q') queryset = self.get_queryset() if q is not None: queryset = queryset.filter( Q(title__icontains=q) | Q(description__icontains=q)) serializer = BookSerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def __serialize_book(self, book, library, request, status=200): serializer = BookSerializer(book, context={ 'request': request, 'library': library, 'user': request.user, }) return Response(serializer.data, status=status)
def test_update_partial_book_should_work(self): """ We check deserialization process of a dictionary where we update some values of an existing object model We check both with partial True and False """ partial_data = {'author': 'partial'} serializer = BookSerializer(self.book, data=partial_data) # Check validations fails self.assertEquals(serializer.is_valid(), False) serializer = BookSerializer(self.book, data=partial_data, partial=True) self.assertEquals(serializer.is_valid(), True) # Check object created is what we expect self.assertEquals(serializer.object, self.book) self.assertEquals(serializer.data['author'], 'partial') # Notice that self.book is updated when serializing self.assertEquals(serializer.object.author, 'partial')
def post(self, request, format=None): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)