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 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_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 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 add_model(request,model,template_name=""): # show_model(request,model,template_name) # print(); result = ""; if request.method == 'POST': print('add') if request.POST.get('mode')=='add_cart_item': cart.add_to_cart(request) cart_items_list = [] cart_items = cart.get_cart_items(request) # serializers.serialize("json", ) cart_item_count = cart.cart_distinct_item_count(request) # result = {'cart_items' : cart_items ,'cart_item_count' : cart_item_count} # print(cart_item_count) for c in cart_items: # print(c) item = {} item.setdefault('image',c.image()) item.setdefault('name',c.name()) item.setdefault('quantity',c.quantity) price = str(c.price()) item.setdefault('unit_price',price) total = str(c.total()) item.setdefault('total_price',total) item.setdefault('id',c.id) # print(item) cart_items_list.append(item) # print(cart_items_list) # cart_items = serializers.serialize("json", cart_items_list) # print(cart_items) result = {'cart_items' : cart_items_list ,'cart_item_count' : cart_item_count} # print(json.dumps(result)) print('++++++++++++++++++++++++++++++') return HttpResponse(json.dumps(result),content_type='application/javascript; charset=utf-8') else: if model == 'people': name = request.POST.get('name') islug = slug(name) category = Category() category.name = name category.description = request.POST.get('description') is_active = request.POST.get('is_active') if is_active=="on": category.is_active = True else: category.is_active = False category.slug = islug category.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") category.created_at = datetime.datetime.now().strftime("%m/%d/%Y") category.save() result = "saved" print('add people') elif model == 'subcategory': subcategory = SubCategory() subcategory.name = request.POST.get('name') subcategory.description = request.POST.get('description') subcategory.slug = slug(subcategory.name) is_active = request.POST.get('is_active') subcategory.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") subcategory.created_at = datetime.datetime.now().strftime("%m/%d/%Y") if is_active=="on": subcategory.is_active = True else: subcategory.is_active = False subcategory.save() selected_c = json.loads(request.POST.get('selected_categories')) for s_c in selected_c: c = get_object_or_404(Category, slug=s_c) subcategory.categories.add(c) subcategory.save() print('add subcategory') elif model == 'product': p = Product() postdata = request.POST.copy() p.name = postdata.get('name','a') product_name = postdata.get('name','a') p.brand = postdata.get('brand') p.sku = postdata.get('sku') p.price = postdata.get('price') p.old_price = postdata.get('old_price') p.quantity = postdata.get('quantity') p.description = postdata.get('description') # print(postdata.get('user')) user = get_object_or_404(MyUser, username=postdata.get('user')) p.user = user p.slug = slug(p.name) is_active = request.POST.get('is_active') if is_active=="on": p.is_active = True else: p.is_active = False p.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") p.created_at = datetime.datetime.now().strftime("%m/%d/%Y") if request.FILES: print('image_exist') p_main_file=request.FILES['img'] file_extention = os.path.splitext(str(request.FILES['img']))[1] # print(file_extention) # file_name = str(request.FILES['img']).split('.') # file_extention = file_name[len(file_name)-1] image_name = str(user)+'_'+p.name+file_extention p_thumbnail_file=request.FILES['img'] with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'wb+') as destination: if p_thumbnail_file.multiple_chunks(): for chunk in p_thumbnail_file.chunks(): destination.write(chunk) else: destination.write(p_thumbnail_file.read()) with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'rb+') as destination: image_file = destination.read() with open(MEDIA_ROOT+'images/products/main/'+image_name, 'wb+') as destination: destination.write(image_file) p.image=image_name else: print('image_empty') p.image='default' p.save() selected_subc = json.loads(request.POST.get('selected_subcategories')) for p_subc in selected_subc: subc = get_object_or_404(SubCategory, slug=p_subc) p.subcategories.add(subc) p.save() print('add product') elif model == 'myuser': user = MyUser() postdata = request.POST.copy() user.username = postdata.get('name') user.first_name = postdata.get('first_name') user.last_name = postdata.get('last_name') ##########change date format###########YYYY-MM-DD # date_of_birth = postdata.get('date_of_birth') # date_list = date_of_birth.split('/') # join_str = '-' # user.date_of_birth = join_str.join(date_list) user.date_of_birth = postdata.get('date_of_birth') ######################################## user.address = postdata.get('address','a') user.telephone = postdata.get('telephone') user.password = make_password(postdata.get('password')) user.is_active = True user.is_staff = True user.save() print('add myuser') elif model == 'order': order = Order() postdata = request.POST.copy() myuser = get_object_or_404(MyUser, username=postdata.get('user')) print(postdata) order.address = myuser.address order.phone = myuser.telephone order_status = get_object_or_404(OrderStatus, id=postdata.get('status')) print(order_status.name) order.status = order_status order.ip_address = postdata.get('ip_address') # user = get_object_or_404(MyUser, username=postdata.get('user')) order.user = myuser order.transaction_id = postdata.get('transaction_id') order.last_updated = datetime.datetime.now().strftime("%m/%d/%Y") order.save() print(order.id); cart_items = cart.get_cart_items(request) for c in cart_items: orderitem = OrderItem() orderitem.product = c.product orderitem.price = c.price() orderitem.quantity = c.quantity orderitem.order = order orderitem.save() print('add order') elif model == 'orderitem': orderitem = OrderItem() postdata = request.POST.copy() product = get_object_or_404(Product, slug=postdata.get('product')) orderitem.product = product orderitem.price = product.price orderitem.quantity = postdata.get('quantity') order = get_object_or_404(Order, id=postdata.get('order')) orderitem.order = order orderitem.save() print('add orderitem') # return show_model(request,model,'') url = urlresolvers.reverse('model',kwargs = {'model':model}) return HttpResponseRedirect(url) else: app_list = permission_app(request) # print('_________________addpermission_________________') if check_permission(request,'add',model): if model == 'people': print('category') elif model == 'subcategory': category = Category.objects.all() print('subcategory') elif model == 'product': user_list = MyUser.objects.all() subcategory = SubCategory.objects.all() print('product') print(subcategory) elif model == 'myuser': print('myuser') elif model == 'order': cart.clean(request) user_list = MyUser.objects.all() product = Product.objects.all() order_status = OrderStatus.objects.all() # print(request.GET) # print('-------------------------------') # cart.add_to_cart(request) # cart_items = serializers.serialize("json", cart.get_cart_items(request)) # cart_item_count = cart.cart_distinct_item_count(request) # result = {'cart_items' : cart_items ,'cart_item_count' : cart_item_count} # print(result) # print('++++++++++++++++++++++++++++++=') # return HttpResponse(json.dumps(result),content_type='application/javascript; charset=utf-8') print('order') elif model == 'orderitem': product = Product.objects.all() order_list = Order.objects.all() print('orderitem') # subcategories = SubCategory.objects.all() template_name = 'myadmin/add/'+model+'.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request)) else: template_name = 'myadmin/err.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def add_product(request, template_name=""): mode = 'user_products' currency_symbol = request.session.get('currency_symbol', '$') currency_rate = request.session.get('currency_rate', 1) products = Product.objects.filter(user=request.user) product_list = products for p_item in products: p_item.price /= Decimal(currency_rate) p_item.price = math.floor(p_item.price * 100) / 100 active_category = 'user_products' if request.method == 'POST': if (request.GET.get('post_mode') != 'currency'): p = Product() postdata = request.POST.copy() p.name = postdata.get('name', 'a') product_name = postdata.get('name', 'a') p.brand = postdata.get('brand') p.sku = postdata.get('sku') p.price = postdata.get('price') p.quantity = postdata.get('quantity') p.description = postdata.get('description') p.user = request.user ######################make slug string############### product_name = product_name.lower() p_n_list = product_name.split(' ') join_str = '-' product_name = join_str.join(p_n_list) slug = "" count = 0 p_n = '' while (count < len(product_name)): p_n = product_name[count] if p_n.isdigit() or p_n.isalpha() or p_n == '-': slug += p_n count += 1 p.slug = slug ##################################################### if request.FILES: p_main_file = request.FILES['img'] file_extention = os.path.splitext(str(request.FILES['img']))[1] # print(file_extention) # file_name = str(request.FILES['img']).split('.') # file_extention = file_name[len(file_name)-1] image_name = str(request.user) + '_' + p.name + file_extention p_thumbnail_file = request.FILES['img'] with open( MEDIA_ROOT + 'images/products/thumbnails/' + image_name, 'wb+') as destination: if p_thumbnail_file.multiple_chunks(): for chunk in p_thumbnail_file.chunks(): destination.write(chunk) else: destination.write(p_thumbnail_file.read()) with open( MEDIA_ROOT + 'images/products/thumbnails/' + image_name, 'rb+') as destination: image_file = destination.read() with open(MEDIA_ROOT + 'images/products/main/' + image_name, 'wb+') as destination: destination.write(image_file) p.image = image_name else: p.image = p.name p.save() print(p.subcategories) subc = get_object_or_404(SubCategory, slug='personal-products') p.subcategories.add(subc) p.save() url = urlresolvers.reverse('account_user_products') return HttpResponseRedirect(url) return render_to_response(template_name, locals(), context_instance=RequestContext(request))