Ejemplo n.º 1
0
 def post(self,request,format=None):
     serializer= ProductSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data,status=status.HTTP_202_ACCEPTED)
     else:
         return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 2
0
def category_products(request, category_id):
    try:
        category = Category.objects.get(id=category_id)
    except Category.DoesNotExist as e:
        return Response({'error': str(e)})

    if request.method == 'GET':
        products = category.product_list.all()
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = CategorySerializer(instance=category, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response({'error': serializer.errors})

    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'error': serializer.errors},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 3
0
 def put(self, request, product_id):
     product = self.get_object(product_id)
     serializer = ProductSerializer(instance=product, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
     return Response({"error": serializer.errors})
Ejemplo n.º 4
0
 def put(self, request, id):
     product = self.get_product(id)
     serializer = ProductSerializer(instance=product, data=json.loads(request.body))
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 5
0
def import_unisport_data():
    """Import unisport data from their api to the db."""

    unisport_api_uri = "https://www.unisport.dk/api/products/batch/"
    products_list_param = "?list=194742,193638,197237,188894,188896,189214,\
    194824,197250,194368,194477,194986,185253,197236,185117,187424,185866,\
    187743,194813,193639,187972,194923,194646,173445,193637,187744,200197,\
    193539,170478,194753,188893,181372,187477,193959,189188,197235,187812,\
    197242,168029,187425,194823"

    import_url = f"{unisport_api_uri}{products_list_param}"

    response = requests.get(url=import_url, timeout=5)

    def product_generator(products):
        for product in products:
            yield product

    with transaction.atomic():
        Product.objects.all().delete()
        for product in product_generator(response.json().get('products')):
            product_serializer = ProductSerializer(data=product)
            try:
                product_serializer.is_valid()
            except AssertionError as e:
                logger.info(product_serializer.errors)
            try:
                product_serializer.save()
                logger.info(f"product {product.get('id')} imported")
            except IntegrityError:
                logger.error(f"could not import product {product.get('id')}")
                continue
        return True
Ejemplo n.º 6
0
def admin_edit(request):
    validation = validate(request)
    if (validation != True):
        return validation

    if (request.method != 'POST'):
        raise Http404('No such method')

    pr = None
    if request.POST['id'] != 'new':
        pr = Product.objects.get(id=int(request.POST['id']))

    serializer = ProductSerializer(pr, data=request.POST)

    if not serializer.is_valid():
        response = HttpResponse('Invalid product object')
        response.status_code = 400
        return response
    serializer.save()

    if request.POST['id'] == 'new':
        os.mkdir(os.path.join(settings.MEDIA_ROOT, str(serializer.data['id'])))
        copy(
            os.path.join(settings.STATIC_ROOT, 'img', 'noimg.jpg'),
            os.path.join(settings.MEDIA_ROOT, str(serializer.data['id']),
                         '0.jpg'))

    return HttpResponse(serializer.data['id'])
 def put(self, request, pk, format=None):
     cat = Product.objects.get(id=pk)
     serializer = ProductSerializer(cat, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 8
0
def set_products(request):
    # dates = pd.read_csv('D:\Programming\PpP\web\cat.csv')
    dates = pd.read_csv(
        'https://docs.google.com/spreadsheets/d/e/2PACX-1vSgzUi6BNlGD2U6RmJcvT2kiszysNj9WISt746Jo67wtwD2DVJb-Iuwrkj6hL6bgDU1KotRaOS_IJL3/pub?gid=1763850928&single=true&output=csv'
    )

    name = dates['name'].values
    price = dates['price'].values
    description = dates['description'].values
    rating = [random.randint(1, 10) for i in range(len(name))]
    likes = dates['likes'].values
    views = dates['views'].values
    category_id = dates['category_id'].values

    for i in range(len(name)):
        di = {
            'name': name[i],
            'price': price[i],
            'description': description[i],
            'rating': rating[i],
            'likes': likes[i],
            'views': views[i],
            'category_id': category_id[i]
        }
        serializer = ProductSerializer(data=di)
        if serializer.is_valid():
            serializer.save()
            print('Good')
        else:
            print('Bad')
            return JsonResponse(serializer.errors)
    return JsonResponse({'Message': 'Good'})
Ejemplo n.º 9
0
    def post(self, request):
        serializer = ProductSerializer(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)
Ejemplo n.º 10
0
 def post(self, request):
     serializer = ProductSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response({'error': serializer.errors},
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 11
0
 def put(self, request, product_id):
     product = self.get_object(product_id)
     serializer = ProductSerializer(instance=product, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response({'error': serializer.errors})
Ejemplo n.º 12
0
 def put(self, request, product_id):
     product = self.get_object(product_id)
     serializer = ProductSerializer(instance=product, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_426_UPGRADE_REQUIRED)
     return Response({'error': serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE)
Ejemplo n.º 13
0
 def put(self,request,pk,format=None):
     products=self.get_object(pk)
     serializer=ProductSerializer(products,data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data,status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 14
0
 def create(self, request):
     slr = ProductSerializer(data=request.data,
                             context={'request': request})
     if slr.is_valid():
         slr.save()
         return Response(slr.data)
     else:
         return Response(slr.errors, status=400)
Ejemplo n.º 15
0
 def put(self, request, pk):
     product = self.get_object(pk)
     serializer = ProductSerializer(product, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     else:
         return Response(status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 16
0
 def post(self, request):
     serializer = ProductSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         response_data = {}
         response_data["success"] = "True"
         response_data["message"] = "Settings created successfully."
         return Response(response_data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 17
0
 def update(self, request, pk=None):
     product = get_object_or_404(Product, pk=pk)
     slr = ProductSerializer(data=request.data,
                             instance=product,
                             context={'request': request})
     if slr.is_valid():
         slr.save()
         return Response(slr.data)
     else:
         return Response(slr.errors, status=400)
Ejemplo n.º 18
0
    def put(self, request, pk):
        product = get_object_or_404(Product, pk=pk)
        serializer = ProductSerializer(instance=product, data=request.data)
        if serializer.is_valid():
            serializer.save()
            logger.info(f'Product with ID {serializer.instance} was updated')
            logger.debug(f'Product with ID {serializer.instance} was updated')
            return Response(serializer.data)

        logger.error(f'Product with ID {serializer.instance} cannot be updated')
        return Response(serializer.errors, status=500)
Ejemplo n.º 19
0
def products_list(request):
    if request.method == 'GET':
        products = Product.objects.all()
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'error': serializer.errors}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 20
0
def category_product(request, pk):
    if request.method == 'GET':
        products = Product.objects.filter(category_id=pk)
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 21
0
def products_list(request):
    if request.method == 'GET':
        vacancies = Product.objects.all()
        serializer = ProductSerializer(vacancies, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'errors': serializer.errors},
                        status=status.HTTP_501_NOT_IMPLEMENTED)
Ejemplo n.º 22
0
def product_list(request, format=None):
    if request.method == 'GET':
        products = Products.objects.all()
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 23
0
def products_list(request):
    if request.method == 'GET':
        products = Product.objects.all()
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        data = request.data
        serializer = ProductSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response({'error': wrong})
Ejemplo n.º 24
0
 def post(self, request, id, format=None):
     serializer = ProductSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         response = Response(serializer.data,
                             status=status.HTTP_201_CREATED)
         Log.objects.create(request=request.get_full_path,
                            response=response)
         return response
     response = Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
     Log.objects.create(request=request.get_full_path, response=response)
     return response
Ejemplo n.º 25
0
def product_detail(request, product_id):
    product = get_object_or_404(Product,id=product_id)
    if request.method == 'GET':
        serializer = ProductSerializer(product)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = ProductSerializer(instance=product, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response({'errors':serializer.errors})
    elif request.method == 'DELETE':
        product.delete()
        return Response({'deleted':True})
Ejemplo n.º 26
0
 def put(self, request):
     aid = request.GET.get('aid')
     ad = Product.objects.get(id=aid)
     serializer = ProductSerializer(ad, data=request.data)
     # validate and update
     if serializer.is_valid():
         serializer.save()
         response_data = {}
         response_data["success"] = "True"
         response_data["message"] = "Settings updated successfully."
         return Response(response_data, status=status.HTTP_200_OK)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 27
0
    def put(self, request, company_id, pk):
        if pk == '0' or company_id == '0':
            return JsonResponse({'detail': 'ID must be greater than zero.'},
                                status=status.HTTP_400_BAD_REQUEST)

        product = Product.objects.get(company_id=company_id, pk=pk)
        request.data["company"] = company_id
        serializer = ProductSerializer(product,
                                       data=request.data,
                                       partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 28
0
def product_single(request, id, format=None):
    product = get_object_or_404(Products, id=id)
    if  request.method == 'GET':
        serializer = ProductSerializer(product)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = ProductSerializer(product, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        product.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Ejemplo n.º 29
0
def product_list(request):
    """
    List all code products, or create a new product.
    """
    if request.method == 'GET':
        products = Product.objects.all()
        serializer = ProductSerializer(products, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ProductSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 30
0
def product_list(request):
    """
    List all products, or create a new snippet.
    """
    if request.method == 'GET':
        products = Product.objects.all()
        serializer = ProductSerializer(products, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ProductSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 31
0
def product_by_category(request, pk):
    try:
        category = Category.objects.get(id=pk)
    except Category.DoesNotExist as e:
        return Response({'error': str(e)})

    if request.method == 'GET':
        serializer = ProductSerializer(category.products.all(), many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'error': serializer.errors},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 32
0
def actualizar(request, pk):
    '''Definición de método PUT para actualizar'''
    try:
        producto = Product.objects.get(pk=pk)
    except Product.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'PUT':
        serializer = ProductSerializer(producto, data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            data = serializer.data
            data['reponse'] = 'Producto modificado satisfactoriamente'
            return Response(data)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 33
0
def product_detail(request, product_id):
    try:
        vacancies = Product.objects.get(id=product_id)
    except Product.DoesNotExist as e:
        return Response({'error': str(e)})

    if request.method == 'GET':
        s = ProductSerializer(vacancies)
        return Response(s.data)
    elif request.method == 'PUT':
        s = ProductSerializer(instance=vacancies, data=request.data)
        if s.is_valid():
            s.save()
            return Response(s.data)
        return Response({'error': s.errors})
    elif request.method == 'DELETE':
        vacancies.delete()
        return JsonResponse({'deleted': True})
Ejemplo n.º 34
0
def product_detail(request, pk):
    """
    Retrieve, update or delete a product.
    """
    try:
        product = Product.objects.get(pk=pk)
    except Product.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ProductSerializer(product)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = ProductSerializer(product, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        product.delete()
        return HttpResponse(status=204)