def save(self): title = self.cleaned_data['title'] iarticle = self.cleaned_data['iarticle'] article = self.cleaned_data['article'] name = self.cleaned_data['name'] description = self.cleaned_data['description'] comment = self.cleaned_data['comment'] url = self.cleaned_data['url'] code = self.cleaned_data['code'] cat = self.cleaned_data['category'] vend = self.cleaned_data['vendor'] distr = self.cleaned_data['distr'] number = Product.set_number(self) #print(number) prod = Product(type=1, number=number, iarticle=iarticle, article=article, title=title, name=name, alias='', description=description, comment=comment, url=url, img='', category=cat, vendor=vend) prod.save() if code: dc = Code(type=0, code=code, distr=distr, product_id=prod.id) dc.save() return "Товар " + title + " добавлен!"
def process_request(request, p: m.Product): if request.user.is_superuser: p.status = 2 p.save() return HttpResponseRedirect('/manager/') else: return HttpResponseRedirect('/index/')
def new_product(request): noForwardedsInfo(request) context = {} if request.method == 'GET': form = ProductForm() context['form'] = form return render(request, 'dashboard_admin/new_product.html', context) else: form = ProductForm(request.POST, request.FILES) if form.is_valid(): value = Utils.convertStringForNumber(request.POST.get('value')) product = Product() product.name = form.cleaned_data['name'] product.description = form.cleaned_data['description'] product.image = form.cleaned_data['image'] product.value = value product.brand = form.cleaned_data['brand'] product.category = form.cleaned_data['category'] product.save() messages.success(request, "Novo Produto salvo com sucesso!") else: messages.warning(request, "Por favor, preencha os campos corretamente!") context['form'] = form return HttpResponseRedirect( reverse('dashboard_admin:show_all_products'))
def setUp(self): """Setup.""" self.client = Client() self.user = User(username='******', email='*****@*****.**') self.user.set_password('COOKIE') self.user.is_active = True self.user.save() self.account = Account.objects.get(user=self.user) self.account.has_address_delete = True self.account.save() self.addresses = [] self.products = [] self.services = [] for i in range(2): address = ShippingInfo(name='test_name{}'.format(i), address1='1234 Test Ave S', zip_code='11111', city='testville', state='testington', resident=self.account) address.save() product = Product(image=test_image, name=('test' + str(i)), price=50.00) product.save() service = Service(image=test_image, name=('test' + str(i))) service.save() self.addresses.append(address) self.products.append(product) self.services.append(service) self.account.main_address = ShippingInfo.objects.last().id self.account.save()
def get_context_data(self, **kwargs): return { 'seo': views.get_seo(), 'banner_products': Product.get_banner(), 'other_products': Product.get_other(), 'other_stock': Category.get_other(), }
def handle(self, *fixture_labels, **options): if len(fixture_labels) > 0: path = fixture_labels[0] if not os.path.exists(path): print "Path does not exist:", path return fields = fields_for_model(Product) print "fields:", fields.keys() reader = csv.reader(open(path), delimiter=";") self.header = reader.next() print "header", self.header columns = list(set(fields.keys()) & set(self.header)) print "columns:", columns for row in reader: id = self.get_value("id", row) data = dict([(c, getattr(self, "resolve_" + c, self.get_value)(c, row)) for c in columns]) prod = None try: prod = Product.objects.get(id=id) except Product.DoesNotExist: data["id"] = id pl = Placeholder(slot="product_description") pl.save() data["description"] = pl prod = Product(**data) else: Product.objects.filter(id=id).update(**data) prod = Product.objects.get(id=id) if prod: prod.save() self.post_create(prod, row)
def process_request(request, deactivatedProduct: cmod.Product): context = {} # deactivatedProduct = cmod.Product.objects.get(id=productID) deactivatedProduct.Status = 'I' deactivatedProduct.save() return redirect('/manager/')
def get(self, request): featured_products = Product.featured_products() recent_products = Product.recent_products( self.get_max_recent_arrivals()) return super(IndexView, self).get(request, featured_products=featured_products, recent_products=recent_products)
def process_request(request, Product: cmod.Product = None): Product.status = 'I' Product.save() return HttpResponseRedirect('/manager/index/') context = {} return request.dmp.render('index.html', context)
def process_request(request, productid: cmod.Product): if not request.user.has_perm('auth.manager_view'): return HttpResponseRedirect('/homepage/index') productid.status = 'I' productid.save() return HttpResponseRedirect('/manager/ProductList')
def __init__(self, **kwargs): super(StatisticModule, self).__init__(**kwargs) self.template = 'admin/statistic_block.html' self.css_classes.append('big-block') self.column = 3 self.collapsible = False self.total_1 = "NONE1" self.total_2 = "NONE2" self.total_3 = "NONE2-NONE1" self.total_4 = Product.get_sales_count() self.total_5 = Product.get_in_stoke_count() request = kwargs.get('context').get('request')
def process_request(request, product:cmod.Product): #p = cmod.Product.objects.get(id=request.urlparams[0]) product.status = 'I' product.save() return HttpResponseRedirect('/manager/product') context = { } return request.dmp.render('delete.html', context)
def process_request(request, product: amod.Product): #set the product status to Inactive product.status = 'I' #save the status change product.save() #get all active products products = amod.Product.objects.filter(status='A') #render the product list template return request.dmp.render('product.html', { 'products': products, })
def process_request(request, product: cmod.Product): # try: # product = cmod.Product.objects.get(id=request.urlparams[0]) # except cmod.Product.DoesNotExist: # return HttpResponseRedirect('/') product.status = 'I' product.save() productList = cmod.Product.objects.filter(status='A') context = {'productList': productList} return request.dmp.render('products.html', context)
def get(self, request, page_num): form = AdvancedSearchForm(request.GET) query = '?' + request.GET.urlencode() products = None keyword = request.GET.get('keyword', None) page_title = 'Search: ' + keyword breadcrumbs = ({ 'name': 'Search: ' + keyword, 'url': reverse('catalog_search') + query }, ) if form.is_valid(): data = form.cleaned_data products = paginate(Product.search_advance_products( data['keyword'], data['category'], data['manufacturer'], data['price_from'], data['price_to'], self.categories), self.get_page_size(), page_num, 'catalog_search', qs=query) return super(SearchProductsView, self).get(request, form=form, keyword=keyword, products=products, page_title=page_title, breadcrumbs=breadcrumbs)
def process_request(request, product:cmod.Product=None): prodict = {} prodict['pid'] = product.id prodict['max'] = product.get_quantity() if product.__class__.__name__ == 'BulkProduct': prodict['bulk'] = True else: prodict['bulk'] = False products = cmod.Product.objects.all() if product in request.last_five: request.last_five.remove(product) request.last_five.insert(0, product) if len(request.last_five) > 6: del request.last_five[-1] form = AddToCart(request, initial=prodict) form.submit_text = form.buy_now_text if form.is_valid(): if request.user.is_authenticated: form.commit() cart = request.user.get_shopping_cart() cart.recalculate() return HttpResponseRedirect('/catalog/cart/') else: return HttpResponseRedirect('/account/signup/') context = { 'product': product, 'form': form, } return request.dmp.render('detail.html', context)
def search(request): company = request.user.account.company results = OrderTransferItem.objects.filter(Q(order__order__supplier=company) | Q(order__order__customer=company)) contact_id = request.GET.get('contact_id', None) if contact_id: results = results.filter(Q(order__order__customer__id=contact_id) | Q(order__order__supplier__id=contact_id)) customer_id = request.GET.get('customer_id', None) if customer_id: results = results.filter(order__order__customer__id=customer_id) supplier_id = request.GET.get('supplier_id', None) if supplier_id: results = results.filter(order__order__supplier__id=supplier_id) product_id = request.GET.get('product_id', None) if product_id: results = results.filter(order__info_id=product_id, order__info_type=Product.content_type()) date = request.GET.get('date', None) if date: date = datetime.strptime(date, settings.DATE_FORMAT) sort = request.GET.get('sort', 'dsc') if sort == 'dsc': if date: results = results.filter(transfer__date__lte=date) results = results.order_by('-transfer__date') else: if date: results = results.filter(transfer__date__gte=date) results = results.order_by('transfer__date') return results
def process_request(request, product: pmod.Product): plist = product.image_urls() if request.method == 'POST': form = PurchaseForm(request.POST) form.user = request.user form.product = product form.sale = request.user.get_shopping_cart() if form.is_valid(): form.commit(product) PurchaseForm(request, form.user) return HttpResponseRedirect( f'/catalog/cart/{request.user.get_shopping_cart().id}') else: form = PurchaseForm() context = { 'form': form, 'product': product, 'plist': plist, } return request.dmp.render('product.html', context)
def handle_noargs(self, **options): admin = User.objects.get(username='******') primary = admin.account.company # list of zero stock products no_stock_ids = set( Product.objects.exclude(stocks__quantity__gt=0).values_list( 'id', flat=True)) # list of products with sales sale_ids = set( OrderItem.objects.filter( info_type=Product.content_type).values_list('info_id', flat=True)) excluded_ids = no_stock_ids.difference(sale_ids) print excluded_ids raw_input("Press to continue...") items = ItemAccount.objects.filter( cost=0, owner=primary, item_type=Product.content_type()).exclude(item_id__in=excluded_ids) fname = "{} {}".format('for_costing', '.csv') with open(fname, 'wb') as f: writer = csv.writer(f) writer.writerow(['ID', 'Name', 'Summary', 'Cost']) for i in items: print '{} {} {} {}'.format(i.id, i.item.name(), i.item.summary, i.cost) writer.writerow([i.id, i.item.name(), i.item.summary, i.cost])
def setUp(self): p = Product() p.name = 'lays' p.slug = 'lays' p.price = 10.00 p.quantity= 1 p.save();
def bookkeep_adjustments(self): physicals = Physical.objects.filter( date__lte=self.end_date, date__gte=self.start_date, stock__location__owner=self.primary) adjustments = AdjustmentItem.objects.filter( adjustment__date__lte=self.end_date, adjustment__date__gte=self.start_date, adjustment__location__owner=self.primary, adjustment__labels__name=Adjustment.VALID) delta_map = {} count = len(physicals) for i, p in enumerate(physicals): sys.stdout.write("Calculating physicals... {} of {}\r".format( i + 1, count)) sys.stdout.flush() delta_map[p.stock.product.id] = delta_map.get( p.stock.product.id, 0) + p.delta count = len(adjustments) for i, a in enumerate(adjustments): sys.stdout.write("Calculating adjustments... {} of {}\r".format( i + 1, count)) sys.stdout.flush() delta_map[a.product.id] = delta_map.get(a.product.id, 0) + a.delta total = 0 accounts = ItemAccount.objects.filter(item_type=Product.content_type(), owner=self.primary) count = len(accounts) for i, account in enumerate(accounts): sys.stdout.write("Writing out adjustments... {} of {}\r".format( i + 1, count)) sys.stdout.flush() key = account.item_id adjustment = delta_map.get(key, 0) * self.context.estimate( account.item) total += adjustment account.data(ItemAccount.YEAR_ADJUSTMENTS, self.cutoff, adjustment) self.primary.account.data(CompanyAccount.YEAR_ADJUSTMENTS, self.cutoff, total) # Calculate bad debts writeoffs = Bill.objects.filter(supplier=self.primary, labels__date__gte=self.start_date, labels__date__lte=self.end_date, labels__name=Bill.BAD) bad_debts = 0 for w in writeoffs: bad_debts += w.outstanding() self.primary.account.data(CompanyAccount.YEAR_BAD_DEBTS, self.cutoff, bad_debts) print "\nDone."
def setUp(self): self.noprod = Product() self.lg3 = Product() self.loafer = Product() self.noprod.activ = False self.noprod.quantity = 10 self.noprod.pk = 19 self.noprod.name = 'No product' # LG3 Product self.lg3.pk = 3 self.lg3.quantity = 1 self.lg3.name = 'LG 3' # Loafer Product self.loafer.pk = 1 self.loafer.quantity = 6 self.loafer.name = 'Loafer'
def process_request(request, product: cmod.Product = None): print(product, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") if product is None: return HttpResponseRedirect('/catalog/index') picList = product.image_urls().order_by('id') for p in picList: print(p.filename) type = product.TITLE quant = product.get_quantity() name = cmod.Category.objects.get(id=product.category_id).name user = request.user if product in request.last_five: request.last_five.remove(product) request.last_five.insert(0, product) if len(request.last_five) > 6: request.last_five.pop() form = BuyForm(request, prod=product) if form.is_valid(): if request.user.is_authenticated != True: return HttpResponseRedirect('/account/login') form.commit(product) return HttpResponseRedirect('/catalog/cart') form.submit_text = 'Add to Cart' context = { # sent to index.html: 'form': form, 'quant': quant, 'type': type, 'product': product, 'name': name if name is not None else "All Products", 'catID': product.category, 'pictures': picList, # sent to index.html and index.js: } return request.dmp.render('details.html', context)
def handle(self, *args, **options): admin = User.objects.get(username__exact='admin') # hack primary = admin.account.company cutoff = primary.account.current_cutoff_date() terms = ' '.join(args) product_ids = SearchQuerySet().auto_query(terms).models( Product).values_list('pk', flat=True) items = ItemAccount.objects.filter(item_id__in=product_ids, item_type=Product.content_type(), owner=primary) today = datetime.today() last_year = today - timedelta(days=365) transfers = OrderTransferItem.objects.filter( order__info_id__in=product_ids, order__info_type=Product.content_type(), transfer__date__lte=today, transfer__date__gte=last_year) sales = {} for t in transfers: if not t.transfer.labeled(OrderTransfer.CANCELED): sales[t.order.info_id] = sales.get(t.order.info_id, 0) + t.net_quantity fname = "{}{}".format(terms, '.csv') with open(fname, 'wb') as f: writer = csv.writer(f) writer.writerow([ 'Brand', 'Model', 'Summary', 'On Hand', '1 Year Sales', 'Average Monthly Rate' ]) for i in items: #data = i.data(ItemAccount.YEAR_SALES_QUANTITY, cutoff) item_sales = sales.get(i.item.id, 0) print '{} {} {} {} {}'.format(i.item.brand, i.item.model, i.item.summary, i.stock, item_sales, item_sales / 12) writer.writerow([ i.item.brand, i.item.model, i.item.summary, i.stock, item_sales, item_sales / 12 ])
def get(self, request, product_id, slug): try: product = Product.get_detail(int(product_id)) except Product.DoesNotExist: raise Http404() return super(ProductDetailView, self).get( request, product=product, breadcrumbs=product.get_breadcrumbs(self.categories), page_title=product.name)
def submit_data(self): data_dict = self.get_data_dict() product = Product( title=data_dict['title'][0], track_stock=True if data_dict['track_stock'][0] == 2 else False, upc=data_dict['UPC_1'][0], upc_2=data_dict['UPC_2'][0], purchase_price=float(data_dict['purchase_price_ET'][0]), selling_price=float(data_dict['selling_price_ET'][0]), tax_rate=float(data_dict['tax_rate'][0]), category=ProductCategory.objects.get(pk=data_dict['category'][0]), dci=data_dict['dci'][0], lab=data_dict['manufacturer'][0], th_class=data_dict['th'][0], refundable=True if data_dict['refundable'][0] == 2 else False, prescription=True if data_dict['prescription'][0] == 2 else False, pharma_form=data_dict['pharma_form'][0], tableau=data_dict['tableau'][0]) product.save() self.close()
def remove_wish_list(request): slug = request.POST.get('slug') product = Product() user_profile = profile.get_profile(request) try: product = user_profile.wish_list.get(slug=slug) user_profile.wish_list.remove(product) response = json.dumps({'success': 'True'}) except product.DoesNotExist: response = json.dumps({'success': 'False'}) return HttpResponse(response, content_type='application/javascript; charset=utf-8')
def order(request): items = [] terms = request.GET.get('terms', None) months = decimal.Decimal(request.GET.get('months', 6)) if terms: terms = terms.strip() results = SearchQuerySet().auto_query(terms) results = results.models(Product) product_ids = results.values_list('pk', flat=True) primary = request.user.account.company accounts = ItemAccount.objects.filter(owner=primary, item_id__in=product_ids, item_type=Product.content_type()) today = datetime.today() last_year = today - timedelta(days=365) transfers = OrderTransferItem.objects.filter( order__order__supplier=primary, order__info_id__in=product_ids, order__info_type=Product.content_type(), transfer__date__lte=today, transfer__date__gte=last_year, transfer__labels__name=OrderTransfer.VALID) sales = {} for t in transfers: sales[t.order.info_id] = sales.get(t.order.info_id, 0) + t.net_quantity for a in accounts: a.sales = sales.get(a.item_id, 0) a.rate = a.sales / 12 a.quantity = a.rate * months - a.stock if a.quantity < 0: a.quantity = 0 items.append(a) return render_to_response('task/purchasing/order.html', dict(items=items, terms=terms, months=months), context_instance=RequestContext(request))
def save(self, commit=False): try: product = Product.objects.get( name=self.cleaned_data.get('name').title(), color=self.cleaned_data.get('color')) return product except Product.DoesNotExist: product = Product() product.name = self.cleaned_data.get('name').title() product.color = self.cleaned_data.get('color') product.quantity_stocked = self.cleaned_data.get('quantity_stocked') product.personalization_limit = self.cleaned_data.get( 'personalization_limit') product.price = self.cleaned_data.get('price') features = self.cleaned_data.get('features') product.save() for feature in features.splitlines(): Feature(product_id=product, feature_desc=feature.strip()).save() return product
def handle(self, *fixture_labels, **options): if len(fixture_labels) > 0: path = fixture_labels[0] if not os.path.exists(path): print 'Path does not exist:', path return fields = fields_for_model(Product) print 'fields:', fields.keys() reader = csv.reader(open(path), delimiter=";") self.header = reader.next() print 'header', self.header columns = list(set(fields.keys()) & set(self.header)) print 'columns:', columns for row in reader: id = self.get_value('id', row) data = dict([(c, getattr(self, 'resolve_' + c, self.get_value)(c, row)) for c in columns]) prod = None try: prod = Product.objects.get(id=id) except Product.DoesNotExist: data['id'] = id pl = Placeholder(slot='product_description') pl.save() data['description'] = pl prod = Product(**data) else: Product.objects.filter(id=id).update(**data) prod = Product.objects.get(id=id) if prod: prod.save() self.post_create(prod, row)
def preload(self): purchases = OrderTransferItem.objects.filter(transfer__labels__name=OrderTransfer.VALID, transfer__date__lte=self.end_date, transfer__date__gte=self.start_date, transfer__order__customer__id=self.primary_id).order_by('transfer__date') quantities = {} values = {} for item in purchases: key = (item.order.info_id, item.order.info_type.id) if item.net_quantity > 0: quantities[key] = quantities.get(key, 0) + item.net_quantity values[key] = values.get(key, 0) + (item.order.price * item.net_quantity) for key in quantities.keys(): self.cache[key] = values[key] / quantities[key] orders = OrderItem.objects.filter(order__labels__name=Order.CLOSED, order__customer__id=self.primary_id, info_type=Product.content_type(), order__date__lte=self.end_date).order_by('order__date') for o in orders: self.last_known_cache[o.info.id] = o.price self.default_cache = dict(ItemAccount.objects.filter(item_type=Product.content_type(), owner__id=self.primary_id).values_list('item_id', 'cost'))
def urgent(request): primary = request.user.account.company # get all sale and purchase items with non-zero balance order_items = OrderItem.objects.pending().filter( info_type=Product.content_type()) products = {} for i in order_items: pid = i.info.id if pid not in products: products[pid] = i.info products[pid].stock = 0 products[pid].incoming = 0 products[pid].outgoing = 0 products[pid].required = 0 if i.order.supplier == primary: products[pid].outgoing = products[pid].outgoing + i.balance elif i.order.customer == primary: products[pid].incoming = products[pid].incoming + i.balance accounts = ItemAccount.objects.filter(owner=primary, item_type=Product.content_type(), item_id__in=products.keys()) for account in accounts: products[account.item_id].stock = account.stock # stocks = Stock.objects.filter(product__id__in=products.keys()) # for s in stocks: # pid = s.product.id # products[pid].stock = products[pid].stock + s.quantity urgent = [] for pid, p in products.items(): p.required = p.outgoing - p.stock - p.incoming if p.required > 0: urgent.append(p) return paginate(request, urgent, 'task/purchasing/urgent_results.html')
def process_request(request, product:cmod.Product): if product is None: return redirect('/catalog/index') #remove the current object from the last_five list, if it exists #this prevents it from showing up as the current object as well as in the last_five list if product in request.last_five: request.last_five.remove(product) #add the current object to the front of the last_five list request.last_five.insert(0, cmod.Product.objects.get(id = product.id)) return request.dmp.render('detail.html', { 'product': product, 'product_images': product.image_urls(), })
def task_product(self, grab, task): print 'Product title: %s' % grab.doc.select(self.xpath['product_title']).text().strip() products = Product.objects.filter(urls__contains=task.url) if not products: product = Product(name=grab.doc.select(self.xpath['product_title']).text().strip(), category=task.category) product.urls = task.url else: product = products[0] product.descr = grab.doc.select(self.xpath['product_descr']).node().text price_rub = grab.doc.select(self.xpath['product_price']) price_kop = price_rub.select(".//span").node().text price_rub = price_rub.node().text try: product.price = float("%s.%s" % (price_rub, price_kop)) except: pass if not product.name == grab.doc.select(self.xpath['product_title']).text().strip(): product.name = grab.doc.select(self.xpath['product_title']).text().strip() product.save()
def handle(self, *args, **options): start_time = time.time() # going to disconnect categories counter update hook from Product Signal.disconnect(pre_save, sender=Product, receiver=counters_hook) # going to disconnect product medial hook Signal.disconnect(post_delete, sender=ProductMedia, receiver=product_image_delete) if options['delete']: Category.objects.all().delete(); Product.objects.all().delete(); for file in args: if file[0:4] == 'http': try: request = urllib2.Request(file, headers={"Accept": "application/xml"}) file = urllib2.urlopen(request) tree = ET.parse(file) except ET.ParseError: raise CommandError('YML "%s" is not valid' % file) else: tree = ET.parse(file) root = tree.getroot() trans_dct = {} # copy categories into databases for child in root.find('shop').find('categories'): category = Category(name=child.text); category.save() trans_dct[child.get('id')] = category.id; # setting child-parent relations for child in root.find('shop').find('categories'): # only for child elements if child.get('parentId') is not None: # search for child a category try: category = Category.objects.get(pk=trans_dct[child.get('id')]) except Category.DoesNotExist: raise CommandError('Category ID "%s" was not found' % child.get('id')) pass # adding relation to parent category try: category.parent = Category.objects.get(pk=trans_dct[child.get('parentId')]) category.save() except Category.DoesNotExist: raise CommandError('Category ID "%s" was not found' % child.get('id')) pass self.stdout.write('Categories imported' + '\n') # import offers (products) product_counter = 0 for child in root.find('shop').find('offers'): if options['verbose']: u = u'import products) %s ' % child.find('name').text print u.encode('ascii', 'ignore') description = child.find('description').text; if description is None: description = "" product = Product( name=child.find('name').text, price=child.find('price').text, description=description, category=Category.objects.get(pk=trans_dct[child.find('categoryId').text]) ); product.save() product_counter += 1 if options['images']: # importing images from <picture>http://...</picture> if child.find('picture') is not None: try: image_data = urllib2.urlopen(child.find('picture').text, timeout=5) except urllib2.HTTPError: print 'Could not download image: ' + child.find('picture').text else: filename = urlparse.urlparse(image_data.geturl()).path.split('/')[-1] + '.jpg' product_media = ProductMedia(image=filename, is_main=True, product=product) product_media.image.save(filename, ContentFile(image_data.read()), save=False) product_media.save() self.stdout.write('Products imported - ' + str(product_counter) + '\n' + str(round(time.time() - start_time, 2)) + " seconds") # fix categories counters categories = Category.objects.all() for category in categories: category.count_products = Product.active.filter( category__in=category.get_descendants(include_self=True)).count() # deactivate empty categories if category.count_products == 0: category.is_active = False category.save()
def get_last_products(session): last_products_id = session.get('last_products', []) if not len(last_products_id): return [] return Product.get_last_products(last_products_id)
def create_master_product(self, data, sync, product=None, is_update=False): if not product: product = Product() product.title = data['cleaned_data']['title'] product.description = data['cleaned_data']['detailed_desc'] or data['cleaned_data']['description'] product.brand = data['cleaned_data']['brand'] product.category = data['cleaned_data']['category'] product.slug = slugify(product.title)[:150] product.model = data['cleaned_data']['model'] product.moderate = True product.currency = data['cleaned_data'].get('currency','inr') product.type = data['cleaned_data'].get('product_type','normal') product.product_type = self.get_mapped_sku_type(data['cleaned_data'].get('sku_type','')) if data['cleaned_data'].get('video',''): product.video_embed = data['cleaned_data']['video'] #If the category belongs to BLACKLIST_CATEGORIES, then set product.status = 'deactive' #else product.status = data['cleaned_data']['status'] category = data['cleaned_data']['category'] if str(category.ext_id) in getattr(settings, 'BLACKLIST_CATEGORIES', []): product.status = 'deactive' elif data['cleaned_data']['status'] in ['active','deactive','deleted']: product.status = data['cleaned_data']['status'] product.save(using='default') product.productimage_set.using('default').all().delete() if self.download_images: # download the image for url in data['cleaned_data']['image_url']: try: feedutils.attach_image_to_product(product,url) except Exception, e: log.exception( 'Error adding image to product %s from %s: %s' % ( product.id, data['cleaned_data']['image_url'], repr(e)))
def process_request(request): #process the form form = CreateProductForm() if request.method == 'POST': # just submitted the form form = CreateProductForm(request.POST) if form.is_valid(): pr = Product() pr.name = form.cleaned_data.get('name') pr.description = form.cleaned_data.get('description') pr.image = form.cleaned_data.get('image') pr.price = form.cleaned_data.get('price') pr.ptype = form.cleaned_data.get('ptype') pr.creator = form.cleaned_data.get('creator') pr.quantity = form.cleaned_data.get('quantity') pr.status = form.cleaned_data.get('status') pr.date_made = form.cleaned_data.get('date_made') pr.save() return HttpResponseRedirect('/manager/products/') template_vars = { 'form': form, } return dmp_render_to_response(request, 'productscreate.html', template_vars)
def get_or_create_rate_chart(self, listing_id): try: rate_chart_map = ListingRateChartMap.objects.get( listing_id = listing_id) if rate_chart_map.rate_chart: return rate_chart_map.rate_chart except ListingRateChartMap.DoesNotExist: pass results = listing_solr_search('id:%s' % listing_id) if results and results.results and len(results.results) > 0: listing = results.results[0] product = Product() product.title = listing.get('title','') product.description = listing.get('description','') product.currency = listing.get('currency','inr') product.brand = self.get_other_brand('Other') product.model = '' product.category = self.get_other_category('Other') product.type = 'normal' product.status = 'unavailable' product.save() rate_chart = SellerRateChart() rate_chart.listing_id = listing_id rate_chart.product = product rate_chart.seller = self.get_seller(listing.get('userId',0)) rate_chart.status = 'unavailable' rate_chart.sku = listing.get('sku', '') rate_chart.condition = 'new' rate_chart.is_prefered = True rate_chart.list_price = Decimal(str(listing.get('mrp',0))) rate_chart.offer_price = Decimal(str(listing.get('askingPrice',0))) if rate_chart.offer_price > rate_chart.list_price: rate_chart.list_price = rate_chart.offer_price rate_chart.warranty = listing.get('warranty','') rate_chart.gift_title = listing.get('gifts','') rate_chart.shipping_charges = Decimal(str(listing.get('shippingCharges','0.0'))) rate_chart.shipping_duration = listing.get('shippingDuration','7-10 working days') rate_chart.availability = self.get_available_every_where() rate_chart.stock_status = 'notavailable' rate_chart.status = 'deleted' rate_chart.save() listing_rate_chart_map = ListingRateChartMap(listing_id=listing_id, rate_chart=rate_chart) listing_rate_chart_map.save() return rate_chart return None
def get(self, request): last_products_id = request.session.get('last_products', []) if not len(last_products_id): return Response([]) products = Product.get_last_products(last_products_id) return Response(ProductSerializer(products, many=True).data)