예제 #1
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})
예제 #2
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()
예제 #3
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})
예제 #4
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})
예제 #5
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)
예제 #6
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)
예제 #7
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,
    })
예제 #8
0
 def create (self, o, f, siz):
   print 'Creating:', f, siz
   i = ProductImage (image=f, product=o, published = (siz > 5000))
   i.save()
예제 #9
0
파일: views.py 프로젝트: Kochesti2/Auction
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)
예제 #10
0
 def create(self, o, f, siz, **kw):
     i = ProductImage(image=f, product=o, **kw)
     i.save()
예제 #11
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)
예제 #12
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()