def approve(request, *args, **kwargs): if request.user.is_authenticated and request.user.is_superuser: id_inc = kwargs["id_inc"] qs = pending.objects.all() for obj in qs: # print(obj.id_inc) if int(obj.id_inc) == int(id_inc): # print("heyyyyy") new_obj = Product() new_obj.user_name = obj.user_name new_obj.category = obj.category new_obj.name = obj.name new_obj.desc = obj.desc new_obj.contact_email = obj.contact_email new_obj.contact_phone = obj.contact_phone new_obj.address = obj.address new_obj.image = obj.image new_obj.price = obj.price new_obj.save() obj.delete() return HttpResponseRedirect('../../pending') break return HttpResponseRedirect('../../pending') else: return HttpResponseRedirect('../../../')
def post(self, request): productForm = ProductForm(request.POST) if productForm.is_valid(): # form = productForm.save(commit=False) # form.shop = request.user.shop # form.product_code = product_code_format(request.user.shop.id) # form.save() product = Product() product.shop = request.user.shop product.product_code = product_code_format(request.user.shop.id) product.category = productForm.cleaned_data.get('category') product.brand = productForm.cleaned_data.get('brand') product.product_name = productForm.cleaned_data.get('product_name') product.subTitle = productForm.cleaned_data.get('subTitle') product.original_price = productForm.cleaned_data.get( 'original_price') product.price = productForm.cleaned_data.get('price') product.cost = productForm.cleaned_data.get('cost') product.publish_status = productForm.cleaned_data.get( 'publish_status') product.description = productForm.cleaned_data.get('description') product.is_freeShipping = productForm.cleaned_data.get( 'is_freeShipping') product.save() # modelform保存后获取model? for pimage in request.FILES.getlist('pimage'): image = ProductImage(product=product, image=pimage, type='image') image.save() for dimage in request.FILES.getlist('dimage'): image = ProductImage(product=product, image=dimage, type='detailImage') image.save() for property in product.category.propertys.all(): propertyValue = Propertyvalue() propertyValue.property = property propertyValue.product = product propertyValue.value = '' propertyValue.save() return render(request, 'salers/amz/propertysForm.html', {'product': product}) else: print(productForm.errors) return render(request, 'salers/amz/product-add.html', {"productForm": productForm})
def create(self, validated_data): products = validated_data.pop('products', None) agent = Agent.objects.create(**validated_data) agent.save() if products is not None: for product in products: prod = Product() prod.name = product.get('name') prod.category = product.get('category') prod.owner = product.get('owner') prod.save() agent.products.add(prod) agent.save() return agent
def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) product = Product() product.user = request.user product.price = float(serializer.data.get('price')) product.currency = serializer.data.get('currency') product.title = serializer.data.get('title') product.description = serializer.data.get('description') product.category = Category.objects.get(id=1) product.time = serializer.data.get('time') product.length = 0 product.width = 0 product.height = 0 product.weight = 0 product.request = 1 product.accept = 0 product.save() requested = Request() requested.seller = serializer.validated_data['seller'] requested.buyer = request.user requested.product = product requested.save() assets = serializer.data.get('assets') if assets: for url in assets: asset = Asset(product=product, url=url) asset.save() ItemRequest_Notification(requested.seller, request.user, product) ItemRequest_mail(requested.seller, request.user, product) return Response( { "result": True, "data": { "Msg": "Item Request created", "Request_id": requested.id, } }, status=status.HTTP_201_CREATED)
def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) product = Product() product.user = request.user product.category = serializer.validated_data['category'] product.price = float(serializer.data.get('price')) product.currency = serializer.data.get('currency') product.title = serializer.data.get('title') product.description = serializer.data.get('description') product.time = serializer.data.get('time') product.length = serializer.data.get('length') product.width = serializer.data.get('width') product.height = serializer.data.get('height') product.weight = serializer.data.get('weight') product.save() assets = serializer.data.get('assets') if assets: for url in assets: asset = Asset(product=product, url=url) asset.save() tags = serializer.data.get('tag') if tags: for t in tags: tag = HashTags(product=product, tag=t) tag.save() # ProductPost_Notification(user) return Response( { "result": True, "data": { "Msg": "product created", "product_id": product.id, } }, status=status.HTTP_201_CREATED)
def create(self, request): dic = request.data.dict() id_cat = dic.pop('category', None) cat = Category.objects.filter(pk=id_cat).first() print(cat) pro = Product() pro.category = cat pro.description = dic.pop('description', None) pro.display = dic.pop('display', None) pro.display_in_home = dic.pop('display_in_home', None) pro.name = dic.pop('name', None) pro.offer_discount = dic.pop('offer_discount', None) pro.order = dic.pop('order', None) pro.price = dic.pop('price', None) print(dic) colors = dic.getlist('color_stocks', None) print(colors) return Response('Hola :V')
def handle(self, *args, **options): """ Scrapes and stores product information """ # get beer page html and make soup object html = urllib2.urlopen(TOP_URL + "/beers/search") soup_beers = BeautifulSoup(html) # find all beers beers = soup_beers.find_all("a", "brand-link") for beer in beers: # get beer page and make soup object beer_url = beer["href"] beer_html = urllib2.urlopen(TOP_URL + beer_url) soup_beer = BeautifulSoup(beer_html) # get sizes beer_products = soup_beer.find_all("table", "brand-pricing") # get propertis and valus and merge them into dict labels = soup_beer.dl.find_all("dt") details = soup_beer.dl.find_all("dd") beer_details = dict(zip(labels, details)) # get name and image beer_name = soup_beer.find("div", "only-desktop").find( "h1", "page-title").get_text() beer_image = soup_beer.find("div", "brand-image").img["src"] # get country and type beer_attributes = soup_beer.find("p", "introduction").find_all("span") beer_attributes = beer_attributes[::-1] beer_country = beer_attributes[0].get_text() beer_type = beer_attributes[1].get_text() # loop through beer products for beer_product in beer_products: beer_containers = beer_product.find_all("tbody") # loop through container tables for beer_container in beer_containers: beer_sizes = beer_container.find_all("tr") # loop through container sizes for beer_size in beer_sizes: # get product information beer_ids = beer_size.a["href"].split('=')[1] beer_id = beer_ids.split('-')[0] print beer_id beer_product_id = beer_ids.split('-')[1] # Comment to disable monitoring beer_product_size = beer_size.find("td", "size").get_text() beer_product_price = beer_size.find( "td", "price").get_text() # check if product exists # NOTE: used this custom solution because django get_or_create # doesn't play nice with custom primary keys try: product_entry = Product.objects.get( product_id=int(beer_product_id.strip())) except: product_entry = Product() # set fields product_entry.name = beer_name.strip() product_entry.size = beer_product_size.strip() product_entry.beer_id = int(beer_id.strip()) product_entry.product_id = int(beer_product_id.strip()) product_entry.image_url = beer_image.strip() product_entry.country = beer_country.strip() product_entry.type = beer_type.strip() # set product attributes # NOTE: this code was created befor the beer store redesign # it still works but some items no longer exist so they were # temporarily omitted from the serializer for key, value in beer_details.iteritems(): attr = key.get_text()[:-1] val = value.get_text() if attr == 'Category': product_entry.category = val if attr == 'Alcohol Content (ABV)': product_entry.abv = float(val[:-1]) if attr == 'Style': product_entry.style = val if attr == 'Attributes': product_entry.attributes = val if attr == 'Brewer': product_entry.brewer = val # update pricing info try: product_entry.price = float( beer_product_price.strip()[1:]) product_entry.on_sale = False except: product_entry.price = float( beer_product_price.split('sale')[1].strip() [1:]) product_entry.on_sale = True product_entry.save()
name = _products[0]['name'] try: product = Product.objects.get(sku=sku) except: product = Product() product.sku = sku product.title = _products[0]['name'] product.price = float(_products[0]['price']) product.attributes = _products[0]['image_url'] category, _a = Category.objects.get_or_create(title=_products[0]['set']) product.category = category product.save() color = [] size = [] for _product in _products: try: size.append(_product['size']) except: pass try: color.append(_product['color']) except:
def handle(self, *args, **options): """ Scrapes and stores product information """ # get beer page html and make soup object html = urllib2.urlopen(TOP_URL + "/beers/search") soup_beers = BeautifulSoup(html) # find all beers beers = soup_beers.find_all("a", "brand-link") for beer in beers: # get beer page and make soup object beer_url = beer["href"] beer_html = urllib2.urlopen(TOP_URL + beer_url) soup_beer = BeautifulSoup(beer_html) # get sizes beer_products = soup_beer.find_all("table", "brand-pricing") # get propertis and valus and merge them into dict labels = soup_beer.dl.find_all("dt") details = soup_beer.dl.find_all("dd") beer_details = dict(zip(labels,details)) # get name and image beer_name = soup_beer.find("div", "only-desktop").find("h1", "page-title").get_text() beer_image = soup_beer.find("div","brand-image").img["src"] # get country and type beer_attributes = soup_beer.find("p","introduction").find_all("span") beer_attributes = beer_attributes[::-1] beer_country = beer_attributes[0].get_text() beer_type = beer_attributes[1].get_text() # loop through beer products for beer_product in beer_products: beer_containers = beer_product.find_all("tbody") # loop through container tables for beer_container in beer_containers: beer_sizes = beer_container.find_all("tr") # loop through container sizes for beer_size in beer_sizes: # get product information beer_ids = beer_size.a["href"].split('=')[1] beer_id = beer_ids.split('-')[0] print beer_id beer_product_id = beer_ids.split('-')[1] # Comment to disable monitoring beer_product_size = beer_size.find("td","size").get_text() beer_product_price = beer_size.find("td","price").get_text() # check if product exists # NOTE: used this custom solution because django get_or_create # doesn't play nice with custom primary keys try: product_entry = Product.objects.get(product_id=int(beer_product_id.strip())) except: product_entry = Product() # set fields product_entry.name = beer_name.strip() product_entry.size = beer_product_size.strip() product_entry.beer_id = int(beer_id.strip()) product_entry.product_id = int(beer_product_id.strip()) product_entry.image_url = beer_image.strip() product_entry.country = beer_country.strip() product_entry.type = beer_type.strip() # set product attributes # NOTE: this code was created befor the beer store redesign # it still works but some items no longer exist so they were # temporarily omitted from the serializer for key, value in beer_details.iteritems(): attr = key.get_text()[:-1] val = value.get_text() if attr == 'Category': product_entry.category = val if attr == 'Alcohol Content (ABV)': product_entry.abv = float(val[:-1]) if attr == 'Style': product_entry.style= val if attr == 'Attributes': product_entry.attributes= val if attr == 'Brewer': product_entry.brewer= val # update pricing info try: product_entry.price = float(beer_product_price.strip()[1:]) product_entry.on_sale = False except: product_entry.price = float(beer_product_price.split('sale')[1].strip()[1:]) product_entry.on_sale = True product_entry.save()
def get_product(q): while True: _url = "http://www.choies.com/api/item?sku=%s" oldproduct = q.get() print oldproduct url = _url % oldproduct.sku try: r = requests.get(url=url, timeout=2) except: q.task_done() return print url try: _products = r.json() except: oldproduct.status = False oldproduct.save() q.task_done() return try: sku = _products[0]['sku'] except: q.task_done() return name = _products[0]['name'] try: product = Product.objects.get(sku=sku) except: product = Product() product.sku = sku product.title = _products[0]['name'] product.price = float(_products[0]['price']) product.attributes = _products[0]['image_url'] category, _a = Category.objects.get_or_create(name=_products[0]['set']) product.category = category product.save() color = [] size = [] for _product in _products: try: size.append(_product['size']) except: pass try: color.append(_product['color']) except: pass if color: productattribute, _a = ProductAttribute.objects.get_or_create( name='color', product=product) productattribute.options = ','.join(color) productattribute.save() if size: productattribute, _a = ProductAttribute.objects.get_or_create( name='size', product=product) productattribute.options = ','.join(size) productattribute.save() oldproduct.status = False oldproduct.save() print _product q.task_done()
def do(self): # Получаем все компании по API res = requests.get('http://otp.spider.ru/test/companies/') companies = json.loads(res.text) # Создаем или обновляем компании... for company in companies: try: # Проверяем есть ли такая компания try: new_company = Company.objects.get(name=company["name"], is_imported=True) except Company.DoesNotExist: new_company = None # Если такая компания уже есть, то просто обновим ее if (new_company != None): new_company.name = company["name"] new_company.save() print("update company: {0}".format(new_company.name)) # Если нет, то создаем ее else: Company.objects.create(name=company["name"], is_imported=True) print("create company: {0}".format(new_company.name)) # Загружаем продукты связанные с компаниями и создаем Категории. res = requests.get( 'http://otp.spider.ru/test/companies/{0}/products/'.format( company['id'])) products = json.loads(res.text) # Обновляем категории для этих продуктов Product.objects.filter(is_imported=True).delete( ) #удаляет все импортированные ранее категории для правиности данных for product in products: try: # Проверяем есть ли такой продукт try: new_product = Product.objects.get( title=product["name"], description=product["description"], is_imported=True, company=new_company) except Product.DoesNotExist: new_product = None # Если такой продукт уже есть, то просто обновим его if (new_product != None): new_product.title = product["name"] new_product.description = product["description"] print("update product {0}".format( new_product.title)) # Если нет, то создаем его else: new_product = Product( title=product["name"], description=product["description"], is_imported=True, company=new_company, is_active=True) print("create product: {0}".format( new_product.title)) # Обновляем категорию для этого продукта try: category = product["category"] # Проверяем есть ли такая категория try: new_category = Category.objects.get( title=category["name"]) except Category.DoesNotExist: new_category = None # Если такая категория уже есть, то просто обновим ее if (new_category != None): new_category.name = category["name"] new_category.save() print("update category: {0}".format( new_category.title)) # Если нет, то создаем ее else: new_category = Category.objects.create( title=category["name"]) print("create category: {0}".format( new_category.title)) # Добавляем категорию к продукту и сохраняем. new_product.category = new_category new_product.save() except Exception as e: print(e) except Exception as e: print(e) except Exception as e: print(e)