• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Product类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Product的典型用法代码示例。如果您正苦于以下问题:Python Product类的具体用法?Python Product怎么用?Python Product使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Product类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: ProductTests

class ProductTests(TestCase):
    def setUp(self):
        stuff = FoodStuff(name='some stuff 2')
        stuff.save()

        recipe = Recipe(name='some recipe 2')
        recipe.save()

        ingredient = RecipeIngredient(stuff=stuff, recipe=recipe, count=1.5)
        ingredient.save()

        self.product = Product(name='some product 2', recipe=recipe)
        self.product.save()

    def test_str(self):
        self.assertEqual('some product 2', str(self.product))

    def test_prepare_price(self):
        check = self.product.prepare_price(100)
        self.assertEqual(100, check)

        self.product.markup = 2
        check = self.product.prepare_price(100)
        self.assertEqual(200, check)

        self.product.markup = 1.44
        check = self.product.prepare_price(100)
        self.assertEqual(150, check)
开发者ID:silverozzo,项目名称:tango4,代码行数:28,代码来源:tests.py


示例2: AddProduct

def AddProduct(request):
    if request.POST.has_key('display_name'):
        NewDisplayName = request.POST['display_name']
    if request.POST.has_key('detail_name'):
        NewDetailName = request.POST['detail_name']
    if request.POST.has_key('material'):
        NewMaterial = request.POST['material']
    if request.POST.has_key('series'):
        NewSeries = request.POST['series']
    if request.POST.has_key('function'):
        NewFunction = request.POST['function']
    if request.POST.has_key('origin'):
        NewOrigin = request.POST['origin']
    AlreadyExist = Product.objects.filter(
        display_name=NewDisplayName,
        detail_name=NewDetailName,
        material=NewMaterial,
        series=NewSeries,
        function=NewFunction,
        origin=NewOrigin
    )
    if len(AlreadyExist) != 0:
        #该产品已存在
        result="AlreadyExist"
        return HttpResponse(result, mimetype="application/text")
    productToAdd = Product(
        display_name=NewDisplayName,
        detail_name=NewDetailName,
        material=NewMaterial,
        series=NewSeries,
        function=NewFunction,
        origin=NewOrigin
    )
    productToAdd.save()
    return HttpResponse(productToAdd.id, mimetype="application/text")
开发者ID:zcb0821,项目名称:yanfenghupo,代码行数:35,代码来源:views.py


示例3: manage_settings

    def manage_settings(self, product):
        product_data = self.retrieve_product(product)
        if type(product_data) is str:
            title = "%s Manage Settings" % product.title()
            product_data = None
            form = forms.ManageProduct()
        else:
            title = "%s Manage Settings" % product_data.title
            form = forms.ManageProduct(obj=product_data)

        if request.method == "POST" and form.validate_on_submit():
            to_save = Product(request.form.to_dict())
            if product_data and product_data.db_name:
                to_save.db_name = product_data.db_name
                to_save.groups = product_data.groups
            else:
                to_save.set_db_name()

            g.db.api_settings.update({}, {"$set": {product: to_save.__dict__}})
            if to_save.active:
                g.db.api_settings.update({}, {"$addToSet": {"active_products": product}})
            else:
                g.db.api_settings.update({}, {"$pull": {"active_products": product}})

            flash("Product was successfully updated", "success")
            return redirect("/%s/manage" % product)
        else:
            if request.method == "POST":
                flash("Form was not saved successfully", "error")

            return render_template("manage/manage_product.html", title=title, form=form, product=product_data)
开发者ID:andrefauth,项目名称:pitchfork,代码行数:31,代码来源:views.py


示例4: set_data_for

 def set_data_for(self, value=None):
     products = [(Product.get(id=rpt.product_id).name) for rpt in
                 Report.select(fn.Distinct(Report.product))]
     if value:
         products = [(prod.name) for prod in Product.select().where(Product.name.contains(value))
                     .where(Product.name << products).order_by(Product.name.desc())]
     self.data = [(prd, "") for prd in products]
开发者ID:Ciwara,项目名称:GCiss,代码行数:7,代码来源:invoice.py


示例5: post

 def post(self, subdomain):
     namespace_manager.set_namespace(subdomain)
     visible = False
     if self.request.get('visible') == 'yes':
         visible = True
     name = self.request.get('name')
     categories = self.request.get('category').split(',')
     logging.info(categories)
     cat_refs = []
     for category in categories:
         logging.info(category)
         if Category.get_by_key_name(category):
             cat_refs.append(Category.get_by_key_name(category).key())
     logging.info(cat_refs)
     entity = Product(key_name=name,
                       name=name,
                       shop_id=Shop.get_by_key_name(subdomain),
                       stock=int(self.request.get('qty')),
                       description=self.request.get('description'),
                       price=float(self.request.get('price')),
                       tags=self.request.get('tags').split(','),
                       video=self.request.get('video'),
                       visible=visible,
                       categories=cat_refs
                           )
     entity.put()
     self.redirect(webapp2.uri_for('addproducts'))
开发者ID:itaogit,项目名称:shopapp,代码行数:27,代码来源:admin.py


示例6: create

def create(request):
    if request.method != "POST":
        raise Http404("Invalid HTTP method!")
    go_back = False
    if len(request.POST["name"]) < 1:
        messages.add_message(request, messages.INFO, "Product Name cannot be blank!")
        go_back = True
    elif len(request.POST["name"]) < 8:
        messages.add_message(request, messages.INFO, "Product Name must be at least 8 characters!")
        go_back = True
    if len(request.POST["price"]) < 1:
        messages.add_message(request, messages.INFO, "Price cannot be blank!")
        go_back = True
    elif float(request.POST["price"]) < 0:
        messages.add_message(request, messages.INFO, "Price cannot be less than $0!")
        go_back = True
    if len(request.POST["description"]) < 1:
        messages.add_message(request, messages.INFO, "Description cannot be blank!")
        go_back = True
    elif len(request.POST["description"]) > 50:
        messages.add_message(request, messages.INFO, "Description cannot be more than 50 characters!")
        go_back = True
    if go_back:
        return redirect("/products")
    else:
        prod = Product(
            name=request.POST["name"],
            manufacturer=request.POST["manufacturer"],
            price=float(request.POST["price"]),
            description=request.POST["description"],
        )
        prod.save()
        return redirect("/products")
开发者ID:eragnew,项目名称:dojodojo,代码行数:33,代码来源:views.py


示例7: post

    def post(self, request):
        url = request.POST['url']
        try:
            response = urllib2.urlopen(url, timeout=300)
        except urllib2.HTTPError as e:
            if e.code == 404:
                raise Http404('Product not found')
            raise e
        except ValueError as e:
            return HttpResponseBadRequest('Invalid url')
        except urllib2.URLError as e:
            return HttpResponseBadRequest('Site is not available')

        html = response.read()
        response.close()
        soup = BeautifulSoup(html)
        image = soup.find('img', {'id': 'base_image'})
        image_src = image['src']
        image_name = image['src'].split('/')[-1]
        title = image['title']
        my_image_path = os.path.join('media', image_name)
        image_my_src = os.path.join(BASE_DIR, my_image_path)
        urllib.urlretrieve(image_src, image_my_src)
        price = soup.find('div', {'name': 'prices_active_element_original'}).find('span', {'itemprop': 'price'}).text

        product = Product(title=title, image='/{0}'.format(my_image_path), price=float(price))
        product.save()

        return HttpResponseRedirect('/list/')
开发者ID:madeinnikolaev,项目名称:mocking,代码行数:29,代码来源:views.py


示例8: product

def product(request):
    """ Get list of products ordered with the cheapest first.
    Create product if method `POST`
    """

    if request.method == 'GET':

        sql = 'SELECT * FROM products_product order by CAST(price AS DECIMAL(6,2))'

        arg = QueryDict(request.GET.urlencode()).dict()
        slc = int(arg.get('page', 1)) * 10

        inst_list = Product.objects.raw(sql)[slc - 10: slc]

        return json_response({'result': [to_dict(ins) for ins in inst_list]})

    # create product
    elif request.method == 'POST':
        data = json.loads(request.body)
        if not data.get('name'):
            return json_response(FIELD_REQUIRED)

        p = Product(**data)
        p.save()
        return json_response({'id': p.id}, status=201)

    return HttpResponse(status=405)
开发者ID:yacneyac,项目名称:sample,代码行数:27,代码来源:views.py


示例9: Addproduct

def Addproduct(request):
    form=ProductForm(request.POST or None)
    if form.is_valid():
        ModelName = form.cleaned_data['ModelName']
        description = form.cleaned_data['description']
        photo = form.cleaned_data['photo']
        manufacturer = form.cleaned_data['manufacturer']
        price_in_dollars = form.cleaned_data['price_in_dollars']
        Quantity = form.cleaned_data['Quantity']
        Serial_No =form.cleaned_data['Serial_No']
        product=Product()
        product.ModelName=ModelName
        product.description=description
        product.photo=photo
        product.manufacturer=manufacturer
        product.price_in_dollars=price_in_dollars
        product.Quantity=Quantity
        product.Serial_No=Serial_No  
        product.save()
        return HttpResponseRedirect(reverse('ecom:product'))
        
        
        #return HttpResponseRedirect(reverse('ecom:product'))
    else:
        return render(request,"ItemMaster.html",{"form":form})    
开发者ID:Alok-Blueocean,项目名称:django,代码行数:25,代码来源:views.py


示例10: click_item

 def click_item(self, row, column, *args):
     if column != 2:
         self.choix = Product.filter(name=self.data[row][1]).get()
         self.parent.table_info.refresh_(self.choix.id)
     if column == 2:
         # self.removeRow(row)
         self.choix = Product.filter(name=self.data[row][1]).get()
         self.parent.table_invoice.refresh_(self.choix)
开发者ID:fadiga,项目名称:mstock,代码行数:8,代码来源:invoice_view.py


示例11: save_products

def save_products(data):
    for key, value in data.iteritems():
        if type(key) is unicode:
            key = int(key)
        product = Product(
            product_id=key, mpn=value["mpn"], image=value["image"], link=value["link"], name=value["name"]
        )
        product.save()
开发者ID:guihaojin,项目名称:django-recommendation-system,代码行数:8,代码来源:upload_handler.py


示例12: setUp

 def setUp(self):
     self.products = []
     for i in range(1,10):
         product = Product(product_id=i, key_name="test_product_"+str(i),price=round(random.uniform(1,10),2),tax_percent=18.00)
         product.put()
         product.add_stock("test_product_"+str(i),10)
         self.products.append("test_product_"+str(i))
     self.cart = Cart()
     random.shuffle(self.products)
开发者ID:itaogit,项目名称:shopapp,代码行数:9,代码来源:tests-cart.py


示例13: create_product

def create_product(request):
  kwargs = {}
  for k in request.POST:
    if k != 'csrfmiddlewaretoken':
      kwargs[k] = request.POST[k]
  product =  Product(**kwargs)
  product.save()
  for k in request.FILES:
    filename = img_utils.thumb_image('main_image', str(product.pk), request.FILES[k], (300, 273))
    setattr(product, k, filename)
  product.save()
开发者ID:Magzhan123,项目名称:TabysKTS,代码行数:11,代码来源:views.py


示例14: test_reserved

 def test_reserved(self):
     qty = random.randint(1,10)
     print ' To reserve: ',qty,
     if Product.reserve(self.name,qty):
         p = Product.get_by_key_name(self.name)
         print ' AVAILABLE: ',p.available
         self.assertEqual(p.available, p.stock - qty, 'Not reserving correctly')
     else:
         p = Product.get_by_key_name(self.name)
         print ' Not enough stock', p.available
         self.assertGreater(qty, p.available, 'Not reserving correctly')
开发者ID:itaogit,项目名称:shopapp,代码行数:11,代码来源:tests-cart.py


示例15: create_product

 def create_product(self,request):
     u = self.current_user(request)
     e = json.load(open('%s/json/elements.json'%settings.STATIC_ROOT))
     c = request.REQUEST['category']
     category = e['locale_cat'].index(c)
     credit = request.REQUEST['credit']
     name = request.REQUEST['name']
     description = request.REQUEST['description']
     product = Product(category=category,credit=credit,visual='',
     name='$$%s'%name,description=description,user=u)
     product.save()
     return redirect('productimage')
开发者ID:fabricadeideias,项目名称:lab,代码行数:12,代码来源:store.py


示例16: SaleOfferTests

class SaleOfferTests(TestCase):
    def setUp(self):
        self.stuff = FoodStuff(name='some stuff 3')
        self.stuff.save()

        recipe = Recipe(name='some recipe 3')
        recipe.save()

        ingredient = RecipeIngredient(
            stuff  = self.stuff,
            recipe = recipe,
            count  = 1.5
        )
        ingredient.save()

        self.product = Product(
            name   = 'some product 3',
            recipe = recipe,
            markup = 1.5
        )
        self.product.save()

        provider = FoodProvider(name='some provider')
        provider.save()

        purchase = Purchase(
            provider   = provider,
            stuff      = self.stuff,
            cost       = 200,
            unit_count = 10,
            unit_size  = 1,
        )
        purchase.save()

        self.offer = SaleOffer(product=self.product)
        self.offer.save()

    def test_str(self):
        self.assertEqual('some product 3', str(self.offer))

    def test_save_change_actual(self):
        self.assertEqual(True, self.offer.is_actual)

        offer_2 = SaleOffer(product=self.product)
        offer_2.save()

        self.offer.refresh_from_db()
        self.assertEqual(False, self.offer.is_actual)

    def test_save(self):
        self.assertEqual(30, self.offer.cost)
        self.assertEqual(50, self.offer.price)
开发者ID:silverozzo,项目名称:tango4,代码行数:52,代码来源:tests.py


示例17: manage_settings

    def manage_settings(self, product):
        product_data = self.retrieve_product(product)
        if type(product_data) is str:
            title = "%s Manage Settings" % product.title()
            product_data = None
            form = forms.ManageProduct()
        else:
            title = "%s Manage Settings" % product_data.title
            form = forms.ManageProduct(obj=product_data)

        if request.method == 'POST' and form.validate_on_submit():
            to_save = Product(request.form.to_dict())
            if product_data and product_data.db_name:
                to_save.db_name = product_data.db_name
                to_save.groups = product_data.groups
            else:
                to_save.set_db_name()

            g.db.api_settings.update(
                {}, {
                    '$set': {
                        product: to_save.__dict__
                    }
                }
            )
            if to_save.active:
                g.db.api_settings.update(
                    {}, {
                        '$addToSet': {'active_products': product}
                    }
                )
            else:
                g.db.api_settings.update(
                    {}, {
                        '$pull': {'active_products': product}
                    }
                )

            flash('Product was successfully updated', 'success')
            return redirect('/%s/manage' % product)
        else:
            if request.method == 'POST':
                flash('Form was not saved successfully', 'error')

            return render_template(
                'manage/manage_product.html',
                title=title,
                form=form,
                product=product_data,
            )
开发者ID:futuernorn,项目名称:pitchfork,代码行数:50,代码来源:views.py


示例18: upload_xml

def upload_xml(xml):

    doc = parseString(xml)
    products = doc.getElementsByTagName("product")

    for prod in products:
        mongoProduct = Product()

        for node in prod.childNodes:
            if (node.nodeType == node.ELEMENT_NODE
                    and node.firstChild != None
                    and node.firstChild.nodeType == node.TEXT_NODE):
                nodeVal = parse_value(node.firstChild.nodeValue)
                mongoProduct.attr[node.nodeName] = nodeVal
        mongoProduct.save()
开发者ID:maxlang,项目名称:shoppersherpa,代码行数:15,代码来源:uploadbestbuyxml2.py


示例19: check_onsale_product

    def check_onsale_product(self, id, url):
        prd = Product.objects(key=id).first()
        if prd is None:
            print '\n\nshopbop {0}, {1}\n\n'.format(id, url)
            return

        ret = self.fetch_page(url)
        if isinstance(ret, int):
            print("\n\nshopbop download product page error: {0}".format(url))
            return

        tree = lxml.html.fromstring(ret)

        listprice = price = None
        for price_node in tree.cssselect('div#productPrices div.priceBlock'):
            if price_node.cssselect('span.salePrice'):
                price = price_node.cssselect('span.salePrice')[0].text_content().replace(',', '').replace('$', '').strip()
            elif price_node.cssselect('span.originalRetailPrice'):
                listprice = price_node.cssselect('span.originalRetailPrice')[0].text_content().replace(',', '').replace('$', '').strip()

        soldout = True if tree.cssselect('img#soldOutImage') else False

        if listprice and prd.listprice != listprice:
            prd.listprice = listprice
            prd.update_history.update({ 'listprice': datetime.utcnow() })
        if prd.price != price:
            prd.price = price
            prd.update_history.update({ 'price': datetime.utcnow() })
        if prd.soldout != soldout:
            prd.soldout = soldout
            prd.update_history.update({ 'soldout': datetime.utcnow() })
        prd.save()
开发者ID:mobishift2011,项目名称:amzn,代码行数:32,代码来源:simpleserver.py


示例20: set_data_for

    def set_data_for(self, prod_find):

        products = Product.select().order_by(Product.name.asc())
        if prod_find:
            products = products.where(Product.name.contains(prod_find))

        self.data = [("", prod.name, "") for prod in products]
开发者ID:fadiga,项目名称:mstock,代码行数:7,代码来源:stock_input.py



注:本文中的models.Product类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Profile类代码示例发布时间:2022-05-27
下一篇:
Python models.Post类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap