Example #1
0
    def handle(self, *args, **kwargs):
        # load categories data
        categories = load_json_data('categories')
        ProductCategory.objects.all().delete()

        for category in categories:
            new_category = ProductCategory(name=category['name'],
                                           description=category['description'])
            new_category.save()

        # load products data
        products = load_json_data('products')
        Product.objects.all().delete()

        for p in products:
            # get category_id by name
            category_id = ProductCategory.objects.get(name=p['category']).id
            # add new product
            new_product = Product(category_id=category_id,
                                  name=p['name'],
                                  short_desc=p['short_desc'],
                                  description=p['description'],
                                  price=p['price'],
                                  quantity=p['quantity'])
            new_product.save()
            # add image to related product
            img = ProductImage(product_id=new_product.id, image=p['image'])
            img.save()
Example #2
0
def product_page(request, product_id):
    # get cart data
    from cart.models import Cart
    cart = Cart.get_cart(request)
    urls_cart = request.build_absolute_uri('/api/cart/' + str(cart.id) + '/')
    urls_product = request.build_absolute_uri('/api/products/' +
                                              str(product_id) + '/')

    if request.user.is_authenticated:
        username = request.user.get_username()
    else:
        username = '******'

    #find product and give it to template
    main_product = Product.objects.get(id=product_id)
    main_image = ProductImage.find_main_product_image(product_id)
    other_images = ProductImage.find_product_images(product_id)

    return render(
        request, 'products/product.html', {
            'product': main_product,
            'main_image': main_image,
            'other_images': other_images,
            'cart': cart,
            'urls_cart': urls_cart,
            'urls_product': urls_product,
            'username': username
        })
Example #3
0
def product_page(request, product_id):
    # get cart data
    cart_manager = CartManager(request)
    # creating the urls needed by the template to make its request to the api
    urls_cart = request.build_absolute_uri(
        '/api/cart/' + urllib.parse.quote(str(cart_manager.cart.id)) + '/')
    urls_product = request.build_absolute_uri(
        '/api/products/' + urllib.parse.quote(str(product_id)) + '/')

    if request.user.is_authenticated:
        username = request.user.get_username()
    else:
        username = ''

    #find product and give it to template
    main_product = Product.objects.get(id=product_id)
    main_image = ProductImage.find_main_product_image(product_id)
    other_images = ProductImage.find_product_images(product_id)

    return render(
        request, 'products/product.html', {
            'product': main_product,
            'main_image': main_image,
            'other_images': other_images,
            'cart': cart_manager.cart,
            'urls_cart': urls_cart,
            'urls_product': urls_product,
            'username': username
        })
Example #4
0
def product_page(request, product_id):
    #find product and give it to template
    main_product = list(Product.objects.filter(id = product_id))
    main_product = main_product[0]
    main_image = list(ProductImage.find_main_product_image(product_id))
    main_image = main_image[0]
    other_images = ProductImage.find_product_images(product_id)

    return render(request, 'products/product.html', {'product':main_product, 'main_image':main_image, 'other_images':other_images})
Example #5
0
def create_item(request):
    if request.method == "POST":
        form = ProductCreationForm(data=request.POST)
        if form.is_valid():
            product = form.save()
            product_image = ProductImage(image=request.POST["image"],
                                         product=product)
            product_image.save()
            return redirect("create_item")
    else:
        form = ProductCreationForm()
    return render(request, "products/create_product.html", {"form": form})
Example #6
0
def create_product(request):
    if request.method == 'POST':
        form = ProductCreateForm(data=request.POST)
        if form.is_valid():
            product = form.save()
            product_image = ProductImage(image=request.POST['image'],
                                         product=product)
            product_image.save()
            return redirect('product-index')
    else:
        form = ProductCreateForm()
    return render(request, 'products/create_product.html', {'form': form})
Example #7
0
    def post(self, request):
        productForm = ProductForm(request.POST)

        if productForm.is_valid():
            # form = productForm.save(commit=False)
            # form.shop = request.user.shop
            # form.product_code = product_code_format(request.user.shop.id)
            # form.save()

            product = Product()

            product.shop = request.user.shop
            product.product_code = product_code_format(request.user.shop.id)
            product.category = productForm.cleaned_data.get('category')
            product.brand = productForm.cleaned_data.get('brand')
            product.product_name = productForm.cleaned_data.get('product_name')
            product.subTitle = productForm.cleaned_data.get('subTitle')
            product.original_price = productForm.cleaned_data.get(
                'original_price')
            product.price = productForm.cleaned_data.get('price')
            product.cost = productForm.cleaned_data.get('cost')
            product.publish_status = productForm.cleaned_data.get(
                'publish_status')
            product.description = productForm.cleaned_data.get('description')
            product.is_freeShipping = productForm.cleaned_data.get(
                'is_freeShipping')

            product.save()

            # modelform保存后获取model?
            for pimage in request.FILES.getlist('pimage'):

                image = ProductImage(product=product,
                                     image=pimage,
                                     type='image')

                image.save()

            for dimage in request.FILES.getlist('dimage'):

                image = ProductImage(product=product,
                                     image=dimage,
                                     type='detailImage')
                image.save()

            for property in product.category.propertys.all():
                propertyValue = Propertyvalue()
                propertyValue.property = property
                propertyValue.product = product
                propertyValue.value = ''
                propertyValue.save()

            return render(request, 'salers/amz/propertysForm.html',
                          {'product': product})

        else:
            print(productForm.errors)
            return render(request, 'salers/amz/product-add.html',
                          {"productForm": productForm})
Example #8
0
def order_history(request):
    order_history = CheckoutDetails.objects.filter(user_id = request.user.id)
    cart_items_list = []
    product_images = []
    total_costs = []
    for order in order_history:
        cart_items = order.cart.get_items()
        cart_items_list.append(cart_items)
        #get product images
        repeated = False
        if cart_items:
            for cart_item in cart_items:
                img_in_list = ProductImage.find_main_product_image(cart_item.product.id)
                repeated = False
                for product_image in product_images:
                    if product_image.pk == img_in_list.pk:
                        repeated = True
                        break
                if not repeated:
                    product_images.append(img_in_list)
                    repeated = False
        #get order total cost
        total_cost = 0.0
        for cart_item in cart_items:
            total_cost += (float(cart_item.product.current_price) * cart_item.quantity)
        total_cost = round(total_cost, 2)
        total_cost_with_tax = total_cost*1.13
        total_cost_with_tax = round(total_cost_with_tax, 2)
        total_costs.append(total_cost_with_tax)

    order_cartitem_history = zip( order_history, cart_items_list, total_costs)
    return render(request, 'cart/order_history.html', {'orders':order_history, 'order_cartitem_history':order_cartitem_history, 'product_images':product_images})
Example #9
0
def order_confirmation(request):
    cart_manager = CartManager(request)
    cart_manager.load_items()
    cart_manager.total_cost()
    total_cost_for_stripe = cart_manager.total_cost_with_tax * 100


    # load main image for each cart item product, should maybe redo this main img finder
    product_images =  []
    repeated = False
    if hasattr(cart_manager, 'cart_items'):
        for cart_item in cart_manager.cart_items:
            img_in_list = ProductImage.find_main_product_image(cart_item.product.id)
            repeated = False
            for product_image in product_images:
                if product_image.pk == img_in_list.pk:
                    repeated = True
                    break
            if not repeated:
                product_images.append(img_in_list)
                repeated = False

    if request.method == "GET":
        payment_confirmation = ''
    elif request.POST['payment_confirmation']:
        payment_confirmation = float(request.POST['payment_confirmation'])
    else:
        payment_confirmation = ''


    # deactivate this cart now
    cart_manager.deactivate(request)
    # cant delete deactiveated carts because they are needed to load order history

    return render(request, 'cart/order_confirmation.html', {'cart':cart_manager.cart, 'cart_items':cart_manager.cart_items, 'product_images':product_images, 'total_cost':cart_manager.total_cost,'tax':cart_manager.tax, 'total_cost_with_tax':cart_manager.total_cost_with_tax, 'total_cost_for_stripe':total_cost_for_stripe, 'payment_confirmation':payment_confirmation, 'true_string':'True'})
Example #10
0
    def get(self, request, filter = ''):
        self.all_categories = Category.update_sub_category_lists()
        self.categories = Category.find_main_categories(self.all_categories)



        # here we use the filter to load the products accordingly!
        if filter != '':
            self.category_from_filter = list(Category.objects.filter(name = filter))
            self.list_of_all_categories_from_filter = Category.get_all_sub_categories(self.category_from_filter[0])
            self.list_of_all_categories_from_filter.append(self.category_from_filter[0])
            self.all_products = Product.get_products_from_list_of_categories(self.list_of_all_categories_from_filter)
        else:
            self.all_products = Product.get_all_products()



        #now we find all the images we need for each product
        self.all_product_images = []
        for product in self.all_products:
            img = list(ProductImage.find_all_product_images(product.id))
            self.all_product_images += img


        # this should be to load the homepage, so give featured products and catalog data
        return render(request, 'products/home.html', {'main_categories':self.categories, 'all_categories':self.all_categories, 'products':self.all_products, 'product_images':self.all_product_images })
Example #11
0
def order_confirmation(request):
    cart = Cart.get_cart(request.session['cart_id'])
    cart_items = cart.get_items()
    # load main image for each cart item product
    product_images = []
    repeated = False
    if cart_items:
        for cart_item in cart_items:
            img_in_list = ProductImage.find_main_product_image(
                cart_item.product.id)
            repeated = False
            for product_image in product_images:
                if product_image.pk == img_in_list.pk:
                    repeated = True
                    break
            if not repeated:
                product_images.append(img_in_list)
                repeated = False

    # calculate total cost
    total_cost = 0.0
    if cart_items:
        for cart_item in cart_items:
            total_cost += (float(cart_item.product.current_price) *
                           cart_item.quantity)
    total_cost = round(total_cost, 2)
    tax = total_cost * 0.13
    tax = round(tax, 2)
    total_cost_with_tax = total_cost * 1.13
    total_cost_with_tax = round(total_cost_with_tax, 2)
    total_cost_for_stripe = total_cost_with_tax * 100
    if request.method == "GET":
        payment_confirmation = ''
    elif request.POST['payment_confirmation']:
        payment_confirmation = float(request.POST['payment_confirmation'])
    else:
        payment_confirmation = ''
    #reset this val

    # clear out cart session and make new cart and update session with new cart
    # note the big difference between get_cart() and Cart.get_cart()
    new_cart = Cart.get_cart()
    request.session['cart_id'] = new_cart.id
    return render(
        request, 'cart/order_confirmation.html', {
            'cart': cart,
            'cart_items': cart_items,
            'product_images': product_images,
            'total_cost': total_cost,
            'tax': tax,
            'total_cost_with_tax': total_cost_with_tax,
            'total_cost_for_stripe': total_cost_for_stripe,
            'payment_confirmation': payment_confirmation,
            'true_string': 'True'
        })
Example #12
0
    def get_image_thumb(self):
        #images = self.Productimage_set.order_by('id').filter(deleted=False).first()
        images = ProductImage.filter(product_id=self.item_id,deleted=False).first()
        if images:
            image_url = str(images.image)
            image_url_array = image_url.split('/')
            url = '/'+image_url_array[0]+'/100/'+image_url_array[2]
        else:
            url = "/static/admin/img/100x100.png"

        return format_html(u'<img src="%s" />' % (url))
Example #13
0
def product_search(request):
    all_categories = Category.update_sub_category_lists()
    categories = Category.find_main_categories(all_categories)

    found_products = search_for_something(request)

    all_product_images = []
    for product in found_products:
        img = list(ProductImage.find_all_product_images(product.id))
        all_product_images += img

    return render(request, 'products/home.html', {'main_categories':categories, 'all_categories':all_categories, 'products':found_products, 'product_images':all_product_images })
Example #14
0
 def get_image_thumb(self):
     #images = self.Productimage_set.order_by('id').filter(deleted=False).first()
     images = ProductImage.filter(product_id=self.product_id).order_by('id').first()
     image_url = ''
     if images:
         image = str(images.image)
         if image:
             image_url = image
         else:
             image_name = str(images.id)+'.jpg'
             image_url = 'pimgs/pimages/'+image_name 
     return  image_url           
Example #15
0
 def mutate(self, info, **fields):
     subcategory = Subcategory.objects.get(id=fields.get('subcategory_id'))
     productOwner = ProductOwner.objects.get(
         id=fields.get('product_owner_id'))
     product = Product.objects.create(name=fields.get('name'),
                                      description=fields.get('description'),
                                      subcategory=subcategory,
                                      state=fields.get('state'),
                                      tag=fields.get('tag'),
                                      price_old=fields.get('price_old'),
                                      discount=fields.get('discount'),
                                      quantity=fields.get('quantity'),
                                      active=fields.get('active'),
                                      featured=fields.get('featured'),
                                      productOwner=productOwner)
     product.save()
     files = info.context.FILES['imageItem']
     productImage = ProductImage(product=product, image=files)
     productImage.save()
     return CreateProduct(product=product,
                          productImage=productImage,
                          success=True)
Example #16
0
def upload(request):
    formset = ImageFormset(queryset=ProductImage.objects.none()) 
    form = UploadForm(request.POST, request.FILES)

    if request.method == 'POST':
        formset = ImageFormset(request.POST, request.FILES)
        if form.is_valid() and formset.is_valid():
            form.save()
            
            # is this hacky?
            product = Product.objects.all().order_by('-id')[0]
            
            for form in formset.cleaned_data:
                image= form['image']
                pi = ProductImage (image = image, product = product)
                pi.save()
            
            return redirect('social_media')
        # invalid form response?
    return render(request, 'upload/upload.html', {
        'form': form, 
        'formset': formset,
    })
Example #17
0
    def get(self, request):
        #what we need for this page it to enable it to be able to get all data from the carts, so
        #all the products, their costs and total cost, main photo of each product, and ability to remove items from the cart
        self.cart = Cart.get_cart(request)
        cart_items = self.cart.get_items()

        # load main image for each cart item product
        product_images = []
        repeated = False
        if cart_items:
            for cart_item in cart_items:
                img_in_list = ProductImage.find_main_product_image(
                    cart_item.product.id)
                repeated = False
                for product_image in product_images:
                    if product_image.pk == img_in_list.pk:
                        repeated = True
                        break
                if not repeated:
                    product_images.append(img_in_list)
                    repeated = False

        # calculate total cost
        total_cost = 0.0
        if cart_items:
            for cart_item in cart_items:
                total_cost += (float(cart_item.product.current_price) *
                               cart_item.quantity)
        total_cost = round(total_cost, 2)
        tax = total_cost * 0.13
        tax = round(tax, 2)
        total_cost_with_tax = total_cost * 1.13
        total_cost_with_tax = round(total_cost_with_tax, 2)
        total_cost_for_stripe = total_cost_with_tax * 100

        # get stipe key
        stripe_key = settings.STRIPE_PUBLISHABLE_KEY

        return render(
            request, 'cart/home2.html', {
                'cart': self.cart,
                'cart_items': cart_items,
                'product_images': product_images,
                'total_cost': total_cost,
                'tax': tax,
                'total_cost_with_tax': total_cost_with_tax,
                'stripe_key': stripe_key,
                'total_cost_for_stripe': total_cost_for_stripe
            })
Example #18
0
def auto_set_product_images(request, password):
    check_password(password)

    series = Series.objects.all()
    for serie in series:
        dirname = os.path.join(MEDIA_ROOT,'uploads','images','products',serie.name.lower())
        if not os.path.isdir(dirname):
            continue

        products = serie.product_set.all()
        for product in products:
            imgname = serie.name.lower() + "-" + product.name.lower() + ".png"

            filename = os.path.join(dirname, imgname)

            if not os.path.isfile(filename):
                continue
            images = ProductImage.objects.filter(product_id=product.id)
            image_path = os.path.join( 'uploads', 'images', 'products', serie.name.lower(), imgname)

            add_image_flag = True
            for image in images:
                if str(image.image) == str(image_path):
                    add_image_flag = False
                    break

            if not add_image_flag:
                continue

            image = ProductImage(product_id = product.id, image = image_path)
            image.save()

    return render_to_response('content/dummy.html',
                              {'testvar': ''},
                              context_instance=RequestContext(
                                  request))
Example #19
0
def product_search(request):
    all_categories = Category.update_sub_category_lists()
    categories = Category.find_main_categories(all_categories)

    # this function here uses whats in the search bar and uses that string to find all products related to it, the search results are not ordered in anyway, its random, which should be changed
    found_products = search_for_something(request)

    if found_products:
        for product in found_products:
            if len(product.description) > 80:
                product.description = product.description[:80] + '...'

    # here we zip the product data with another list that has values to help the template determine when it should start a new card-deck as apposed to card
    products_and_carddeck_checker = []
    if found_products:
        card_deck_update_check = []
        i = 0
        for product in found_products:
            if i == 0:
                card_deck_update_check.append('first')
            elif i % 3:
                card_deck_update_check.append(False)
            else:
                card_deck_update_check.append(True)
            i += 1
        products_and_carddeck_checker = zip(found_products,
                                            card_deck_update_check)

    all_product_images = []
    if found_products:
        for product in found_products:
            img = list(ProductImage.find_all_product_images(product.id))
            all_product_images += img

    search_string = request.GET['search_string']
    return render(
        request, 'products/home.html', {
            'main_categories': categories,
            'all_categories': all_categories,
            'products': found_products,
            'products_and_carddeck_checker': products_and_carddeck_checker,
            'product_images': all_product_images,
            'empty_list': [],
            'search_string': search_string
        })
Example #20
0
    def get(self, request):
        self.cart = Cart.get_cart(request)
        cart_items = self.cart.get_items()

        cart_product_ids = set()
        product_images = []
        if cart_items:
            for cart_item in cart_items:
                cart_product_ids.add(cart_item.product.id)

            for cart_product_id in cart_product_ids:
                product_images.append(
                    ProductImage.find_main_product_image(cart_product_id))

        # calculate total cost
        total_cost = 0.0
        if cart_items:
            for cart_item in cart_items:
                total_cost += (float(cart_item.product.current_price) *
                               cart_item.quantity)
        total_cost = round(total_cost, 2)
        tax = total_cost * 0.13
        tax = round(tax, 2)
        total_cost_with_tax = total_cost * 1.13
        total_cost_with_tax = round(total_cost_with_tax, 2)
        total_cost_for_stripe = total_cost_with_tax * 100

        # get stipe key
        stripe_key = settings.STRIPE_PUBLISHABLE_KEY

        return render(
            request, 'cart/home2.html', {
                'cart': self.cart,
                'cart_items': cart_items,
                'product_images': product_images,
                'total_cost': total_cost,
                'tax': tax,
                'total_cost_with_tax': total_cost_with_tax,
                'stripe_key': stripe_key,
                'total_cost_for_stripe': total_cost_for_stripe
            })
Example #21
0
    def get(self, request):

        cart_manager = CartManager(request)
        cart_manager.load_items()
        cart_manager.total_cost()
        total_cost_for_stripe = cart_manager.total_cost_with_tax * 100

        # load product images
        product_images = []
        if hasattr(cart_manager, 'cart_items'):

            cart_product_ids = set()
            for cart_item in cart_manager.cart_items:
                cart_product_ids.add(cart_item.product.id)

            for cart_product_id in cart_product_ids:
                product_images.append(ProductImage.find_main_product_image(cart_product_id))


        # get stipe key
        stripe_key = settings.STRIPE_PUBLISHABLE_KEY


        return render(request, 'cart/home.html', {'cart':cart_manager.cart, 'cart_items':cart_manager.cart_items, 'product_images':product_images, 'total_cost':cart_manager.total_cost,'tax':cart_manager.tax, 'total_cost_with_tax':cart_manager.total_cost_with_tax, 'stripe_key':stripe_key, 'total_cost_for_stripe':total_cost_for_stripe})
Example #22
0
    def test_thumbnails_are_generated_on_save(self):

        with open('products/fixtures/the-cathedral-the-bazaar.jpg', 'rb') as f:
            image = ProductImage(
                product=self.product,
                image=ImageFile(f, name='tctb.jpg'),
            )
            with self.assertLogs('products.signals', level='INFO') as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open('products/fixtures/the-cathedral-the-bazaar.thumb.jpg', 'rb') as f:
            expected_content = f.read()
            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Example #23
0
    def handle(self, *args, **options):
        products_data = loadFromJSON('product_data')

        # удаляем все данные из таблиц
        Product.objects.all().delete()
        ProductBySize.objects.all().delete()
        ProductImage.objects.all().delete()
        ProductCategory.objects.all().delete()

        for i in (
                'ALTER SEQUENCE products_productcategory_id_seq RESTART WITH 1;',
                'ALTER SEQUENCE products_product_id_seq RESTART WITH 1;',
                'ALTER SEQUENCE products_productbysize_id_seq RESTART WITH 1;',
                'ALTER SEQUENCE products_productimage_id_seq RESTART WITH 1;',
        ):
            connection.cursor().execute(i)

        # фаилы выбивающиеся из общей системы названий, копирование его с переименованием
        copyfile(os.path.join('media/content/', 'woman/jackets', '4.png'),
                 os.path.join('media/content/', 'woman/jackets', 'c1-1.jpg'))
        copyfile(os.path.join('media/content/', 'woman/tshirts', 'wcp22.jpg'),
                 os.path.join('media/content/', 'woman/tshirts', 'wcp2-2.jpg'))
        copyfile(os.path.join('media/content/', 'woman/tshirts', 'wcp24.jpg'),
                 os.path.join('media/content/', 'woman/tshirts', 'wcp2-4.jpg'))
        copyfile(os.path.join('media/content/', 'man/tshirts', 'r1-1psd.jpg'),
                 os.path.join('media/content/', 'man/tshirts', 'r1-1.jpg'))

        for data in products_data:
            name_category = data['category']
            """Запись категорий продуктов в таблицу ProductCategory"""
            try:
                # проверяем наличие категории в таблице ProductCategory
                ProductCategory.objects.get(name_category=name_category)
            except (ProductCategory.DoesNotExist, ):
                # если категории в таблице нет добавляем
                category = ProductCategory(name_category=name_category)
                category.save()
            """Запись данных о продукте в таблицу Product"""
            category = ProductCategory.objects.get(name_category=name_category)
            product = Product(category=category,
                              name_product=data['name'],
                              logotype=data['logotype'],
                              gender=data['gender'],
                              color=data['color'],
                              article=data['article'],
                              price=data['price'],
                              description=data['description'])
            product.save()
            """Запись размеров продукта в таблицу ProductBySize"""
            product = Product.objects.get(name_product=data['name'])

            size_list = data['size_quantity']
            for size in size_list.keys():
                product_size = ProductBySize(product=product,
                                             size=size,
                                             quantity=size_list[size])
                product_size.save()
            """Запись картинок фотографий продукта в таблицу ProductImage"""
            print(data['product'])
            for i in range(1, 5):
                try:
                    path_img = 'content/' + data['product'] + f'-{i}.jpg'
                    ImageFile(open('media/' + path_img, "rb"))
                    product_img = ProductImage(product=product,
                                               img_product=path_img)
                    product_img.save()
                except FileNotFoundError:
                    path_img = 'content/' + data['product'][:-1] + f'{i}.jpg'
                    ImageFile(open('media/' + path_img, "rb"))
                    product_img = ProductImage(product=product,
                                               img_product=path_img)
                    product_img.save()
Example #24
0
    def get(self, request, filter=''):
        self.all_categories = Category.update_sub_category_lists()
        self.categories = Category.find_main_categories(self.all_categories)

        # here we use the filter to load the products accordingly!
        if filter != '':
            self.category_from_filter = Category.objects.get(name=filter)
            self.list_of_all_categories_from_filter = Category.get_all_sub_categories(
                self.category_from_filter)
            self.list_of_all_categories_from_filter.append(
                self.category_from_filter)
            self.all_products = Product.get_products_from_list_of_categories(
                self.list_of_all_categories_from_filter)
        else:
            self.all_products = Product.get_all_products()

        # update the descripton of the product
        for product in self.all_products:
            if len(product.description) > 80:
                product.description = product.description[:80] + '...'

        #now we find all the images we need for each product
        self.all_product_images = []
        for product in self.all_products:
            img = list(ProductImage.find_all_product_images(product.id))
            self.all_product_images += img

        # here we zip the product data with another list that has values to help the template determine when it should start a new card-deck as apposed to card
        card_deck_update_check = []
        i = 0
        for product in self.all_products:
            if i == 0:
                card_deck_update_check.append('first')
            elif i % 3:
                card_deck_update_check.append(False)
            else:
                card_deck_update_check.append(True)
            i += 1
        products_and_carddeck_checker = zip(self.all_products,
                                            card_deck_update_check)

        if filter == '':
            self.featured_products = Product.objects.filter(featured=True)

            self.featured_product_images = []
            for featured_product in self.featured_products:
                img = list(
                    ProductImage.find_all_product_images(featured_product.id))
                self.featured_product_images += img
        # this should be to load the homepage, so give featured products and catalog data                                                                                                                                                                                              featured_products
            return render(
                request, 'products/home.html', {
                    'main_categories': self.categories,
                    'all_categories': self.all_categories,
                    'products': self.all_products,
                    'products_and_carddeck_checker':
                    products_and_carddeck_checker,
                    'product_images': self.all_product_images,
                    'empty_list': [],
                    'featured_products': self.featured_products,
                    'featured_product_images': self.featured_product_images
                })
        return render(
            request, 'products/home.html', {
                'main_categories': self.categories,
                'all_categories': self.all_categories,
                'products': self.all_products,
                'products_and_carddeck_checker': products_and_carddeck_checker,
                'product_images': self.all_product_images,
                'empty_list': []
            })
Example #25
0
for prod, photos in pp.product_loop():
    #if prod.sku == 'TWINGUARD.ENT':
    if prod.sku == 'ZENBOOK':
        #photo_list = [f for f,s in photos]
        #if trace: pprint (photo_list)

        for photo, siz in photos:
            if trace: print photo, is_autocreated(photo, [])  # photo_list)

            if not is_autocreated(photo, []):  # photo_list):
                if prod.images.filter(image__iexact=photo):
                    print photo, 'DUP'
                else:
                    print 'Creating:', photo, siz
                    i = ProductImage(image=photo,
                                     product=prod,
                                     published=(siz > 5000))
                    i.save()
                    #prod.images.add (i)
                    #prod.save()

print
print 'Published prods with no dir:', pp.no_dir_count

# TODO: Count the dirs with/without a prod, and prods with/without a dir, and which ones are published...

# then upd db tables with the actual imges
# and add exclude field
# and pre-populate exclude with under 22K (Or whatever it was)
Example #26
0
 def create(self, o, f, siz, **kw):
     i = ProductImage(image=f, product=o, **kw)
     i.save()
Example #27
0
 def create (self, o, f, siz):
   print 'Creating:', f, siz
   i = ProductImage (image=f, product=o, published = (siz > 5000))
   i.save()
Example #28
0
 def create (self, o, f, siz, **kw):
   i = ProductImage (image=f, product=o, **kw)
   i.save()
Example #29
0
def new_auction_page(request):

    extra = 4 if request.user.is_premium else 1
    ImageFormset = modelformset_factory(ProductImage, fields=('image',),extra=extra)
    form = new_auction_form(request.POST or None)
    formset = ImageFormset(request.POST or None, request.FILES or None)

    try:
        prof = Profile.objects.get(user=request.user)
    except:
        messages.warning(request, 'You have to provide your information before you start an auction')
        url = reverse('profileit')
        return redirect(url)
    NumeroProdottiPerCliente = Product.objects.filter(profile=prof).count()
    print(NumeroProdottiPerCliente)
    if NumeroProdottiPerCliente >= 3 and not request.user.premium:
        return render(request, "users/credit_card.html", {})


    if form.is_valid() or formset.is_valid():
        name  = form.cleaned_data.get("name")
        try:
            if len(name) > 40:
                messages.error(request, "Name is too long")
                return redirect('create-auction')
        except:
            messages.error(request, "Name is too long")
            return redirect('create-auction')

        description = form.cleaned_data.get("description")
        try:
            if len(description) > 300:
                messages.error(request, "Description is too long max 300 characters")
                return redirect('create-auction')
        except:
            messages.error(request, "Description is too long max 300 characters")
            return redirect('create-auction')

        price = form.cleaned_data.get("price")
        try:
            if price <= 0 or price > 50000000:
                messages.error(request, "Price should be between 0 - 50'000'000")
                return redirect('create-auction')
        except:
            messages.error(request, "Price should be between 0 - 50'000'000")
            return redirect('create-auction')

        min_increment = form.cleaned_data.get("min_increment")
        try:
            print(min_increment)
            if min_increment <= 0:
                messages.error(request, "Increment cannot be negative")
                return redirect('create-auction')
        except:
            messages.error(request, "Increment cannot be negative")
            return redirect('create-auction')

        end_date = form.cleaned_data.get("end_date")
        try:
            if form.cleaned_data.get("end_date") < datetime.date(timezone.localtime(timezone.now())):
                messages.error(request, "Date not valid!")
                return redirect('create-auction')
        except:
            messages.error(request, "Date not valid!")
            return redirect('create-auction')

        p = Product(name=name,description= description,price=price,min_increment=min_increment,end_date=end_date,final_price=price,profile = prof)
        p.save()

        for f in formset:
            try:
                print(f)
                photo = ProductImage(product = p, image=f.cleaned_data['image'])
                print(type(f.cleaned_data['image']))
                photo.save()
            except Exception as e:
                break
        if formset.total_form_count() == 0:
            print("non ci sono immagini")

        messages.success(request, 'You have successfully created a new auction!')
        return redirect('home')


    if request.method == 'GET':
        formset = ImageFormset(queryset=ProductImage.objects.none())
    context = {
        "form": form, "formset":formset
    }
    return render(request, "users/new_auction.html", context)
for prod, photos in pp.product_loop():
  #if prod.sku == 'TWINGUARD.ENT':
  if prod.sku == 'ZENBOOK':
    #photo_list = [f for f,s in photos]
    #if trace: pprint (photo_list)

    for photo, siz in photos:
      if trace: print photo, is_autocreated (photo, []) # photo_list)

      if not is_autocreated (photo, []):  # photo_list):
        if prod.images.filter (image__iexact=photo):
          print photo, 'DUP'
        else:
          print 'Creating:', photo, siz
          i = ProductImage (image=photo, product=prod, published = (siz > 5000))
          i.save()
          #prod.images.add (i)
          #prod.save()

print
print 'Published prods with no dir:', pp.no_dir_count




# TODO: Count the dirs with/without a prod, and prods with/without a dir, and which ones are published...

# then upd db tables with the actual imges
# and add exclude field
# and pre-populate exclude with under 22K (Or whatever it was)