def create(self, request):
     Item_all_obj = ItemSerializer(data=request.data)
     if Item_all_obj.is_valid():
         new_obj = Item_all_obj.save()
         new_obj_ser = ItemSerializer(new_obj)
         return Response(new_obj_ser.data)
     else:
         return Response(new_obj_ser.errors)
Beispiel #2
0
class MyItemSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=False)
    item = ItemSerializer(read_only=True, required=False)

    class Meta:
        model = MyItem
        fields = "__all__"
Beispiel #3
0
    def get(self, request, *args, **kwargs):

            user = self.get_user()

            ordered_items = list()

            #orders_ = self.model.objects.all()

            orders = BuyerOrder.objects.filter(user = user) 

            for i, obj in enumerate(orders) :
                order_info = obj.item

                # Every Item has info about the users(field) how posted it
                # That user info can be used to get sellerprofile

                seller_info = SellerProfile.objects.get(user = obj.item.user)


                ordered_items.append( {"placed" : obj.placed,
                                        "Order Satus"  : obj.order_sat,
                                        "Info" : ItemSerializer(order_info).data,
                                        "seller" : SellerProfileSerializer(seller_info).data
                                        }
                                        )


            res = {
            "status": 'success',
            "code": status.HTTP_200_OK,
            "message": 'Fteched successfully',
            "ordered_items" : ordered_items,
            }

            return Response(res , status=status.HTTP_200_OK)
Beispiel #4
0
class CartItemSerializer(ModelSerializer):
    total_price = serializers.SerializerMethodField('_get_total_price')
    item = ItemSerializer(read_only=True)
    price = serializers.DecimalField(max_digits=10,
                                     decimal_places=2,
                                     required=False)

    class Meta:
        model = CartItem
        fields = ('id', 'item', 'item_id', 'price', 'quantity', 'total_price')

    def _get_total_price(self, cart_item):
        return cart_item.price * int(cart_item.quantity)

    def create(self, validated_data):
        request = self.context.get('request')
        item = Item.objects.get(id=request.data['item'])
        cart = request.user.current_cart
        cart_item = CartItem(
            item=item,
            price=item.price,
            cart_id=cart.id,
            item_id=item.id,
            quantity=request.data['quantity'],
        )
        cart_item.save()
        cart.items.add(item)
        cart.save()
        return cart_item
Beispiel #5
0
 def test(self):
     response = self.client.get(self.url)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(
         response.data,
         ItemSerializer(self.item).data
     )
Beispiel #6
0
    def fix(self, request, pk=None):
        """moves Item from the current state to the next"""
        item = self.get_object()

        try:
            item.fix()
        except InvalidStateTransitionError as ex:
            return Response(
                data={
                    'error': str(ex)
                },
                status=status.HTTP_400_BAD_REQUEST,
                exception=True
            )
        else:
            # response should have current Item values and success message
            serializer = ItemSerializer(
                item,
                context={
                    'request': request
                }
            )
            response_data = serializer.data
            response_data['status'] = 'Item fixed'
            return Response(response_data)
    def get(self, request, *args, **kwargs):

            user = self.get_user()

            _items = list()

            #orders_ = self.model.objects.all()

            orders = Item.objects.filter(user = user) 

            for i, obj in enumerate(orders) :
                _items.append( { 
                                        "Info" : ItemSerializer(obj).data,
                                        }
                                        )


            res = {
            "status": 'success',
            "code": status.HTTP_200_OK,
            "message": 'Fteched successfully',
            "items" : _items,
            }

            return Response(res , status=status.HTTP_200_OK)
Beispiel #8
0
class PromoSerializer(serializers.ModelSerializer):

    items = ItemSerializer(many=True)

    class Meta:
        model = Promo
        fields = ('title', 'due_date', 'start_date', 'cashback_rub',
                  'items', 'lower_bound_rub')
Beispiel #9
0
    def retrieve(self, request, pk=None):
        try:
            item = Item.objects.get(id=pk)
        except Item.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        serializer = ItemSerializer(item)

        return Response(serializer.data)
Beispiel #10
0
    def update(self, request, pk=None):
        try:
            item = Item.objects.get(id=pk)
            print(item)
            item.name = request.data.get('name')
            item.save()
        except Item.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        serialized = ItemSerializer(item)

        return Response(serialized.data)
Beispiel #11
0
    def __init__(self, *args, **kwargs):
        # Lazy loading, solving circular import errors
        from knacks.serializers import KnackSerializer
        from items.serializers import ItemSerializer

        self.fields['knacks'] = KnackSerializer(many=True,
                                                read_only=True,
                                                depth=-1)
        self.fields['items'] = ItemSerializer(many=True,
                                              read_only=True,
                                              depth=-1)

        super(ProfileSerializer, self).__init__(*args, **kwargs)
Beispiel #12
0
def category_search(request, pk, format=None):
    """Retrieve, update or delete a code category."""
    try:
        category = Category.objects.get(name=pk)
    except Category.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        items = Item.get_active(category=category)
        print("items")
        serializer = ItemSerializer(items, many=True)
        # serializer = ItemsCategorySerializer(items, many=True)
        return Response(serializer.data)
Beispiel #13
0
def item_list(request, format=None):
    """List all code items, or create a new item."""
    if request.method == 'GET':
        items = Item.get_active()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ItemSerializer(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)
Beispiel #14
0
def ItemList(request):

    if request.method == 'GET':
        items = Items.objects.all()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ItemSerializer(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)
Beispiel #15
0
    def create_transaction(self, request, pk=None):
        """creates a Transaction for the given Item"""
        item = self.get_object()
        transaction = item.create_transaction()

        # response should have current Item values and success message
        serializer = ItemSerializer(
            item,
            context={
                'request': request
            }
        )
        response_data = serializer.data
        response_data['status'] = 'Transaction {} created'.format(transaction.id)
        return Response(response_data)
Beispiel #16
0
    def post(self, request: Request, product_id: int, format: str = None):
        try:
            Product.objects.filter(id=product_id, seller=request.user).exists()
        except Item.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        request.data.update({"product": product_id})

        serializer = ItemSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #17
0
class CartItemSerializer(serializers.ModelSerializer):
    item = ItemSerializer(read_only=True)
    item_id = serializers.PrimaryKeyRelatedField(
        source='item',
        queryset=Item.objects.all(),
    )

    class Meta:
        model = CartItem
        fields = (
            'id',
            'item',
            'quantity',
            'item_id',
            'price',
            'total_price',
        )
        read_only_fields = (
            'price',
            'total_price',
            'item',
        )
        extra_kwargs = {
            'quantity': {
                'required': True
            },
        }

    def validate_quantity(self, value):
        if value <= 0:
            raise serializers.ValidationError("Not valid")
        return value

    def create(self, validated_data):
        cart_item = CartItem(
            item=validated_data['item'],
            cart=self.context['request'].user.current_cart,
            quantity=validated_data['quantity'],
            price=validated_data['item'].price,
        )
        cart_item.save()
        return cart_item
    def post(self, request, *args, **kwargs):


            item_serializer = self.get_serializer(data = request.data  )

            item_serializer.is_valid(raise_exception=True)

            item = item_serializer.save(user = self.get_object(),
                                        item_name_normalized = normalize_text(request.data["item_name"]),
                                        top_product = products_info.IsTopProduct(),
                                        featured_product = products_info.IsFeaturedProduct(),)
            res = {
            "status": 'success',
            "code": status.HTTP_200_OK,
            "message": 'Item Saved Successfully',
            "item": ItemSerializer(item, context=self.get_serializer_context()).data
            
            }

            return Response(res , status=status.HTTP_200_OK)
 def list(self, request, *args, **kwargs):
     to_be_shown = []
     latitude = radians(float(request.query_params.get('latitude')))
     longitude = radians(float(request.query_params.get('longitude')))
     queryset = Item.objects.all()
     for i in queryset:
         lat1 = radians(i.latitude)
         long1 = radians(i.longitude)
         dlat = latitude - lat1
         dlon = longitude - long1
         # a = sin(dlat / 2)**2 + cos(latitude) * cos(i.latitude) * sin(dlong/ 2)**2
         a = sin(dlat / 2)**2 + cos(latitude) * cos(lat1) * sin(dlon / 2)**2
         c = 2 * atan2(sqrt(a), sqrt(1 - a))
         # c = 2 * asin(sqrt(a))
         distance = c * 6371
         # print(c)
         print(distance)
         if distance < 100:
             to_be_shown.append(i)
     serializer = ItemSerializer(to_be_shown, many=True)
     return Response(serializer.data)
Beispiel #20
0
    def patch(
        self, request: Request, product_id: int, item_id: int, format: str = None
    ):
        try:
            item = Item.objects.get(
                id=item_id, product__id=product_id, product__seller=request.user
            )
        except Item.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = ItemSerializer(item, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #21
0
def ItemDetail(request, pk):

    try:
        item = Items.objects.get(pk=pk)
    except Items.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ItemSerializer(item, 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':
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #22
0
class BillSerializer(serializers.ModelSerializer):

    qr = serializers.JSONField()
    items = ItemSerializer(many=True)

    class Meta:
        model = Bill
        fields = ('dateTime', 'nds18', 'taxation_type', 'ecash_total_sum',
                  'qr', 'fiscalSign', 'cashTotalSum', 'total_sum',
                  'operationType', 'items')

    def create(self, validated_data):
        """
        without data validation - need only qr code
        :param validated_data:
        :return:
        """

        items_data = validated_data.pop('items')

        model_class = self.Meta.model

        try:
            instance = model_class.objects.create(**validated_data)
        except TypeError:
            msg = ('Got a `TypeError` when calling `%s.objects.create()`. '
                   '\nOriginal exception was:\n %s' %
                   (model_class.__name__, traceback.format_exc()))
            raise TypeError(msg)

        for item_data in items_data:
            item, created = Item.objects.get_or_create(**item_data)

            instance.items.add(item)

        # BillService.determine_cashback(instance)

        return instance
Beispiel #23
0
def item_detail(request, pk, format=None):
    """Retrieve, update or delete a code item."""
    try:
        item = Item.objects.get(pk=pk)
    except Item.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ItemSerializer(item, 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)

    elif request.method == 'DELETE':
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #24
0
 def list(self, request):
     items = Item.objects.all()
     serializer = ItemSerializer(items, many=True)
     return Response(serializer.data)
Beispiel #25
0
 def get(self, request: Request, product_id: int, format: str = None):
     queryset = Item.objects.filter(
         product__seller=self.request.user, product__id=product_id
     )
     return Response(ItemSerializer(queryset, many=True).data)
Beispiel #26
0
class ProfileSerializer(serializers.ModelSerializer):
    social_links = SocialLinkSerializer(source='sociallink', many=False)
    descriptions = DescriptionSerializer(source='description_set', many=True)
    feedbacks = FeedbackSerializer(source='feedback_set', many=True)
    full_name = serializers.CharField(max_length=255,
                                      required=True,
                                      allow_blank=True)
    college = serializers.ReadOnlyField(source='college.name')
    year = serializers.ReadOnlyField(source='year.name')
    knacks = KnackSerializer(many=True, read_only=True)
    items = ItemSerializer(many=True, read_only=True)
    #picture = serializers.SerializerMethodField('get_avatar_thumbnail')
    reasons = serializers.SerializerMethodField('split')
    last_seen1 = serializers.SerializerMethodField('get_last_seen')
    created_date = serializers.SerializerMethodField('get_created_at')

    class Meta:
        model = User
        fields = ('email', 'full_name', 'first_name', 'last_name', 'age',
                  'college', 'year', 'picture', 'feedbacks', 'grand_total',
                  'reasons', 'about_me', 'payment_venmo', 'payment_paypal',
                  'public_profile_url', 'created_date', 'last_seen1',
                  'social_links', 'descriptions', 'id', 'knacks', 'items')

    def split(self, obj):
        if obj.reasons:
            return obj.reasons
        else:
            return None

    def get_avatar_thumbnail(self, obj):
        if obj.picture:
            return obj.picture.url
        else:
            return None

    def get_last_seen(self, obj):
        mins = (timezone.now() - obj.last_seen).total_seconds() / 60
        if mins >= 1440:
            mins = int(mins) / 1440
            unit = ' days ago'
        elif mins >= 60:
            mins = int(mins) / 60
            unit = ' hours ago'
        else:
            mins = int(mins)
            unit = ' minutes ago'
        return str(mins) + unit

    def get_created_at(self, obj):
        return obj.created_at.strftime('%b %dth, %Y')

    def update(self, instance, validated_data):
        instance.age = validated_data.get('age')
        full_name = validated_data.get('full_name').split(' ')
        instance.first_name = full_name[0]
        try:
            instance.last_name = full_name[1]
        except:
            instance.last_name = ''
        # instance.email = validated_data.get('email', instance.email)
        instance.save()

        return instance

    def to_internal_value(self, data):
        picture = data.pop('picture')[0]
        if not isinstance(picture, str) or not isinstance(picture, unicode):
            self.instance.picture = picture

        sociallinks = json.loads(data.pop('social_links', None)[0])
        if sociallinks:
            if not hasattr(self.instance, 'sociallink'):
                self.instance.sociallink = SocialLink()
            self.instance.sociallink.twitter = sociallinks['twitter']
            self.instance.sociallink.instagram = sociallinks['instagram']
            self.instance.sociallink.facebook = sociallinks['facebook']
            self.instance.sociallink.googleplus = sociallinks['googleplus']
            self.instance.sociallink.save()

        self.instance.description_set.all().delete()
        descriptions = json.loads(data.pop('descriptions', None)[0])
        for desc in descriptions:
            desc_obj = Description(description=desc['description'],
                                   user=self.instance)
            desc_obj.save()

        ret = super(ProfileSerializer, self).to_internal_value(data)
        return ret
Beispiel #27
0
    def get(self, request):
        items = Item.objects.all()
        serialized = ItemSerializer(instance=items)

        return Response(serialized.data, status=200)
Beispiel #28
0
class UserSerializer(serializers.HyperlinkedModelSerializer):
    items = ItemSerializer(many=True, read_only=False)

    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups', 'items']
Beispiel #29
0
class FolderSerializer(serializers.ModelSerializer):
    items = ItemSerializer(many=True, read_only=True)
    class Meta:
        model = Folder
        fields = ('id', 'name', 'isroot', 'idparent', 'created', 'items')
Beispiel #30
0
def item_create(request):
    if request.method == 'PUT':
        data = JSONParser().parse(request)
        # create item
        item = Item()
        item_data = {}
        item_data['item_name'] = data['item_name']
        item_data['item_price'] = data['item_price']
        item_data['frequency'] = data['frequency']
        item_data['classify'] = data['classify']
        serializer = ItemSerializer(item, data=item_data)
        if serializer.is_valid():
            serializer.save()
            item_id = item.id
            # create step
            step_list = data['steps']
            for step_val in step_list:
                step = Step()
                step_data = step_val
                step_data['belong_item'] = item_id
                serializer = StepSerializer(step, step_data)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return JsonResponse(serializer.errors, status=400)
            product_list = data['product']
            for product_val in product_list:
                item_product = Item_Product()
                product_data = product_val
                product_data['item'] = item_id
                product_data['product'] = Product.objects.get(
                    name=product_data['name']).id
                serializer = ItemProductSerializer(item_product, product_data)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return JsonResponse(serializer.errors, status=400)
            instrument_list = data['instrument']
            for instrument_val in instrument_list:
                item_instrument = Item_Instrument()
                instrument_data = instrument_val
                instrument_data['item'] = item_id
                instrument_data['instrument'] = Instrument.objects.get(
                    name=instrument_data['name']).id
                serializer = ItemInstrumentSerializer(item_instrument,
                                                      instrument_data)
                if serializer.is_valid():
                    serializer.save()
                else:
                    return JsonResponse(serializer.errors, status=400)
            return JsonResponse({"text": "success"})
        return JsonResponse(serializer.errors, status=400)