Exemplo n.º 1
0
 def put(self, request, pk):
     category = self.get_object(pk)
     serializer = CategorySerializer(category, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 2
0
 def post(self, request):
     request.data["company"] = request.user.company.id
     serializer = CategorySerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
 def addNewCategory(self, data):
     if 'admin' in data:
         serializer = CategorySerializer(data=data)
         if serializer.is_valid():
             serializer.save()
             return
         else:
             serializer.errors
             return
     token = data['token']
     user = Token.objects.get(key=token).user
     if user:
         if user.has_perm():
             data = {'name': data['category']}
             serializer = CategorySerializer(data=data)
             if serializer.is_valid():
                 serializer.save()
                 return {'result': 'success'}
             else:
                 return {'error': 'Taka nazwa kategorii już istnieje'}
         else:
             return {
                 'error': 'Nie masz uprawnień do wykonania tej czynności'
             }
     else:
         return {'error': 'Nie masz uprawnień do wykonania tej czynności'}
Exemplo n.º 4
0
    def post(self, request):
        serializer = CategorySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()

            # Send email 
            email_sub = 'Category Created'
            email_msg = 'New Category Name: {}'.format(serializer.data.get('name'))
            # trigger_email.delay(email_sub, email_msg)

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 5
0
 def get(self, request):
     try:
         categories = Category.objects.all()
     except Category.DoesNotExist:
         raise Http404
     serializer = CategorySerializer(categories, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Exemplo n.º 6
0
class Categories(ListModelMixin,
                CreateModelMixin,
                GenericAPIView):

    permission_classes = [IsStaffOrReadOnly]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    @swagger_auto_schema(
        responses={
            200: CategorySerializer(),
            204: 'No Content'
        }
    )
    def get(self, request, *args, **kwargs):
        """
        Category List

        Return all available category.<br>
        Will use 204 status code if result is empty.

        ### Permission:
        * Allow Any
        """

        qs = self.list(request, *args, **kwargs)
        return qs if qs.data else Response(status=status.HTTP_204_NO_CONTENT)

    @swagger_auto_schema(
        responses={
            201: CategorySerializer(),
            400: 'Bad Request',
            401: 'Invalid User\'s Credential',
            403: 'You Do Not Have Permission To Perform This Action'
        }
    )
    def post(self, request, *args, **kwargs):
        """
        Create Category

        Create a new category.

        ### Permission:
        * Staff Only
        """

        return self.create(request, *args, **kwargs)
Exemplo n.º 7
0
def category_list(request):
    """
    List all categories.
    """
    if request.method == 'GET':
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        return Response(serializer.data)
Exemplo n.º 8
0
def category_list(request):
    # GET list of Category, POST a new Category, DELETE all Category
    if request.method == 'GET':
        category = Category.objects.all() 
        
        name = request.GET.get('name', None)
        if name is not None:
            category = category.filter(name__icontains=name)
        
        category_serializer = CategorySerializer(category, many=True)
        return JsonResponse(category_serializer.data, safe=False)
        
        # 'safe=False' for objects serialization
    elif request.method == 'POST':
        # parser_classes = (FormParser, MultiPartParser, JSONParser)
        # category_data = MultiPartParser().parse(request)
        category_serializer = CategorySerializer(data=request.data)
        if category_serializer.is_valid():
            category_serializer.save()
            return JsonResponse(category_serializer.data, status=status.HTTP_201_CREATED) 
        return JsonResponse(category_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        count = Category.objects.all().delete()
        return JsonResponse({'message': '{} Categories was/were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 9
0
    def test_successful_retrieve_categories_by_manager(self):
        """Test success retrieve categories by manager"""

        Category.objects.create(name='Toys')
        Category.objects.create(name='Ladies Ware')

        res = self.client.get(CATEGORIES_URL)
        self.assertEqual(res.status_code, status.HTTP_200_OK)

        categories = Category.objects.all().order_by('name')
        serializer = CategorySerializer(categories, many=True)

        self.assertEqual(res.data, serializer.data)
Exemplo n.º 10
0
    def test_successful_retrieve_categories_by_non_manager(self):
        """Test success retrieve categories by non-manager"""

        Category.objects.create(name='T-shirts')
        Category.objects.create(name='Hardware')

        self.client = APIClient()
        self.client.force_authenticate(self.cashier)
        res = self.client.get(CATEGORIES_URL)
        self.assertEqual(res.status_code, status.HTTP_200_OK)

        categories = Category.objects.all().order_by('name')
        serializer = CategorySerializer(categories, many=True)

        self.assertEqual(res.data, serializer.data)
Exemplo n.º 11
0
class OutletProductSerializer(serializers.ModelSerializer):
    from product.serializers import CategorySerializer

    id = serializers.IntegerField(source='product.id')
    name = serializers.CharField(source='product.name')
    category = CategorySerializer(source='product.category')
    sku_code = serializers.CharField(source='product.sku_code')
    hsn = serializers.CharField(source='product.hsn')
    uom = serializers.CharField(source='product.uom.name')
    taxations = OutletTaxSerializer(many=True, allow_null=True)

    class Meta:
        from .models import OutletProduct

        model = OutletProduct
        fields = ('id', 'name', 'category', 'sku_code', 'hsn', 'uom', 'mrp',
                  'taxations')
Exemplo n.º 12
0
def category_detail(request, pk):
    # find category by pk (id)
    try: 
        category = Category.objects.get(pk=pk) 
        if request.method == 'GET': 
            category_serializer = CategorySerializer(category) 
            return JsonResponse(category_serializer.data)
        elif request.method == 'PUT': 
            category_serializer = CategorySerializer(category, data=request.data) 
            if category_serializer.is_valid(): 
                category_serializer.save() 
                return JsonResponse(category_serializer.data) 
            return JsonResponse(category_serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
        elif request.method == 'DELETE': 
            category.delete() 
            return JsonResponse({'message': 'Category was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT)
    except Category.DoesNotExist: 
        return JsonResponse({'message': 'The Category does not exist'}, status=status.HTTP_404_NOT_FOUND) 
Exemplo n.º 13
0
 def test_get_all_categories(self):
     response = self.client.get('/api/v1/categories/')
     categories = CategorySerializer(Category.objects.all(), many=True)
     self.assertEqual(response.data, categories.data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemplo n.º 14
0
class CategoryDetail(RetrieveModelMixin,
                    UpdateModelMixin,
                    DestroyModelMixin,
                    GenericAPIView):

    permission_classes = [IsStaffOrReadOnly]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    @swagger_auto_schema(
        responses={
            200: CategorySerializer(),
            404: 'No Category With That ID Found'
        }
    )
    def get(self, request, *args, **kwargs):
        """
        Detail Category

        Return the detail of category with requested id.<br>
        Return 404 if no category with that id is found.

        ### Permission:
        * Allow Any
        """
        return self.retrieve(request, *args, **kwargs)

    @swagger_auto_schema(
        request_body=CategorySerializer(),
        responses={
            200: CategorySerializer(),
            400: 'Bad Request',
            401: 'Invalid User\'s Credential',
            403: 'You Do Not Have Permission To Perform This Action',
            404: 'No Category With That ID Found'
        }
    )
    def put(self, request, *args, **kwargs):
        """
        Update Category

        Update category that the id mentioned, returned the updated category if succesfull.<br>
        Return 404 if no category with that id is found.

        ### Permission:
        * Staff Only
        """
        return self.update(request, *args, **kwargs)

    @swagger_auto_schema(
        responses={
            204: 'Category Succesfully Deleted',
            400: 'Bad Request',
            401: 'Invalid User\'s Credential',
            403: 'You Do Not Have Permission To Perform This Action',
            404: 'No Category With That ID Found'
        }
    )
    def delete(self, request, *args, **kwargs):
        """
        Delete Category

        Delete category that the id mentioned, then returned 204 if succesfull.<br>
        Return 404 if no category with that id is found.

        ### Permission:
        * Staff Only
        """
        return self.destroy(request, *args, **kwargs)
Exemplo n.º 15
0
 def get(self, request, format=None):
     categories = Category.objects.all()
     serializer = CategorySerializer(categories, many=True)
     return Response(serializer.data)
Exemplo n.º 16
0
 def get(self, _, pk):
     category = self.get_object(pk)
     serializer = CategorySerializer(category, context={'request': _})
     return Response(serializer.data)
Exemplo n.º 17
0
 def get_categories(self, obj):
     return CategorySerializer(obj.categories.all(), many=True).data
Exemplo n.º 18
0
 def get(self, request):
     categories = Category.objects.all()
     category_filter = CategoryFilter(request.GET, queryset=categories)
     serializer = CategorySerializer(category_filter.qs, many=True, context={'request': request})
     return Response(serializer.data)
Exemplo n.º 19
0
 def get(self, request):
     categories = Category.objects.exclude(id=1)
     serializer = CategorySerializer(categories, many=True)
     return Response(serializer.data)