예제 #1
0
def new_item(request):
    if request.method == 'POST':
        from uuid import uuid4

        sku = escape(request.POST.get('sku').strip())
        model = escape(request.POST.get('model').strip())
        name = escape(request.POST.get('name').strip())
        category_id = escape(request.POST.get('category').strip())
        category = Category.objects.get(id=category_id)
        price = escape(request.POST.get('price').strip())
        length = escape(request.POST.get('length').strip())
        breadth = escape(request.POST.get('breadth').strip())
        height = escape(request.POST.get('height').strip())
        image = request.FILES.get('image')
        image.name = '{}{}'.format(uuid4().hex, image.name[image.name.rfind('.'):])
        product = Product(sku=sku, model=model, name=name, category=category, length=length, breadth=breadth,
                          height=height, price=price, image=image)
        try:
            product.save()
            category.number_of_items += 1
            category.save()
            url = "%s?created=True" % reverse('user:dashboard')
        except IntegrityError:
            from django.utils.http import quote_plus
            r = "SKU needs to be unique"
            url = "%s?created=False&reason=%s" % (reverse('user:dashboard'), quote_plus(r))
        return HttpResponseRedirect(url)

    category = Category.objects.all()
    cd = {'category': category}
    return render(request, 'new.html', cd)
def update_from_kbpoz(db_filename):
    with open(db_filename) as f:
        for line in f:
            split = line.split('\t')
            gtin = split[0].strip()
            if len(gtin)>13:
                gtin = gtin[1:]

            if len(split)>1:
                nip = split[1].strip()

                try:
                    prod = Product.objects.get(code=gtin)
                    if not prod.company and nip != "":
                        with transaction.atomic():
                            try:
                                company = Company.objects.get(nip=nip)
                            except ObjectDoesNotExist:
                                company = Company.objects.create(nip = nip)
                                if not update_company_from_krs(prod, company):
                                    company.delete()
                                    continue
                                print "!"

                            print gtin+" "+nip
                            print company
                            prod.company = company
                            prod.ilim_queried_at = timezone.now()
                            Product.save(prod, commit_desc="Produkt przypisany "
                                              "do producenta na podstawie bazy "
                                              "KBPOZ")

                except ObjectDoesNotExist:
                    pass
예제 #3
0
def submit_spur(request):

    if 'user' in request.session and Subscriber.objects.filter(email=request.session['user']).exists():
        userObject = Subscriber.objects.get(email=request.session['user'])
        post_data = request.POST
        file_data = request.FILES
        print(file_data)
        category_id = post_data['category']
        brand_id = post_data['brand']
        type_id = post_data['type']
        description = post_data['contact-message']
        product = post_data['product']
        category_object = Category.objects.get(id=category_id)
        brand_object = Brand.objects.get(id=brand_id)
        type_object = Type.objects.get(id=type_id)
        if 'avatar1' in file_data:
            avatar1 = file_data['avatar1']
        else:
            avatar1 = None

        if 'avatar2' in file_data:
            avatar2 = file_data['avatar2']
        else:
            avatar2 = None

        if 'avatar3' in file_data:
            avatar3 = file_data['avatar3']
        else:
            avatar3 = None

        if 'avatar4' in file_data:
            avatar4 = file_data['avatar4']
        else:
            avatar4 = None

        if 'avatar5' in file_data:
            avatar5 = file_data['avatar5']
        else:
            avatar5 = None
        new_product = Product(name=product,
                              description=description,
                              type=type_object,
                              brand=brand_object,
                              category=category_object,
                              addedBy=userObject,
                              image1=avatar1,
                              image2=avatar2,
                              image3=avatar3,
                              image4=avatar4,
                              image5=avatar5)
        new_product.save()
        return redirect('/')
    else:
        return redirect('/register')
예제 #4
0
    def create(self, request):
        
        attrs = self.flatten_dict(request.POST)

        if self.exists(**attrs):
            return rc.DUPLICATE_ENTRY
        else:
            prod = Product(name=attrs['name'], value=attrs['price']) 
            prod.product_spec = ProductSpec.objects.filter(product_spec_id=attrs['product_spec_id'])
            prod.save()
            
            return prod
예제 #5
0
  def parse_item(self, response) :
    sel = Selector (response)
    item =  SWDItem ()
    item['Title'] = #Xpath for title
    item['Category'] = #xpath for some other field
    item['Product_URL'] = response.request.url #this gives the current url cralwed
    
    # Django database 

    item1 = Product() 
    item1.field_name = #assign value
    item1.save() #Save item in the database
    return item 
예제 #6
0
파일: views.py 프로젝트: mwamser/control
def add_product(request):
  
  form = FormProducts(request.POST, request.FILES)
  
  if form.is_valid():
    values = form.cleaned_data
    item = Product(name=values['name'], note=values['note'])
    item.save()
    
    return render_to_response("save.html", {})
    
  else:
    form = FormProducts()
    return render_to_response("add_product.html", {'form' : form}, context_instance=RequestContext(request))
예제 #7
0
    def handle(self, **options):
        categories = [
            ("کلاه", "انواع کلاه ها با رنگبندی های مختلف برای آقایان و بانوان"),
            ("عینک", "عینک های آفتابی متنوع با کیفیت عالی"),
            ("ساعت مچی", "ساعت مچی متناسب برای زیباپسندان"),
            ("انگشتر", "انواع انگشتر های زیبا و جذاب"),
            ("کیف پول", "انواع کیف پول پارچه ای و چرمی "),
        ]

        for category_data in categories:
            c = Category()
            c.title, c.description = category_data
            c.save()
        hat_images_path = path.join(settings.BASE_DIR, "media", "hat")
        pictures = [f for f in os.listdir(hat_images_path) if
                    path.isfile(os.path.join(hat_images_path, f))]
        hat_product_data = [
            ("چنار", "کلاه ساده و زیبا", 12000),
            ("روزگار", "یک کلاه متفاوت و زیبا", 16000),
            ("یادگار", "سازگار با هر نوع تیپ", 20000),
            ("نوین", "شکلی و ساده", 10000),
            ("جوانی", "کلاه مناسب نسل جوان", 22000),
            ("سحاب", "کلاه خاص برای افراد خاص", 18000),
            ("چنار", "کلاه ساده و زیبا", 12000),
            ("روزگار", "یک کلاه متفاوت و زیبا", 16000),
            ("یادگار", "سازگار با هر نوع تیپ", 20000),
            ("نوین", "شکلی و ساده", 10000),
            ("جوانی", "کلاه مناسب نسل جوان", 22000),
            ("سحاب", "کلاه خاص برای افراد خاص", 18000),
            ("چنار", "کلاه ساده و زیبا", 12000),
            ("روزگار", "یک کلاه متفاوت و زیبا", 16000),
            ("یادگار", "سازگار با هر نوع تیپ", 20000),
            ("نوین", "شکلی و ساده", 10000),
            ("جوانی", "کلاه مناسب نسل جوان", 22000),
            ("سحاب", "کلاه خاص برای افراد خاص", 18000),

        ]
        hat_category = Category.objects.filter(pk=1).first()

        for hat in hat_product_data:
            p = Product()
            p.name, p.description, p.price = hat
            p.category = hat_category
            p.save()
            pic = Picture()
            pic.path.name = "hat/" + pictures.pop()
            pic.product = p
            pic.save()
예제 #8
0
def add(request):
    if request.method == 'POST':
        p = Product()
        p.product_name = request.POST.get('product_name')
        p.save()
        
        # 添加权限记录
        newpm = Permission()
        newpm.codename = product2AuthStr(p.id)
        newpm.desc = p.product_name + u"操作权限"
        newpm.type = 5
        newpm.save()
        
        # 日志
        Log(username=request.user.username, log_type=8, content="execute add product " + p.product_name + " success!", level=1).save()
        return HttpResponse(simplejson.dumps({"statusCode":200, "url": "/product/index", "message":u'添加成功'}), mimetype='application/json')
    else:
        return render_to_response('product/add.html', context_instance=RequestContext(request)) 
예제 #9
0
def add_test_product():
    # p1 = Product(name='Potato', grade="A", image_path="/static/product_images/potato.jpeg")
    # p1.save()
    #
    # RU1= RateUnit(product=p1, rate=30, unit="Kg")
    # RU1.save()
    #
    # p2 = Product(name='Tomato', grade="A", image_path="/static/product_images/tomato.jpeg")
    # p2.save()
    #
    # RU2 = RateUnit(product=p2, rate=80, unit="Kg")
    # RU2.save()

    p3 = Product(name='Apple', grade="A", image_path="/static/product_images/apple.jpeg")
    p3.save()

    RU3 = RateUnit(product=p3, rate=80, unit="Kg")
    RU3.save()
예제 #10
0
    def save(self):
        data = self.cleaned_data
        site = Site.objects.get_current()

        # create product
        product = Product(name=data['title'], slug=data['slug'], site=site, active=True)
        product.save()

        # create product price
        price = Price(price=data['price'], product=product)
        price.save()

        if data.get('category'):
            product.category.add(data['category'])

        if data.get('cover_image'):
            # create product image
            ProductImage.objects.create(product=product, picture=data['cover_image'])

        # check for product attributes
        for key in data:
            # if key is not product attribute or
            # value for the key is blank, goto next key
            if key in NOT_PRODUCT_ATTRS or not data[key]:
                continue

            # get the field related to the key
            field = self.fields[key]
            description = (field.label or key.replace('_', ' ')).capitalize()

            # get or create the attribute
            try:
                attribute = AttributeOption.objects.get(name=key)
            except AttributeOption.DoesNotExist:
                attribute = AttributeOption(name=key,
                                            description=description,
                                            validation='product.utils.validation_simple')
                attribute.save()

            # create product attribute
            product_attribute = ProductAttribute(product=product,
                                                 option=attribute,
                                                 value=data[key])
            product_attribute.save()
예제 #11
0
 def create(self, request, *args, **kwargs):
     """
     request.POST['ProductSpec'] = ProductSpec
     try:
         result = super(ProducSpectHandler, self).create(
                request, *args, **kwargs)
         return result
     except:
         return HttpResponse(status=415)
     """ 
     attrs = self.flatten_dict(request.POST)
    
     if self.exists(**attrs):
         return rc.DUPLICATE_ENTRY
     else:
         prod_spec = Product(name=attrs['name'])
         prod_spec.save()
         
         return prod_spec
예제 #12
0
 def setUp(self):
     self.client = Client()
     self.product = Product(
         name=self._product_name,
         slug=self._product_slug,
         price=self._product_price,
         description=self._product_description,
     )
     self.product.save()
     self.user = User.objects.create_user(self._user_email, self._user_email, self._user_password)
    def test_no_dbmod_in_tt(self):
        from product.models import Product
        from django_timetravel import (timetravel,
                                       TimeTravelDBModException,
                                       TimeTravelModelError)

        with timetravel(0):
            p = Product(name='P')
            with pytest.raises(TimeTravelDBModException):
                p.save()

            with pytest.raises(TimeTravelDBModException):
                Product.objects.all().delete()

            with pytest.raises(TimeTravelDBModException):
                Product.objects.update(name='X')

        with pytest.raises(TimeTravelModelError):
            p.name
예제 #14
0
def create_products(num,categories):
		
		created_categories = __create_product_categories(categories)

		cat_sel = 0

		for i in range(num):
			if cat_sel == len(created_categories):
				cat_sel = 0

			p = Product(
				image=u'../../static/static/image/placeholder.jpg',
				title=u'product %s' % i,
				description=u'This is a description of product %s' % i
			)

			p.save()
			p.category.add(created_categories[cat_sel])

			cat_sel += 1
예제 #15
0
파일: views.py 프로젝트: sivajipr/flipkart
def add_product(request):
	user = request.user
	merchant = Merchant.objects.get(user=user)
	if request.method == 'POST':
		form = ProductForm(request.POST, request.FILES)
		if form.is_valid():
			product = Product(merchant=merchant,name=form.cleaned_data['name'],
							  category=form.cleaned_data['category'],
							  selling_price=form.cleaned_data['selling_price'],
							  original_price=form.cleaned_data['original_price'],
							  quantity=form.cleaned_data['quantity'],
							  photo = request.FILES['photo'])
			product.save()
			return HttpResponseRedirect('/merchant')

		else:
			pass
	else:
		form = ProductForm()
	variables = RequestContext(request, {'form': form})
	return render_to_response('product/add_product.html', variables)
예제 #16
0
def bulkUploadProducts(request):
    context= {}
    if request.method == 'POST':
        excel_file = request.FILES['myfile']
        # you may put validations here to check extension or file size
        wb = openpyxl.load_workbook(excel_file)
        # getting a particular sheet by name out of many sheets
        worksheet = wb["PRODUCT"]
        excel_data = list()
        # iterating over the rows and
        # getting value from each cell in row
        for row in worksheet.iter_rows():
            print(row)
            row_data = list()
            for cell in row:
                row_data.append(str(cell.value))
            excel_data.append(row_data)
        print(len(excel_data))
        # Since first element is going to be only the header part
        excel_data.pop(0)
        print(len(excel_data))
        if request.session.get('userId') is not None:
            userId = int(request.session['userId'])
            try:
                user = getUser(userId)
                # with transaction.atomic():
                isActive = ''
                if user != None:
                    for row in excel_data:
                        name = row[0]
                        print(name)
                        prodDescription = row[1]
                        print(prodDescription)
                        brand = row[2]
                        print(brand)
                        prodCategoryId = row[3]
                        print(prodCategoryId)
                        MRP = row[4]
                        print(MRP)
                        isDiscountAvailable = row[5]
                        print(isDiscountAvailable)
                        discountPercentage = row[6]
                        print(discountPercentage)
                        active = row[7]
                        print(active)
                        productSpecification = row[8]
                        print(productSpecification)
                        batchNumber = row[9]
                        print(batchNumber)
                        manufactureDate = row[10]
                        print(manufactureDate)
                        tax = row[11]
                        print(tax)
                        taxSlab = row[12]
                        print(taxSlab)
                        expiryDate = row[13]
                        print(expiryDate)
                        if active=='TRUE' or active=='True':
                            active = True
                        else:
                            active = False
                        discountAvailable = False
                        if isDiscountAvailable == 'TRUE':
                            discountAvailable = True
                        else:
                            discountAvailable = False
                        sellingPrice = int(MRP) - (int(MRP) * int(discountPercentage) / 100)

                        brand = Brand.objects.get(id=int(brand))
                        prodCategoryId = ProductCategory.objects.get(id=int(prodCategoryId))
                        tax = Tax.objects.get(id=int(tax))
                        taxSlab = TaxSlab.objects.get(id=int(taxSlab))
                        print('Active',active)
                        print('Discount available',discountAvailable)
                        product = Product(
                            name=name,
                            prodDescription=prodDescription,
                            prodCategoryId=prodCategoryId,
                            isActive=active,
                            brand=brand,
                            MRP=MRP,
                            sellingPrice=sellingPrice,
                            isDiscountAvailable=discountAvailable,
                            discountPercentage=discountPercentage,
                            productSpecification=productSpecification,
                            batchNumber=batchNumber,
                            manufactureDate=manufactureDate,
                            tax=tax,
                            taxSlab=taxSlab,
                            expiryDate=expiryDate,
                            createdBy=user,
                        )
                        product.save()
                    messages.success(request, INFO_PRODUCT_ADDITION_SUCCESS)
                    listOfProducts = Product.objects.filter(createdBy=user).filter(isActive=True)
                    context['listOfProducts'] = listOfProducts
                    return render(request, 'product/listOfProducts.html', context)
            except Exception as ex:
                print(ex)
                messages.success(request, INFO_PRODUCT_ADDITION_FAILURE)
                return render(request, 'product/addProductsInBulkClass.html')
    else:
        return render(request, 'product/addProductsInBulkClass.html',context)
예제 #17
0
def addProduct(request):
    context = {}
    if request.method == 'POST':
        login_data = request.POST.dict()
        print(login_data)
        if request.session.get('userId') is not None:
            userId = int(request.session['userId'])
            try:
                user = getUser(userId)
                productCategory = ProductCategory.objects.get(id=int(login_data['Category']))
                # productClass = ProductClass.objects.get(id=3)
                # imageFile = request.FILES['imageFile']
                with transaction.atomic():
                    product = None
                    isActive = True
                    if 'active' in request.POST:
                        isActive = True
                    else:
                        isActive = False
                    discountAvailable = False
                    if 'isDiscountAvailable' in request.POST:
                        discountAvailable = True
                    else:
                        discountAvailable = False
                    manufactureDate = '9999-12-31'
                    if login_data['manufactureDate']:
                        manufactureDate = login_data['manufactureDate'],
                        manufactureDate = manufactureDate[0]

                    expiryDate = '9999-12-31'
                    if login_data['expiryDate']:
                        expiryDate = login_data['expiryDate'],
                        expiryDate = expiryDate[0]

                    if user != None:
                        name = login_data['name']
                        description = login_data['description']
                        productSpecification = login_data['productSpecification']
                        brand = Brand.objects.get(id=int(login_data['brand']))
                        MRP = login_data['mrp']
                        discountPercentage = login_data['discount']
                        if discountPercentage == '' or discountPercentage == None:
                            discountPercentage = 0
                        batchNumber = login_data['batchNumber']
                        tax = Tax.objects.get(id=int(login_data['tax']))
                        taxSlab = TaxSlab.objects.get(id=int(login_data['TaxSlab']))
                        # manufactureDate = login_data['manufactureDate']
                        # expiryDate = login_data['expiryDate']
                        sellingPrice = int(MRP) - (int(MRP)*int(discountPercentage)/100)
                        print('I am active' , isActive)
                        product = Product(
                            name=name,
                            prodDescription=description,
                            prodCategoryId = productCategory,
                            isActive=isActive,
                            brand = brand,
                            MRP = MRP,
                            sellingPrice = sellingPrice,
                            isDiscountAvailable = discountAvailable,
                            discountPercentage = discountPercentage,
                            productSpecification = productSpecification,
                            batchNumber = batchNumber,
                            manufactureDate = manufactureDate,
                            tax = tax,
                            taxSlab = taxSlab,
                            expiryDate = expiryDate,
                            createdBy = user,
                        )
                        product.save()
                        messages.success(request, INFO_PRODUCT_ADDITION_SUCCESS)
                        listOfProducts = Product.objects.filter(createdBy=user).filter(isActive=True)
                        context['listOfProducts'] = listOfProducts
                        if 'save_display' in request.POST:
                            print('Here')
                            return render(request, 'product/listOfProducts.html', context)
                        elif 'save_add' in request.POST:
                            print('Here 1')
                            addProductsInLineForm(request, context)
                            return render(request, 'product/addProduct.html', context)
            except Exception as ex:
                print(ex)
                messages.error(request, INFO_PRODUCT_ADDITION_FAILURE)
                addProductsInLineForm(request, context)
                return render(request, 'product/addProduct.html', context)
    # form1 = ProductForm(request.POST or None)
    # # form1 = CategoryForm()
    # if form1.is_valid():
    #     instance = form1.save(commit=False)
    #     instance.save()
    #
    # form2 = TaxForm(request.POST or None)
    # # form1 = CategoryForm()
    # if form2.is_valid():
    #     instance = form2.save(commit=False)
    #     instance.save()
    #
    # form3 = BrandForm(request.POST or None)
    # # form1 = CategoryForm()
    # if form3.is_valid():
    #     instance = form3.save(commit=False)
    #     instance.save()
    #
    # form4 = TaxSlabForm(request.POST or None)
    # # form1 = CategoryForm()
    # if form4.is_valid():
    #     instance = form4.save(commit=False)
    #     instance.save()
    #
    # context['form1'] = form1
    # context['form2'] = form2
    # context['form3'] = form3
    # context['form4'] = form4
    addProductsInLineForm(request,context)
    return render(request, 'product/addProduct.html', context)
예제 #18
0
def addcontent(request):
    if request.method == 'POST':  # form post edildiyse
        form = ContentForm(request.POST, request.FILES)
        if form.is_valid():
            current_user = request.user
            data = Product()
            data.user_id = current_user.id
            data.category = form.cleaned_data['category']
            data.title = form.cleaned_data['title']
            data.keywords = form.cleaned_data['keywords']
            data.description = form.cleaned_data['description']
            data.price = form.cleaned_data['price']
            data.amount = form.cleaned_data['amount']
            data.detail = form.cleaned_data['detail']
            data.slug = form.cleaned_data['slug']
            data.status = 'False'
            data.save()
            messages.success(request, "Your Content Inserted successfully.")
            return HttpResponseRedirect('/user/contents')
        else:
            messages.success(request,
                             "Content Form error :" + str(form.errors))
            return HttpResponseRedirect('/user/addcontent')
    else:
        category = Category.objects.all()
        form = ContentForm()
        context = {
            'form': form,
            'category': category,
        }
        return render(request, 'user_addcontent.html', context)
예제 #19
0
파일: models.py 프로젝트: hnejadi/EShop-2
        verbose_name = _("product featured sorting")
        verbose_name_plural = _("products featured sorting")


# Patch Product
def get_main_units(self):
    product = self
    units = [p for p in product.productattribute_set.all() \
                                        if p.option.name == 'unita-di-misura']
    if units:
        units = units[0].value
    else:
        units = u'Kg' # default value
    return units

Product.add_to_class("get_main_units", get_main_units)


# Patch Order
def shipping_extimated_date(self):
    order = self
    method = shipping_method_by_key(order.shipping_model)
    if method.valid():
        expected_delivery = method.expectedDelivery(order.contact)

    try:
        shipment = Shipment.objects.get(order=order)
        humanize_times = HumanizeTimes()
        start = shipment.mission.starts
        end = shipment.mission.ends
        start_str = start.strftime("%H:%M")
예제 #20
0
def import_ws_product_detail(re_notice):
    msg = ''
    success_ids = []
    for j in re_notice:

        p = Product.objects.filter(choies_sku=re_notice[j]['model']).first()
        if p:
            continue
            pass
        else:
            try:
                product = Product()
                product.category_id = re_notice[j]['category']
                product.name = re_notice[j]['name']
                product.cn_name = re_notice[j]['cn_name']
                product.cost = re_notice[j]['cost']
                product.manager_id = 1
                product.choies_sku = re_notice[j]['model']
                product.weight = re_notice[j]['weight']
                product.description = re_notice[j]['size']
                product.choies_supplier_name = re_notice[j]['supplier_name']
                product.choies_site_url = re_notice[j]['site_url']
                product.price = re_notice[j]['other']
                product.save()
                success_ids.append(product.id)

                supplier = Supplier.objects.filter(
                    deleted=False, name=re_notice[j]['supplier_name']).first()
                if not supplier:
                    supplier = Supplier.objects.create(
                        name=re_notice[j]['supplier_name'])

            except Exception, e:
                msg += "失败创建product:%s%s%s |" % (
                    re_notice[j]['model'], re_notice[j]['category'], str(e))
예제 #21
0
        verbose_name_plural = _("products featured sorting")


# Patch Product
def get_main_units(self):
    product = self
    units = [p for p in product.productattribute_set.all() \
                                        if p.option.name == 'unita-di-misura']
    if units:
        units = units[0].value
    else:
        units = u'Kg'  # default value
    return units


Product.add_to_class("get_main_units", get_main_units)


# Patch Order
def shipping_extimated_date(self):
    order = self
    method = shipping_method_by_key(order.shipping_model)
    if method.valid():
        expected_delivery = method.expectedDelivery(order.contact)

    try:
        shipment = Shipment.objects.get(order=order)
        humanize_times = HumanizeTimes()
        start = shipment.mission.starts
        end = shipment.mission.ends
        start_str = start.strftime("%H:%M")
예제 #22
0
    def handle_noargs(self, **options):
        from satchmo_store.contact.models import (
            AddressBook,
            Contact,
            ContactOrganization,
            ContactOrganizationRole,
            ContactRole,
            Organization,
            PhoneNumber,
        )
        from product.models import (
            Category,
            OptionGroup,
            Option,
            Price,
            Product,
        )
        from product.modules.configurable.models import ConfigurableProduct

        from satchmo_store.shop.models import Config
        from django.conf import settings
        from l10n.models import Country
        from django.contrib.sites.models import Site
        from django.contrib.auth.models import User
        #idempotency test

        print "Checking for existing sample data."
        try:
            p = Product.objects.get(slug="dj-rocks")
            print "It looks like you already have loaded the sample store data, quitting."
            import sys
            sys.exit(1)
        except Product.DoesNotExist:
            pass

        print "Loading sample store data."

        #Load basic configuration information

        print "Creating site..."
        try:
            site = Site.objects.get(id=settings.SITE_ID)
            print "Using existing site #%i" % settings.SITE_ID
        except Site.DoesNotExist:
            print "Creating Example Store Site"
            site = Site(domain="localhost", name="Sample Store")
        site.domain = settings.SITE_DOMAIN
        site.name = settings.SITE_NAME
        site.save()
        store_country = Country.objects.get(iso3_code='USA')
        config = Config(site=site,
                        store_name=settings.SITE_NAME,
                        country=store_country,
                        sales_country=store_country)
        config.save()
        config.shipping_countries.add(store_country)
        config.save()
        print "Creating Customers..."
        # Import some customers

        customer = ContactRole.objects.get(pk='Customer')
        c1 = Contact(first_name="Chris",
                     last_name="Smith",
                     email="*****@*****.**",
                     role=customer,
                     notes="Really cool stuff")
        c1.save()
        p1 = PhoneNumber(contact=c1,
                         phone="601-555-5511",
                         type="Home",
                         primary=True)
        p1.save()
        c2 = Contact(first_name="John",
                     last_name="Smith",
                     email="*****@*****.**",
                     role=customer,
                     notes="Second user")
        c2.save()
        p2 = PhoneNumber(contact=c2,
                         phone="999-555-5111",
                         type="Work",
                         primary=True)
        p2.save()
        # Import some addresses for these customers
        us = Country.objects.get(iso2_code='US')
        a1 = AddressBook(description="Home",
                         street1="8235 Pike Street",
                         city="Anywhere Town",
                         state="TN",
                         postal_code="38138",
                         country=us,
                         is_default_shipping=True,
                         contact=c1)
        a1.save()
        a2 = AddressBook(description="Work",
                         street1="1245 Main Street",
                         city="Stillwater",
                         state="MN",
                         postal_code="55082",
                         country=us,
                         is_default_shipping=True,
                         contact=c2)
        a2.save()
        print "Creating Suppliers..."
        #Import some suppliers

        supplier = ContactOrganizationRole.objects.get(pk='Supplier')
        company = ContactOrganization.objects.get(pk='Company')
        contactsupplier = ContactRole.objects.get(pk='Supplier')
        org1 = Organization(name="Rhinestone Ronny",
                            type=company,
                            role=supplier)
        org1.save()
        c4 = Contact(first_name="Fred",
                     last_name="Jones",
                     email="*****@*****.**",
                     role=contactsupplier,
                     organization=org1)
        c4.save()
        p4 = PhoneNumber(contact=c4,
                         phone="800-188-7611",
                         type="Work",
                         primary=True)
        p4.save()
        p5 = PhoneNumber(contact=c4, phone="755-555-1111", type="Fax")
        p5.save()
        a3 = AddressBook(contact=c4,
                         description="Mailing address",
                         street1="Receiving Dept",
                         street2="918 Funky Town St",
                         city="Fishkill",
                         state="NJ",
                         country=us,
                         postal_code="19010")
        a3.save()
        #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200",
        #              city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**",
        #              notes="My main supplier")
        #s1.save()

        #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane",
        #    city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**",
        #              notes="Shirt Supplier")
        #s2.save()

        print "Creating Categories..."
        #Create some categories
        cat1 = Category(site=site,
                        name="Shirts",
                        slug="shirts",
                        description="Women's Shirts")
        cat1.save()
        cat2 = Category(site=site,
                        name="Short Sleeve",
                        slug="shortsleeve",
                        description="Short sleeve shirts",
                        parent=cat1)
        cat2.save()
        cat3 = Category(site=site,
                        name="Books",
                        slug="book",
                        description="Books")
        cat3.save()
        cat4 = Category(site=site,
                        name="Fiction",
                        slug="fiction",
                        description="Fiction Books",
                        parent=cat3)
        cat4.save()
        cat5 = Category(site=site,
                        name="Science Fiction",
                        slug="scifi",
                        description="Science Fiction",
                        parent=cat4)
        cat5.save()
        cat6 = Category(site=site,
                        name="Non Fiction",
                        slug="nonfiction",
                        description="Non Fiction",
                        parent=cat3)
        cat6.save()
        cat7 = Category(site=site, name="Software", slug="software")
        cat7.save()

        print "Creating products..."
        #Create some items
        i1 = Product(site=site,
                     name="Django Rocks shirt",
                     slug="dj-rocks",
                     description="Really cool shirt",
                     active=True,
                     featured=True)
        i1.save()
        p1 = Price(price="20.00", product=i1)
        p1.save()
        i1.category.add(cat1)
        i1.save()
        i2 = Product(
            site=site,
            name="Python Rocks shirt",
            slug="PY-Rocks",
            description="Really cool python shirt - One Size Fits All",
            active=True,
            featured=True)
        i2.save()
        p2 = Price(price="19.50", product=i2)
        p2.save()
        i2.category.add(cat2)
        i2.save()
        i3 = Product(site=site,
                     name="A really neat book",
                     slug="neat-book",
                     description="A neat book.  You should buy it.",
                     active=True,
                     featured=True)
        i3.save()
        p3 = Price(price="5.00", product=i3)
        p3.save()
        i3.category.add(cat4)
        i3.save()
        i4 = Product(site=site,
                     name="Robots Attack!",
                     slug="robot-attack",
                     description="Robots try to take over the world.",
                     active=True,
                     featured=True)
        i4.save()
        p4 = Price(price="7.99", product=i4)
        p4.save()
        i4.category.add(cat5)
        i4.save()

        #    i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True)
        #    i5.save()
        #    i5.category.add(cat7)
        #    i5.save()

        #Create an attribute set
        optSet1 = OptionGroup(site=site, name="sizes", sort_order=1)
        optSet2 = OptionGroup(site=site, name="colors", sort_order=2)
        optSet1.save()
        optSet2.save()

        optSet3 = OptionGroup(site=site, name="Book type", sort_order=1)
        optSet3.save()

        optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5)
        optSet4.save()

        optItem1a = Option(name="Small",
                           value="S",
                           sort_order=1,
                           option_group=optSet1)
        optItem1a.save()
        optItem1b = Option(name="Medium",
                           value="M",
                           sort_order=2,
                           option_group=optSet1)
        optItem1b.save()
        optItem1c = Option(name="Large",
                           value="L",
                           sort_order=3,
                           price_change="1.00",
                           option_group=optSet1)
        optItem1c.save()

        optItem2a = Option(name="Black",
                           value="B",
                           sort_order=1,
                           option_group=optSet2)
        optItem2a.save()
        optItem2b = Option(name="White",
                           value="W",
                           sort_order=2,
                           option_group=optSet2)
        optItem2b.save()
        optItem2c = Option(name="Blue",
                           value="BL",
                           sort_order=3,
                           price_change="2.00",
                           option_group=optSet2)
        optItem2c.save()

        optItem3a = Option(name="Hard cover",
                           value="hard",
                           sort_order=1,
                           option_group=optSet3)
        optItem3a.save()
        optItem3b = Option(name="Soft cover",
                           value="soft",
                           sort_order=2,
                           price_change="1.00",
                           option_group=optSet3)
        optItem3b.save()
        optItem3c = Option(name="On tape",
                           value="tape",
                           sort_order=3,
                           option_group=optSet3)
        optItem3c.save()

        optItem4a = Option(name="Full Version",
                           value="full",
                           option_group=optSet4,
                           sort_order=1)
        optItem4a.save()
        optItem4b = Option(name="Upgrade Version",
                           value="upgrade",
                           option_group=optSet4,
                           sort_order=2)
        optItem4b.save()

        #Add the option group to our items
        pg1 = ConfigurableProduct(product=i1)
        pg1.save()
        pg1.option_group.add(optSet1)
        pg1.save()
        pg1.option_group.add(optSet2)
        pg1.save()

        pg3 = ConfigurableProduct(product=i3)
        pg3.save()
        pg3.option_group.add(optSet3)
        pg3.save()

        pg4 = ConfigurableProduct(product=i4)
        pg4.save()
        pg4.option_group.add(optSet3)
        pg4.save()

        #    pg5 = ConfigurableProduct(product=i5)
        #    pg5.option_group.add(optSet4)
        #    pg5.save()

        print "Creating product variations..."
        #Create the required sub_items
        pg1.create_all_variations()
        pg3.create_all_variations()
        pg4.create_all_variations()
        #pg5.create_all_variations()

        #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required.
        #    pv1 = pg5.get_product_from_options([optItem4a])
        #    Price(product=pv1, price='5.00').save()
        #    Price(product=pv1, price='2.00', quantity='50.00').save()
        #    DownloadableProduct(product=pv1).save()

        #    pv2 = pg5.get_product_from_options([optItem4b])
        #    Price(product=pv2, price='1.00').save()
        #    DownloadableProduct(product=pv2).save()

        print "Create a test user..."
        #First see if our test user is still there, then use or create that user
        try:
            test_user = User.objects.get(username="******")
        except:
            test_user = User.objects.create_user('csmith',
                                                 '*****@*****.**', 'test')
            test_user.save()
        c1.user = test_user
        c1.save()
def sync_products():
    start = datetime.now()
    car_model_list = {
        "Sonata": ["sonata"],
        "Elantra": ["elantra"],
        "Santa Fe": ["santafe"],
        "Porter2": ["porter2"],
        "Porter": ["porter1"],
        "Istana": ["istana"],
        "Solaris": ["solaris"],
        "Bongo": ["bongo3"],
        "Starex": ["starex"],
        "Grace": ["grace"],
        "Spectra": ["spectra"],
        "Tucson": ["tukson"],
        "Accent": ["accent"],
        "HD": ["hd65", "hd72", "hd78"],
        "Rio": ["rio"],
        "COROLLA": ["corolla"],
        "Ducato": ["ducato"],
        "TRANSIT": ["tranzit"],
        "LOGAN": ["logan"],
        "L200": ["l200"],
        "Peugeot boxer": ["bokser"],
        "Sportage": ["sportage"],
        "IX35": ["ix35"],
        "Aero tawn": ["aerotaun"],
        "FOCUS": ["fokus"],
        "JUMPER": ["dzhamper"],
        "Cerato": ["serato"],
        "Besta": ["besta"],
        "Trajet": ["tradzhet"],
        "Sorento": ["sorento"],
        "Ceed": ["ceed"],
        "Terracan": ["terakan"],
        "Pregio": ["pajero"],
        "Soul": ["soul"],
        "Tourneo connect": ["tourneo-connect"],
        "Carnival": ["carnival"],
    }
    # Bring dict keys to lowercase
    lower_cars = {}
    for key, value in car_model_list.items():
        lower_cars[key.lower()] = value

    f = 0
    csv_ids = []

    with open(settings.ONE_C_PRICE, encoding="utf-8") as file:
        reader = csv.reader(file, delimiter=";")
        csv_list = list(reader)

    csv_dict = []
    i = 0
    for product in csv_list:
        try:
            csv_ids.append(int(product[1]))
            csv_dict.append(
                {
                    "name": product[0],
                    "one_c_id": int(product[1]),
                    "brand": product[6] if product[6] else "origin",
                    "car_model": product[3].lower(),
                    "cat_number": product[4],
                    "price": float(product[5]) if product[5] else 0,
                    "quantity": int(product[8]) if product[8] else 0,
                    "availability_days": 0,
                }
            )
        except:
            i += 1

    products = Product.objects.all()
    product_id_list = [x.one_c_id for x in products]
    print("Lenght of product id list is:", len(product_id_list))
    update_list = []
    create_list = []
    obj_create_list = []
    i = 0
    j = 0
    for csv_prod in csv_dict:
        brand = None
        car_model = None
        try:
            brand = BrandsDict.objects.get(brand=csv_prod["brand"])
        except:
            pass
        #     try:
        #         car_model = CarModel.objects.get(slug=csv_prod['car_model'])
        #         car_model_list = cars[csv_prod['car_model']]
        #     except:
        #         pass

        if csv_prod["one_c_id"] in product_id_list:
            # update product herer
            i += 1
            update_list.append(csv_prod)
            django_product = Product.objects.get(one_c_id=csv_prod["one_c_id"])
            try:
                stock = Stock.objects.get(product=django_product, store=1)
                stock.price = csv_prod["price"]
                stock.quantity = csv_prod["quantity"]
                stock.save()
            except:
                new_stock = Stock(
                    product=django_product,
                    store=Store.objects.get(id=1),
                    price=csv_prod["price"],
                    quantity=csv_prod["quantity"],
                )
                new_stock.save()
        else:
            # create product here
            j += 1
            create_list.append(csv_prod)

            new_product = Product(
                name=csv_prod["name"],
                brand=brand,
                one_c_id=csv_prod["one_c_id"],
                cat_number=csv_prod["cat_number"],
            )
            new_product.save()
            try:
                for car in lower_cars[csv_prod["car_model"].lower()]:
                    try:
                        car_model = CarModel.objects.get(slug=car.lower())
                        new_product.car_model.add(car_model)
                    except:
                        f += 1
            except:
                pass
            st = Stock(
                product=new_product,
                store=Store.objects.get(id=1),
                price=csv_prod["price"],
                quantity=csv_prod["quantity"],
            )
            st.save()

    end = datetime.now()
    print(f"Sync script ended up in:", end - start)
    print(f"Products updated:", j, "Products the same: ", i)
예제 #24
0
    def post(self, request):
        global product, main
        form0 = MainForm(request.POST)
        form1 = StepOneForm(request.POST)
        form2 = StepTwoForm(request.POST)
        form3 = StepThreeForm(request.POST)
        formset = StepFourFormSet(request.POST)

        if form0.is_valid():
            main = form0.save()
            self.log(user=request.user,
                     action="제품생산",
                     obj=main,
                     extra=model_to_dict(main))

        if form1.is_valid():
            stepOneProductEgg = [[key, value]
                                 for key, value in form1.cleaned_data.items()]
            memo = [
                stepOneProductEgg[i][1]
                for i in range(2, len(stepOneProductEgg), 3)
            ]  # 메모만 가져오기
            validStepOne = ProductEgg.makeVaildinfo(stepOneProductEgg, memo)
            ProductEgg.insertInfo(main, validStepOne)
            ProductEgg.getLossOpenEggPercent(main)

        if form2.is_valid():
            stepTwoProductEgg = [[key, value]
                                 for key, value in form2.cleaned_data.items()]
            memo = [
                stepTwoProductEgg[i][1]
                for i in range(1, len(stepTwoProductEgg), 2)
            ]
            validStepTwo = ProductEgg.makeVaildinfo(stepTwoProductEgg, memo)
            ProductEgg.insertInfo(main, validStepTwo)

        if form3.is_valid():
            stepThreeProductEgg = [
                [key, value] for key, value in form3.cleaned_data.items()
            ]
            memo = [
                stepThreeProductEgg[i][1]
                for i in range(1, len(stepThreeProductEgg), 2)
            ]
            validStepThree = ProductEgg.makeVaildinfo(stepThreeProductEgg,
                                                      memo)
            ProductEgg.insertInfo(main, validStepThree)

        if formset.is_valid():
            for form in formset:
                code = form.cleaned_data.get('product', None)
                amount = form.cleaned_data.get('amount', None)
                amount_kg = form.cleaned_data.get('amount_kg', None)
                count = form.cleaned_data.get('count', None)
                memo = form.cleaned_data.get('memo', None)
                KCFRESH_LOCATION_CODE: str = '00301'
                location = Location.objects.get(
                    code=KCFRESH_LOCATION_CODE)  # kcfresh 본사

                if code and count > 0:
                    productCode = ProductCode.objects.get(code=code)
                    productExist = Product.objects.filter(code=code).filter(
                        ymd=main.ymd).first()
                    if not productExist:
                        product = Product.objects.create(
                            master_id=main,
                            ymd=main.ymd,
                            code=code,
                            codeName=productCode.codeName,
                            productCode=productCode,
                            amount=amount,
                            amount_kg=amount_kg,
                            count=count,
                            memo=memo)

                        productAdmin = ProductAdmin.objects.create(
                            product_id=product,
                            amount=amount,
                            count=count,
                            ymd=main.ymd,
                            location=location,
                        )
                        product.save()
                        productAdmin.save()
                    else:
                        productExist.amount += Decimal(amount)
                        productExist.count += count
                        productExistAdmin = ProductAdmin.objects.filter(releaseType='생성') \
                            .filter(product_id=productExist).first()
                        productExistAdmin.amount += Decimal(amount)
                        productExistAdmin.count += count
                        productExist.save()
                        productExistAdmin.save()

                    for packing in AutoPacking.objects.filter(
                            productCode=productCode):
                        packing_product = productExist if productExist else product
                        packing_count = int(count) // int(packing.count)
                        Packing.objects.create(
                            ymd=main.ymd,
                            type='생산',
                            code=packing.packingCode.code,
                            codeName=packing.packingCode.codeName,
                            count=-packing_count,
                            packingCode=packing.packingCode,
                            productCode=packing_product,
                            autoRelease='자동출고',
                        )

            Product.getLossProductPercent(main)
        return redirect('productList')
예제 #25
0
def delete_product(product_id):
    deleting_product = Product.objects.get(id=product_id)
    Product.delete(deleting_product)
예제 #26
0
    def setUp(self):
        client = Client()

        Category.objects.create(id=1, name='스니커즈')

        Brand.objects.create(
            id=1,
            name='Jordan',
            image_url=
            'https://heuream-images.s3.ap-northeast-2.amazonaws.com/heuream-brand_image/heuream-brand_image/d_5_dc2727e24e2f4741b4afde50f4f4a5f0.png'
        )

        BrandLine.objects.create(id=1, name='1', brand=Brand.objects.get(id=1))

        Product.objects.bulk_create([
            Product(id=1,
                    korean_name='엄청 이쁜 조던 1',
                    english_name='Ultra Super Jordan 1',
                    models_number='WO123on',
                    best_color='REALRED',
                    release_date='2222-12-01',
                    release_price=1299999.00,
                    sell_count=0,
                    category=Category.objects.get(id=1),
                    brand=Brand.objects.get(id=1),
                    brand_line=BrandLine.objects.get(id=1)),
            Product(id=2,
                    korean_name='조던 1 레트로 하이 OG 유니버시티 블루',
                    english_name='Jordan 1 Retro High OG University Blue',
                    models_number='555088-134',
                    best_color='WHITE/UNIVERSITY',
                    release_date='2222-12-01',
                    release_price=1299999.00,
                    sell_count=10,
                    category=Category.objects.get(id=1),
                    brand=Brand.objects.get(id=1),
                    brand_line=BrandLine.objects.get(id=1)),
            Product(id=3,
                    korean_name='조던 6 레트로 카마인 2021',
                    english_name='Jordan 6 Retro Carmine 2021',
                    models_number='CT8529-106',
                    best_color='WHITE/BLACK-CARMINE',
                    release_date='2222-12-01',
                    release_price=1299999.00,
                    sell_count=5,
                    category=Category.objects.get(id=1),
                    brand=Brand.objects.get(id=1),
                    brand_line=BrandLine.objects.get(id=1))
        ])

        ProductImage.objects.bulk_create([
            ProductImage(
                id=1,
                image_url=
                'https://kream-phinf.pstatic.net/MjAyMTAyMDNfMjY2/MDAxNjEyMzE3NDQ1NTAx.Oejtk7Y6zAvCrjhtND50c7JClIDq5g75DlJ391D3Rfkg.nukMbPmTeoKRGgSvfzBM9ZoF0JaqIw6Ge5TkWfncHHUg.PNG/p_56ffd2340d6c476da2f58c151e0205c2.png?type=m',
                product=Product.objects.get(id=1)),
            ProductImage(
                id=2,
                image_url=
                'https://kream-phinf.pstatic.net/MjAyMTAxMjlfMjY1/MDAxNjExOTExMDk2MTk3.1MZuTEku1jlLYcE_HdTcgrqTDj-lTgnDxBnZG2kJem0g.oYV3sKYXXx6s9BV9RxJCu73ImL4ALZrGpqE6v_aanOcg.PNG/p_6e61fca4282c4d84ab532ba227686965.png?type=m',
                product=Product.objects.get(id=2)),
            ProductImage(
                id=3,
                image_url=
                'https://kream-phinf.pstatic.net/MjAyMTAzMDhfMjQ4/MDAxNjE1MTMwODIxNTgy.VS50ej9g1IPn3FflN2ypdEkK09xTg2g6-UJWBdYs3sYg.NN0qISq4PfRzWFqqzRelxjWxQz9XTyZf7Ji3tGyyxQwg.PNG/p_6249c81c28db4270b9aa79d93ef4f245.png?type=m',
                product=Product.objects.get(id=3))
        ])
예제 #27
0
    def get_product(self, day, schedule=None, tour_time=None, create=True):
        """
        Get the TourProduct for the given day and time.  If create is false and product does
        not exist, return None.
        """

        if schedule and tour_time:
            assert False, 'Make up your mind, use a schedule or a tour_time, not both'
        if not schedule and not tour_time:
            assert False, 'Need a time buddy'

        try:
            if schedule:
                tour_product = TourProduct.objects.filter(tour_type=self, day=day).filter(
                    Q(schedule=schedule) | Q(tour_time=schedule.tour_time))[0]
            else:
                tour_product = TourProduct.objects.get(tour_type=self, day=day, tour_time=tour_time)

            if tour_product.tour_type.has_price_raise():
                p = tour_product.product.price_set.all()[0]
                p.price = self.get_raised_base_price(tour_product.day)
                p.save()

            return tour_product
        except (TourProduct.DoesNotExist, IndexError):
            if create:
                # print 'creating product... ', day
                product = Product()
                product.site = Site.objects.get_current()
                product.name = '%s on %s at ' % (self.name, day.strftime('%B %d, %Y'))
                if schedule:
                    product.name += schedule.tour_time.strftime('%I:%M %p')
                else:
                    product.name += tour_time.strftime('%I:%M %p')
                product.items_in_stock = self.get_capacity_for_day(day)
                product.shipclass = 'NO'  # see product.models.SHIP_CLASS_CHOICES
                product.save()

                tour_product = TourProduct()
                tour_product.product = product
                tour_product.tour_type = self
                tour_product.day = day
                if schedule:
                    tour_product.schedule = schedule
                    tour_product.tour_time = schedule.tour_time
                else:
                    tour_product.schedule = None
                    tour_product.tour_time = tour_time
                tour_product.save()

                p = Price()
                p.product = product
                if tour_product.tour_type.has_price_raise():
                    p.price = self.get_raised_base_price(tour_product.day)
                else:
                    p.price = self.base_price
                p.save()

                # Create Variations
                if self.option_group_id:
                    configurable_product = ConfigurableProduct(product=product)
                    configurable_product.save()
                    configurable_product.option_group.add(self.option_group)
                    configurable_product.create_subs = True
                    configurable_product.save()
                return tour_product
            else:
                return None
예제 #28
0
파일: views.py 프로젝트: jw1/insmart
def adjust_product_inventory(product_id, new_count):
    product = Product.objects.filter(id=product_id).first()
    product.current = new_count
    Product.save(product)
예제 #29
0
def gen():
    
    principle = Principle(name='Bombay Sweet', contact_no='01737573157')
    principle.save()

    product_category = ProductCategory(name='Chips')
    product_category.save()
    Product(product_category=product_category, principal=principle, name='Slanty', code='1.06', weight='25 gm',
            mop='80(20×2)', distributor_price='920.0', sell_price='961.0').save()
    Product(product_category=product_category, principal=principle, name='Alooz', code='1.07', weight='25 gm',
            mop='80(20×2)', distributor_price='920.0', sell_price='961.0').save()
    Product(product_category=product_category, principal=principle, name='Potato Ring Chips', code='1.08',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Chipstar ( Cheese Ball)', code='1.09',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Chipstar (onion Ring )', code='1.1',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Pasta Chips (tubes)', code='1.17',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Ring Chips', code='1.01', weight='25 gm',
            mop='80 (20×2)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Potato Crackers', code='1.02', weight='25 gm',
            mop='80(20×4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Bombay Sticks', code='1.03', weight='14 gm',
            mop='80(20×4)', distributor_price='307.28', sell_price='321.0').save()
    Product(product_category=product_category, principal=principle, name='Mr. Twist', code='1.04', weight='25 gm',
            mop='80(20×2)', distributor_price='920.0', sell_price='961.0').save()
    Product(product_category=product_category, principal=principle, name='Korntos', code='1.05', weight='20 gm',
            mop='80(20×4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Chipstar ( Potato Sticks)', code='1.11',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Chipstar ( Cheese Puff)', code='1.12',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Chipstar ( Twister)', code='1.13',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Chipstar (smiley )', code='1.14',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Chipstar (choco Sea )', code='1.15',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()
    Product(product_category=product_category, principal=principle, name='Pasta Chips (shell)', code='1.16',
            weight='20 gm', mop='80(20 * 4)', distributor_price='613.36', sell_price='641.0').save()

    product_category = ProductCategory(name='Chanachur')
    product_category.save()
    Product(product_category=product_category, principal=principle, name='Bombay Mix', code='2.07', weight='30 gm',
            mop='200(25×8)', distributor_price='1073.4', sell_price='1122.0').save()
    Product(product_category=product_category, principal=principle, name='Bombay Mix', code='2.08', weight='200 gm',
            mop='5', distributor_price='153.335', sell_price='160.0').save()
    Product(product_category=product_category, principal=principle, name='Dalmoth', code='2.09', weight='30 gm',
            mop='160(20×8)', distributor_price='982.56', sell_price='1027.0').save()
    Product(product_category=product_category, principal=principle, name='Dalmoth', code='2.1', weight='200 gm',
            mop='5', distributor_price='153.335', sell_price='160.0').save()
    Product(product_category=product_category, principal=principle, name='Bbq', code='2.11', weight='35 gm',
            mop='160(20×8)', distributor_price='1226.73', sell_price='1282.0').save()
    Product(product_category=product_category, principal=principle, name='Bbq', code='2.12', weight='150 gm',
            mop='40(10×4)', distributor_price='924.6', sell_price='966.0').save()
    Product(product_category=product_category, principal=principle, name='Deshi Mix (geen Chilli)', code='2.13',
            weight='35 gm', mop='160 (20×8)', distributor_price='1226.73', sell_price='1282.0').save()
    Product(product_category=product_category, principal=principle, name='Deshi Mix (geen Chilli)', code='2.14',
            weight='150 gm', mop='40(10×4)', distributor_price='924.6', sell_price='966.0').save()
    Product(product_category=product_category, principal=principle, name='Deshi Mix (red Chilli)', code='2.15',
            weight='35 gm', mop='160 (20×8)', distributor_price='1226.73', sell_price='1282.0').save()
    Product(product_category=product_category, principal=principle, name='Deshi Mix (red Chilli)', code='2.16',
            weight='150 gm', mop='40(10×4)', distributor_price='924.6', sell_price='966.0').save()
    Product(product_category=product_category, principal=principle, name='Chanachur', code='2.01', weight='20 gm',
            mop='160 (20×8)', distributor_price='614.56', sell_price='642.0').save()
    Product(product_category=product_category, principal=principle, name='Chanachur', code='2.02', weight='50 gm',
            mop='160(20×8)', distributor_price='1253.04', sell_price='1310.0').save()
    Product(product_category=product_category, principal=principle, name='Chanachur', code='2.03', weight='85 gm',
            mop='80(10×8)', distributor_price='940.24', sell_price='982.0').save()
    Product(product_category=product_category, principal=principle, name='Chanachur', code='2.04', weight='150 gm',
            mop='40(10×4)', distributor_price='805.0', sell_price='841.0').save()
    Product(product_category=product_category, principal=principle, name='Chanachur', code='2.05', weight='300 gm',
            mop='20(5×4)', distributor_price='800.0', sell_price='836.0').save()
    Product(product_category=product_category, principal=principle, name='Chanachur', code='2.06', weight='650 gm',
            mop='8(8×1)', distributor_price='652.78', sell_price='682.0').save()

    product_category = ProductCategory(name='Fruit Drinks')
    product_category.save()
    Product(product_category=product_category, principal=principle, name='Jucy (fruit Drinks)', code='3.01',
            weight='200 ml', mop='20pcs.', distributor_price='303.0', sell_price='317.0').save()

    product_category = ProductCategory(name='Masala')
    product_category.save()
    Product(product_category=product_category, principal=principle, name='Red Chilli', code='4.01', weight='50 gm',
            mop='160(20×8)', distributor_price='2424.0', sell_price='2533.0').save()
    Product(product_category=product_category, principal=principle, name='Red Chilli', code='4.02', weight='100 gm',
            mop='80(10×8)', distributor_price='2578.0', sell_price='2694.0').save()
    Product(product_category=product_category, principal=principle, name='Red Chilli', code='4.03', weight='200 gm',
            mop='40(5×8)', distributor_price='2464.0', sell_price='2575.0').save()
    Product(product_category=product_category, principal=principle, name='Turmeric', code='4.04', weight='50 gm',
            mop='160(20×8)', distributor_price='2424.0', sell_price='2533.0').save()
    Product(product_category=product_category, principal=principle, name='Turmeric', code='4.05', weight='100 gm',
            mop='80(10×8)', distributor_price='2200.0', sell_price='2299.0').save()
    Product(product_category=product_category, principal=principle, name='Turmeric', code='4.06', weight='200 gm',
            mop='40(5×8)', distributor_price='2085.0', sell_price='2179.0').save()
    Product(product_category=product_category, principal=principle, name='Cumin', code='4.07', weight='50 gm',
            mop='160(20×8)', distributor_price='5156.0', sell_price='5389.0').save()
    Product(product_category=product_category, principal=principle, name='Cumin', code='4.08', weight='100 gm',
            mop='80(10×8)', distributor_price='5308.0', sell_price='5547.0').save()
    Product(product_category=product_category, principal=principle, name='Cumin', code='4.09', weight='200 gm',
            mop='40(5×8)', distributor_price='4928.0', sell_price='5150.0').save()

    product_category = ProductCategory(name='Frozen Foods')
    product_category.save()
    Product(product_category=product_category, principal=principle, name='Malaysian Roti Paratha', code='5.01',
            weight='400 gm', mop='12pkt/ctn', distributor_price='552.0', sell_price='600.0').save()
    Product(product_category=product_category, principal=principle, name='malaysian roti paratha (family pack)',
            code='5.02', weight='1600 gm', mop='6pkt/ctn', distributor_price='1012.002', sell_price='1100.0').save()
    Product(product_category=product_category, principal=principle, name='Dal Puri & Alo Puri', code='5.03',
            weight='500 gm', mop='20pkt/ctn', distributor_price='1049.8', sell_price='1100.0').save()
    Product(product_category=product_category, principal=principle, name='Kishan Cheese', code='5.04', weight='200 gm',
            mop='5pkt/kg', distributor_price='800.0', sell_price='856.0').save()
    Product(product_category=product_category, principal=principle, name='Kishan Butter', code='5.05', weight='200 gm',
            mop='5pkt/kg', distributor_price='467.5', sell_price='500.0').save()
예제 #30
0
	sub1.save()
	sub2.save()
	sub3.save()

# opens a file with urls of fake articles
profilePicRead = open("generator/profile_pictures.txt", "r+")
product_title = open("generator/product_names.txt", 'r+')
sentencesRead = open("generator/sentences.txt", "r+")
# then makes into an array split by endline
articleUrl = profilePicRead.read().split("\n")
productTitle = product_title.read().split("\n")
sentences = re.findall(r"\s+[^.!?]*[.!?]", sentencesRead.read())

for i in range(80):
	seed = randint(0,200)
	product = Product()
	product.title = productTitle[seed%(len(productTitle)-1)]
	product.description = sentences[seed%(len(sentences)-1)]
	product.category = categories[randint(1,8888)%categories.count()]
	product.price = round(random.uniform(1.5, 111.9),3)
	
	product.thumbnail = articleUrl[seed%(len(articleUrl)-1)]

	if (int(product.price) % 2) == 0:
		product.discount = True

		product.price_discount_percent = round(random.random()*100)
		product.price_discount = product.price - product.price*product.price_discount_percent/100
	
	else:
		product.discount = False
예제 #31
0
def add_site(sender, instance, **kwargs):
	"""Adds the current page's site to the contact if it hasn't been set."""
	if not instance.site:
		instance.site = Site.objects.get_current()


def user_can_edit(self, user_obj):
	'''
	This function will be hooked up to the User model as a method.
	The rule says that a user can only be modified by the same user
	'''
	user_site = user_obj.get_profile().site
	if user_site is not None and self.site == user_site:
		return True
	return False
Product.add_to_class('can_edit', user_can_edit)
registry.register('can_edit', Product)


def is_shop_owner(self):
	"""Returns True when the User is in the 'shop_owner' group."""
	return self.groups.filter(name='shop_owner').count() == 1
User.add_to_class('is_shop_owner', is_shop_owner)


def is_multishop_owner(self):
	"""Returns True when the User is in the 'virtual_shop_owner' group."""
	# TODO: Maybe asking the user's site is a better approach to determine if
	#       the user is running a multishop or a normal shop. This would at
	#       least eliminate the need for the group 'multishop_owner' to have
	#       a hardcoded name.
예제 #32
0
def product_from_post(productslug, formdata):
    product = Product.objects.get_by_site(slug=productslug)
    origproduct = product
    log.debug('found product: %s', product)
    p_types = product.get_subtypes()
    details = []
    zero = Decimal("0.00")

    if 'ConfigurableProduct' in p_types:
        # This happens when productname cannot be updated by javascript.
        cp = product.configurableproduct
        # catching a nasty bug where ConfigurableProducts with no option_groups can't be ordered
        if cp.option_group.count() > 0:
            chosenOptions = optionids_from_post(cp, formdata)
            optproduct = cp.get_product_from_options(chosenOptions)
            if not optproduct:
                log.debug(
                    'Could not fully configure a ConfigurableProduct [%s] with [%s]',
                    product, chosenOptions)
                raise Product.DoesNotExist()
            else:
                product = optproduct

    if 'CustomProduct' in p_types:
        try:
            cp = product.customproduct
        except ObjectDoesNotExist:
            # maybe we've already looked up the subtype product above, try the original
            cp = origproduct.customproduct
        for customfield in cp.custom_text_fields.all():
            if customfield.price_change is not None:
                price_change = customfield.price_change
            else:
                price_change = zero
            data = {
                'name': customfield.translated_name(),
                'value': formdata.get("custom_%s" % customfield.slug, ''),
                'sort_order': customfield.sort_order,
                'price_change': price_change
            }
            details.append(data)
            data = {}
        chosenOptions = optionids_from_post(cp, formdata)
        manager = OptionManager()
        for choice in chosenOptions:
            result = manager.from_unique_id(choice)
            if result.price_change is not None:
                price_change = result.price_change
            else:
                price_change = zero
            data = {
                'name': unicode(result.option_group),
                'value': unicode(result.translated_name()),
                'sort_order': result.sort_order,
                'price_change': price_change
            }
            details.append(data)
            data = {}

    if 'GiftCertificateProduct' in p_types:
        ix = 0
        for field in ('email', 'message'):
            data = {
                'name': field,
                'value': formdata.get("custom_%s" % field, ""),
                'sort_order': ix,
                'price_change': zero,
            }
            ix += 1
            details.append(data)
        log.debug("Gift Certificate details: %s", details)
        data = {}

    return product, details
예제 #33
0
class ProductTest(TestCase):
    _product_name = u"product name"
    _product_description = u"product description"
    _product_slug = u"slug"
    _product_price = 1
    _user_password = u"password"
    _user_email = u"*****@*****.**"

    def setUp(self):
        self.client = Client()
        self.product = Product(
            name=self._product_name,
            slug=self._product_slug,
            price=self._product_price,
            description=self._product_description,
        )
        self.product.save()
        self.user = User.objects.create_user(self._user_email, self._user_email, self._user_password)

    def assert_message_contains(self, response, text, level=None):
        """
        Asserts that there is exactly one message containing the given text.
        """
        messages = response.context["messages"]
        matches = [m for m in messages if text in m.message]
        if len(matches) == 1:
            msg = matches[0]
            if level is not None and msg.level != level:
                self.fail("There was one matching message but with different" "level: %s != %s" % (msg.level, level))
            return
        elif len(matches) == 0:
            messages_str = ", ".join('"%s"' % m for m in messages)
            self.fail('No message contained text "%s", messages were: %s' % (text, messages_str))
        else:
            self.fail('Multiple messages contained text "%s": %s' % (text, ", ".join(('"%s"' % m) for m in matches)))

    def test_product_detail(self):
        """
        Test /products/<slug>/ page
        """
        response = self.client.get(self.product.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "product/product_detail.html")
        self.assertContains(response, self.product.name)
        self.assertContains(response, self.product.description)
        self.assertContains(response, self.product.price)
        return response

    def test_product_comment(self):
        url = reverse("comment")
        """
        Test product's comment creating
        """
        # Send request with empty text field
        response = self.client.post(url, {"product": self.product.id}, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assert_message_contains(response, "This field is required.")

        # Send request with params
        response = self.client.post(url, {"product": self.product.id, "text": "test"}, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assert_message_contains(response, CreateCommentView._success_message)

    def test_product_like(self):
        """
        Test product's liking
        """
        url = reverse("like-product", args=[self.product.slug])
        # Send request with unauthorised user
        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 404)

        self.client.login(username=self._user_email, password=self._user_password)

        # Like firstly succesfully
        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assert_message_contains(response, ProductLikeView._success_message)

        # Like firstly succesfully with error
        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assert_message_contains(response, ProductLikeView._error_message)
예제 #34
0
 def test_should_read_existing_object(self):
     Product(code=TEST_EAN13, name="NAME").save()
     response = get_by_code(TEST_EAN13)
     self.assertEqual(response.name, "NAME")
예제 #35
0
파일: models.py 프로젝트: hnejadi/EShop-2
    def create_variation(self, options, name=u"", sku=u"", slug=u""):
        """Create a productvariation with the specified options.
        Will not create a duplicate."""
        log.debug("Create variation: %s", options)
        variations = self.get_variations_for_options(options)

        if not variations:
            # There isn't an existing ProductVariation.
            if self.product:
                site = self.product.site
            else:
                site = self.site

            variant = Product(site=site, items_in_stock=0, name=name)
            optnames = [opt.value for opt in options]
            if not slug:
                slug = slugify(u'%s_%s' % (self.product.slug, u'_'.join(optnames)))

            while Product.objects.filter(slug=slug).count():
                slug = u'_'.join((slug, unicode(self.product.id)))

            variant.slug = slug

            log.info("Creating variation for [%s] %s", self.product.slug, variant.slug)
            variant.save()

            pv = ProductVariation(product=variant, parent=self)
            pv.save()

            for option in options:
                pv.options.add(option)

            pv.name = name
            pv.sku = sku
            pv.save()

        else:
            variant = variations[0].product
            log.debug("Existing variant: %s", variant)
            dirty = False
            if name and name != variant.name:
                log.debug("Updating name: %s --> %s", self, name)
                variant.name = name
                dirty = True
            if sku and sku != variant.sku:
                variant.sku = sku
                log.debug("Updating sku: %s --> %s", self, sku)
                dirty = True
            if slug:
                # just in case
                slug = slugify(slug)
            if slug and slug != variant.slug:
                variant.slug = slug
                log.debug("Updating slug: %s --> %s", self, slug)
                dirty = True
            if dirty:
                log.debug("Changed existing variant, saving: %s", variant)
                variant.save()
            else:
                log.debug("No change to variant, skipping save: %s", variant)

        return variant
예제 #36
0
    def handle_noargs(self, **options):
        from satchmo_store.contact.models import (
            AddressBook,
            Contact,
            ContactOrganization,
            ContactOrganizationRole,
            ContactRole,
            Organization,
            PhoneNumber,
        )
        from product.models import (
            Category,
            OptionGroup,
            Option,
            Price,
            Product,
        )
        from product.modules.configurable.models import ConfigurableProduct

        from satchmo_store.shop.models import Config
        from django.conf import settings
        from l10n.models import Country
        from django.contrib.sites.models import Site
        from django.contrib.auth.models import User
        #idempotency test

        print "Checking for existing sample data."
        try:
            p = Product.objects.get(slug="dj-rocks")
            print "It looks like you already have loaded the sample store data, quitting."
            import sys
            sys.exit(1)
        except Product.DoesNotExist:
            pass

        print "Loading sample store data."

        #Load basic configuration information

        print "Creating site..."
        try:
            site = Site.objects.get(id=settings.SITE_ID)
            print "Using existing site #%i" % settings.SITE_ID
        except Site.DoesNotExist:
            print "Creating Example Store Site"
            site = Site(domain="localhost", name="Sample Store")
        site.domain = settings.SITE_DOMAIN
        site.name = settings.SITE_NAME
        site.save()
        try:
            store_country = Country.objects.get(iso3_code='USA')
        except Country.DoesNotExist:
            print "\nError: Country data should be first loaded by:  python manage.py satchmo_load_l10n"
            import sys
            sys.exit(1)
        config = Config(site=site, store_name=settings.SITE_NAME, country=store_country, sales_country=store_country)
        config.save()
        config.shipping_countries.add(store_country)
        config.save()
        print "Creating Customers..."
        # Import some customers

        customer = ContactRole.objects.get(pk='Customer')
        c1 = Contact(first_name="Chris", last_name="Smith", email="*****@*****.**", role=customer, notes="Really cool stuff")
        c1.save()
        p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home",primary=True)
        p1.save()
        c2 = Contact(first_name="John", last_name="Smith", email="*****@*****.**", role=customer, notes="Second user")
        c2.save()
        p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work",primary=True)
        p2.save()
        # Import some addresses for these customers
        us = Country.objects.get(iso2_code='US');
        a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN",
                     postal_code="38138", country=us, is_default_shipping=True, contact=c1)
        a1.save()
        a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN",
                     postal_code="55082", country=us, is_default_shipping=True, contact=c2)
        a2.save()
        print "Creating Suppliers..."
        #Import some suppliers

        supplier = ContactOrganizationRole.objects.get(pk='Supplier')
        company = ContactOrganization.objects.get(pk='Company')
        contactsupplier = ContactRole.objects.get(pk='Supplier')
        org1 = Organization(name="Rhinestone Ronny", type=company, role=supplier)
        org1.save()
        c4 = Contact(first_name="Fred", last_name="Jones", email="*****@*****.**",
            role=contactsupplier, organization=org1)
        c4.save()
        p4 = PhoneNumber(contact=c4,phone="800-188-7611", type="Work", primary=True)
        p4.save()
        p5 = PhoneNumber(contact=c4,phone="755-555-1111",type="Fax")
        p5.save()
        a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept",
            street2="918 Funky Town St", city="Fishkill",
             state="NJ", country=us, postal_code="19010")
        a3.save()
        #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200",
        #              city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**",
        #              notes="My main supplier")
        #s1.save()

        #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane",
        #    city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**",
        #              notes="Shirt Supplier")
        #s2.save()


        print "Creating Categories..."
        #Create some categories
        '''cat1 = Category(site=site, name="Shirts",slug="shirts",description="Women's Shirts")
        cat1.save()
        cat2 = Category(site=site, name="Short Sleeve",slug="shortsleeve",description="Short sleeve shirts", parent=cat1)
        cat2.save()'''
        cat3 = Category(name="Books",slug="book",description="Books")
        cat3.save()
        cat3.site.add(site)
        
        '''cat4 = Category(site=site, name="Fiction",slug="fiction",description="Fiction Books", parent=cat3)
        cat4.save()
        cat5 = Category(site=site, name="Science Fiction",slug="scifi",description="Science Fiction",parent=cat4)
        cat5.save()
        cat6 = Category(site=site, name="Non Fiction",slug="nonfiction",description="Non Fiction",parent=cat3)
        cat6.save()
        cat7 = Category(site=site, name="Software", slug="software")
        cat7.save()'''


        print "Creating products..."
        #Create some items
        '''i1 = Product(name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt",
                 active=True, featured=True)
        i1.save()
        p1 = Price(price="20.00", product=i1)
        p1.save()
        i1.category.add(cat1)
        i1.save()
        i2 = Product(name="Python Rocks shirt", slug="PY-Rocks",
            description="Really cool python shirt - One Size Fits All",
            active=True, featured=True)
        i2.save()
        p2 = Price(price="19.50", product=i2)
        p2.save()
        i2.category.add(cat2)
        i2.save()'''
        i3 = Product(name="Purusha Suktam", slug="Advyata",
            description="A neat book.  You should buy it.",
            active=True, featured=True)
        i3.save()
        i3.site.add(site)
        p3 = Price(price="5.00", product=i3)
        p3.save()
        i3.category.add(cat3)
        i3.save()
        i3.site.add(site)


        '''i4 = Product(name="Robots Attack!", slug="robot-attack",
            description="Robots try to take over the world.",
            active=True, featured=True)
        i4.save()
        p4 = Price(price="7.99", product=i4)
        p4.save()
        i4.category.add(cat5)
        i4.save()

    #    i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True)
    #    i5.save()
    #    i5.category.add(cat7)
    #    i5.save()

        #Create an attribute set
        optSet1 = OptionGroup(site=site, name="sizes", sort_order=1)
        optSet2 = OptionGroup(site=site, name="colors", sort_order=2)
        optSet1.save()
        optSet2.save()'''

        optSet3 = OptionGroup(name="Book type", sort_order=1)
        optSet3.save()
        optSet3.site.add(site)

        '''optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5)
        optSet4.save()

        optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1)
        optItem1a.save()
        optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1)
        optItem1b.save()
        optItem1c = Option(name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1)
        optItem1c.save()

        optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2)
        optItem2a.save()
        optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2)
        optItem2b.save()
        optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2)
        optItem2c.save()'''

        optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3)
        optItem3a.save()
        optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3)
        optItem3b.save()
        optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3)
        optItem3c.save()

        '''optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1)
        optItem4a.save()
        optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2)
        optItem4b.save()'''


        #Add the option group to our items
        '''pg1 = ConfigurableProduct(product=i1)
        pg1.save()
        pg1.option_group.add(optSet1)
        pg1.save()
        pg1.option_group.add(optSet2)
        pg1.save()'''

        pg3 = ConfigurableProduct(product=i3)
        pg3.save()
        pg3.option_group.add(optSet3)
        pg3.save()

        '''pg4 = ConfigurableProduct(product=i4)
        pg4.save()
        pg4.option_group.add(optSet3)
        pg4.save()'''

    #    pg5 = ConfigurableProduct(product=i5)
    #    pg5.option_group.add(optSet4)
    #    pg5.save()

        print "Creating product variations..."
        #Create the required sub_items
        #pg1.create_all_variations()
        pg3.create_all_variations()
        #pg4.create_all_variations()
        #pg5.create_all_variations()

        #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required.
    #    pv1 = pg5.get_product_from_options([optItem4a])
    #    Price(product=pv1, price='5.00').save()
    #    Price(product=pv1, price='2.00', quantity='50.00').save()
    #    DownloadableProduct(product=pv1).save()

    #    pv2 = pg5.get_product_from_options([optItem4b])
    #    Price(product=pv2, price='1.00').save()
    #    DownloadableProduct(product=pv2).save()

        print "Create a test user..."
        #First see if our test user is still there, then use or create that user
        try:
            test_user = User.objects.get(username="******")
        except:
            test_user = User.objects.create_user('csmith', '*****@*****.**', 'test')
            test_user.save()
        c1.user = test_user
        c1.save()
예제 #37
0
파일: views.py 프로젝트: owad/service
 def get_context_data(self, **kwargs):
     context = super(ProductListView, self).get_context_data(**kwargs)
     products = Product()
     context['counts'] = products.get_counts()
     return context
예제 #38
0
def addcontent(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            current_user = request.user
            data = Product()
            data.user_id = current_user.id
            data.title = form.cleaned_data['title']
            data.category = form.cleaned_data['category']
            data.price = form.cleaned_data['price']
            data.amount = form.cleaned_data['amount']
            data.detail = form.cleaned_data['detail']
            data.image = form.cleaned_data['image']
            data.slug = form.cleaned_data['slug']

            data.save()
            messages.success(request, 'Success')
            return HttpResponseRedirect('/user/contents')
        else:
            messages.success(request, 'Error : ' + str(form.errors))
            return HttpResponseRedirect('/user/addcontent')

    else:
        category = Category.objects.all()
        menu = Menu.objects.all()
        form = ProductForm()
        context = {
            'menu': menu,
            'category': category,
            'form': form,
        }
        return render(request, 'user_addcontent.html', context)
예제 #39
0
def db_init():
    """ setUp Test """
    user = User.objects.create(email='*****@*****.**')
    user.set_password('@unMotdePasse')
    user.save()

    data = Category(name="Sauce")
    data.save()

    data = Level(name="High")
    data.save()

    data = Product(name="Mayonnaise",
                   url="https://mayo.fr",
                   nutriscore="c",
                   category_id=Category.objects.get(name="Sauce"),
                   photo="https://mayo.fr/photo.jpg",
                   salt_100g="1.00",
                   sugars_100g="2.00",
                   fat_100g="3.00",
                   saturate_fat_100g="4.00",
                   level_salt=Level.objects.get(name="High"),
                   level_sugars=Level.objects.get(name="High"),
                   level_saturate_fat=Level.objects.get(name="High"),
                   level_fat=Level.objects.get(name="High"),
                   code="100200300",
                   last_modified_t="1568887200")
    data.save()

    data = Product(name="Sauce tomate",
                   url="https://Sauce-tomate.fr",
                   nutriscore="b",
                   category_id=Category.objects.get(name="Sauce"),
                   photo="https://Sauce-tomate.fr/photo.jpg",
                   salt_100g="1.00",
                   sugars_100g="2.00",
                   fat_100g="3.00",
                   saturate_fat_100g="4.00",
                   level_salt=Level.objects.get(name="High"),
                   level_sugars=Level.objects.get(name="High"),
                   level_saturate_fat=Level.objects.get(name="High"),
                   level_fat=Level.objects.get(name="High"),
                   code="101201301",
                   last_modified_t="10120130111")
    data.save()

    data = Product(name="Ketchup",
                   url="https://Ketchup.fr",
                   nutriscore="c",
                   category_id=Category.objects.get(name="Sauce"),
                   photo="https://Ketchup.fr/photo.jpg",
                   salt_100g="1.00",
                   sugars_100g="2.00",
                   fat_100g="3.00",
                   saturate_fat_100g="4.00",
                   level_salt=Level.objects.get(name="High"),
                   level_sugars=Level.objects.get(name="High"),
                   level_saturate_fat=Level.objects.get(name="High"),
                   level_fat=Level.objects.get(name="High"),
                   code="102202302",
                   last_modified_t="1768894400")
    data.save()
예제 #40
0
def products_new(request):
    if request.POST:
        form = UserProductForm(request.POST, request.FILES)
        if form.is_valid():
            user = request.user
            data = Product()
            data.user_id = user.id
            data.category_id = request.POST.get('category')
            data.title = form.cleaned_data['title']
            data.keywords = form.cleaned_data['keywords']
            data.description = form.cleaned_data['description']
            data.image = form.cleaned_data['image']
            data.marka = form.cleaned_data['marka']
            data.model = form.cleaned_data['model']
            data.renk = form.cleaned_data['renk']
            data.year = form.cleaned_data['year']
            data.kilometre = form.cleaned_data['kilometre']
            data.vites = form.cleaned_data['vites']
            data.durum = form.cleaned_data['durum']
            data.price = form.cleaned_data['price']
            data.amount = form.cleaned_data['amount']
            data.detail = form.cleaned_data['detail']
            data.slug = form.cleaned_data['slug']
            data.status = 'Evet'
            data.save()

            messages.success(request,
                             'Ürününz Eklendi. <a href="/product/' +
                             str(data.id) + '/' + str(data.slug) +
                             '">Ürüne git >></a>',
                             extra_tags='safe')
            return HttpResponseRedirect('/user/products')
        else:
            messages.error(
                request,
                'Lütfen hatalı alanları düzeltiniz <br>' + str(form.errors))
            return HttpResponseRedirect('/user/products/new')
    else:
        form = UserProductForm()
        user = request.user
        current_user = UserProfile.objects.get(user_id=user.id)
        context = {
            'profile': current_user,
            'form': form,
        }
        return render(request, 'user_products_new.html', context)
예제 #41
0
    def create_variation(self, options, name=u"", sku=u"", slug=u""):
        """Create a productvariation with the specified options.
        Will not create a duplicate."""
        log.debug("Create variation: %s", options)
        variations = self.get_variations_for_options(options)

        if not variations:
            # There isn't an existing ProductVariation.
            if self.product:
                site = self.product.site
            else:
                site = self.site

            variant = Product(site=site, items_in_stock=0, name=name)
            optnames = [opt.value for opt in options]
            if not slug:
                slug = slugify(u'%s_%s' %
                               (self.product.slug, u'_'.join(optnames)))

            while Product.objects.filter(slug=slug).count():
                slug = u'_'.join((slug, unicode(self.product.id)))

            variant.slug = slug

            log.info("Creating variation for [%s] %s", self.product.slug,
                     variant.slug)
            variant.save()

            pv = ProductVariation(product=variant, parent=self)
            pv.save()

            for option in options:
                pv.options.add(option)

            pv.name = name
            pv.sku = sku
            pv.save()

        else:
            variant = variations[0].product
            log.debug("Existing variant: %s", variant)
            dirty = False
            if name and name != variant.name:
                log.debug("Updating name: %s --> %s", self, name)
                variant.name = name
                dirty = True
            if sku and sku != variant.sku:
                variant.sku = sku
                log.debug("Updating sku: %s --> %s", self, sku)
                dirty = True
            if slug:
                # just in case
                slug = slugify(slug)
            if slug and slug != variant.slug:
                variant.slug = slug
                log.debug("Updating slug: %s --> %s", self, slug)
                dirty = True
            if dirty:
                log.debug("Changed existing variant, saving: %s", variant)
                variant.save()
            else:
                log.debug("No change to variant, skipping save: %s", variant)

        return variant
예제 #42
0
 def product_headers(self) -> List:
     self._product_headers = []
     self._product_headers, self._product_ids = Product.published_names()
     return self._product_headers
 def handle(self, *args, **options):
     print "Recalculating product query count"
     Product.recalculate_query_count()
     print "Recalculating company query count"
     Company.recalculate_query_count()
     print "Finished recalculating query count"
예제 #44
0
def wizard_event(request, step='step0', template='localsite/wizard_event.html'):
    wizard = request.session.get('wizard')
    output = {}
    formsets = []
    form = None

    if step == 'step0':
        if not wizard:
            wizard = {}
        product = Product()
        if request.method == 'POST':
            form = ProductForm(request.POST, instance=product)
            formsets.append(EventFormInline(request.POST, instance=product))
            if form.is_valid() and formsets[0].is_valid():
                product = form.save(commit=False)
                product.site = Site.objects.get(id=1)
                product.slug = slugify(cyr2lat(product.name))
                product.save()
                form.save_m2m()
                formsets[0].save()
                event = formsets[0].instance.event
                wizard['event'] = event
                wizard['step'] = 1
                request.session['wizard'] = wizard
                for group in event.hallscheme.groups.all():
                    price = SeatGroupPrice(event=event, group=group)
                    price.save()
                return HttpResponseRedirect('/wizards/event/step1/')
        else:
            form = ProductForm(instance=product)
            formsets.append(EventFormInline(instance=product))
    elif step == 'step1':
        if not wizard:
            return HttpResponseRedirect('/wizards/event/')
        event = wizard['event']
        step = wizard['step']
        if step != 1:
            return HttpResponseRedirect('/wizards/event/')
        if request.method == 'POST':
            form = SeatGroupPriceFormset(request.POST, queryset=event.prices.all())
            if form.is_valid():
                form.save()
                wizard['step'] = 2
                request.session['wizard'] = wizard
                return HttpResponseRedirect('/wizards/event/step2/')
        else:
            form = SeatGroupPriceFormset(queryset=event.prices.all())
    elif step == 'step2':
        template='localsite/wizard_event_dates.html'
        if not wizard:
            return HttpResponseRedirect('/wizards/event/')
        event = wizard['event']
        step = wizard['step']
        if step != 2:
            return HttpResponseRedirect('/wizards/event/')
        if request.method == 'POST':
            formsets.append(EventDateFormInline(request.POST, instance=event))
            if formsets[0].is_valid():
                formsets[0].save()
                wizard['step'] = 3
                request.session['wizard'] = wizard
                return HttpResponseRedirect('/wizards/event/step3/')
        else:
            formsets.append(EventDateFormInline(instance=event))
    elif step == 'step3':
        template='localsite/wizard_product_images.html'
        if not wizard:
            return HttpResponseRedirect('/wizards/event/')
        event = wizard['event']
        step = wizard['step']
        if step != 3:
            return HttpResponseRedirect('/wizards/event/')
        if request.method == 'POST':
            formsets.append(ProductImageFormInline(request.POST, request.FILES, instance=event.product))
            if formsets[0].is_valid():
                formsets[0].save()
                wizard['step'] = 4
                request.session['wizard'] = wizard
                return HttpResponseRedirect('/wizards/event/step4/')
        else:
            formsets.append(ProductImageFormInline(instance=event.product))
    elif step == 'step4':
        if not wizard:
            return HttpResponseRedirect('/wizards/event/')
        event = wizard['event']
        step = wizard['step']
        if step != 4:
            return HttpResponseRedirect('/wizards/event/')
        if request.method == 'POST':
            formsets.append(AnnouncementFormInline(request.POST, request.FILES, instance=event))
            if formsets[0].is_valid():
                formsets[0].save()
                wizard['step'] = 5
                request.session['wizard'] = wizard
                return HttpResponseRedirect('/wizards/event/done/')
        else:
            formsets.append(AnnouncementFormInline(instance=event))
    elif step == 'done':
        template='localsite/wizard_event_done.html'
        if not wizard:
            return HttpResponseRedirect('/wizards/event/')
        event = wizard['event']
        output['event'] = event
        step = wizard['step']
        if step != 5:
            return HttpResponseRedirect('/wizards/event/')
        event.create_all_variations()
        del request.session['wizard']
        return HttpResponseRedirect(event.get_absolute_url())

    if form:
        output['form'] = form
    if formsets:
        output['formsets'] = formsets
    ctx = RequestContext(request, output)
    return render_to_response(template, context_instance=ctx)
예제 #45
0
 def create(self, name: str, description: str) -> Product:
     product = Product(name=name, description=description)
     product.save()
     return product
예제 #46
0
    def handle(self, *args, **kwargs):
        #start_time = time.time()

        with open('outoutfile.json') as json_file:
            data = json.load(json_file)
            #print(data)
            i = 0
            for product in data:
                print(i)
                #print(product)
                title = product['title']
                description = product['description']
                category = product['category']
                try:
                    categoryObj = Category.objects.get(title=category)
                except:
                    categoryObj = Category(title=category, catalog_rep='A')
                    categoryObj.save()
                #dbProduct = Product(name= title,content=(description or ''), category=categoryObj)
                dbProductList = Product.objects.filter(name=title,
                                                       category=categoryObj)
                dbProduct = dbProductList.first()
                if dbProduct == None:
                    dbProduct = Product(category=categoryObj,
                                        name=title,
                                        content=(description or ''),
                                        buy_cost=0)
                    print('creating new product ', dbProduct.name,
                          'description: ', dbProduct.content)
                else:
                    dbProduct.content = description or ''
                    print('updating product ', dbProduct.name, 'description: ',
                          dbProduct.content)

                #print(dbProduct.name)
                #print(dbProduct.content)
                #print(dbProduct.category)
                dbProduct.save()

                if 'image1' in product:
                    dbImage1 = ProductImage(product=dbProduct)
                    with open(product['image1'], 'rb') as f:
                        image_data = File(f)
                        dbImage1.image.save(product['image1'], image_data,
                                            True)
                    dbImage1.save()

                if 'image2' in product:
                    dbImage1 = ProductImage(product=dbProduct)
                    with open(product['image2'], 'rb') as f:
                        image_data = File(f)
                        dbImage1.image.save(product['image2'], image_data,
                                            True)
                    dbImage1.save()

                colors = []
                if 'צבע' in product:
                    colors = product['צבע']
                else:
                    colors = ['no color']

                sizes = []
                if 'גודל' in product:
                    sizes = product['גודל']
                else:
                    sizes = ['one size']
                import itertools
                productStuckList = list(itertools.product(colors, sizes))
                #print(productStuckList)

                from provider.models import Provider

                try:
                    defultProvider = Provider.objects.all()[0]
                except:
                    defultProvider = Provider(name='defult provider')
                    defultProvider.save()

                from packingType.models import PackingType
                try:
                    defultPackingType = PackingType.objects.all()[0]
                except:
                    defultPackingType = PackingType(name='defult packing')
                    defultPackingType.save()

                for stock in productStuckList:
                    from stock.models import Stock

                    from productSize.models import ProductSize
                    dbProductSize = None
                    try:
                        dbProductSize = ProductSize.objects.get(size=stock[1])
                    except:
                        dbProductSize = ProductSize(size=stock[1])
                        dbProductSize.save()

                    from productColor.models import ProductColor
                    dbProductColor = None
                    try:
                        dbProductColor = ProductColor.objects.get(
                            name=stock[0])
                    except:
                        dbProductColor = ProductColor(name=stock[0])
                        dbProductColor.save()

                    stock, created = Stock.objects.update_or_create(
                        provider=defultProvider,
                        productSize=dbProductSize,
                        productColor=dbProductColor,
                        product=dbProduct,
                        packingType=defultPackingType)
                    print(created, stock.product, stock.productSize,
                          stock.productColor)
                    stock.save()

                i += 1

        #end_time = time.time()
        #print('imported in ' + (end_time - start_time) + ' seconds' )

        pass
예제 #47
0
 def get(request):
     products = Product.get_all()
     return TemplateResponse(request, 'products.html', {
         'products': products,
         'error_messages': {}
     })