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 setUp(self): p = Product() p.name = 'lays' p.slug = 'lays' p.price = 10.00 p.quantity= 1 p.save();
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 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 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 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))
def handle(self, *args, **options): print("Add products") file_name = os.path.join(settings.BASE_DIR, 'termos.xls') book = xlrd.open_workbook(file_name) sh = book.sheet_by_index(0) print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols)) print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=5))) _root, _ = Category.objects.get_or_create(name='_root', slug='root', parent=None) categories = set() products = [] artikuls = [] for rx in range(sh.nrows): if rx == 0: continue curr_cat = sh.cell_value(rowx=rx, colx=5) categories.add(curr_cat) product_name = sh.cell_value(rowx=rx, colx=1) product_artikul = sh.cell_value(rowx=rx, colx=0) img_url = sh.cell_value(rowx=rx, colx=15) price_opt = sh.cell_value(rowx=rx, colx=16) price = sh.cell_value(rowx=rx, colx=17) old_price = sh.cell_value(rowx=rx, colx=18) products.append({ 'name': product_name, 'artikul': product_artikul, 'img_url': img_url, 'price_opt': price_opt, 'price': price, 'old_price': old_price, 'category_name': curr_cat, 'category_slug': slugify(curr_cat), }) for category in categories: sl_curr_cat = slugify(category) ext_cat = Category.objects.filter(slug=sl_curr_cat).first() if not ext_cat: new_cat = Category() new_cat.name = category new_cat.slug = sl_curr_cat new_cat.parent = _root new_cat.save() for prod in products: # print(prod.get('name')) try: artikul = prod.get('artikul') ext_prod = Product.objects.filter(artikul=artikul).first() if not ext_prod: need_category = Category.objects.filter( slug=prod.get('category_slug')).first() # print(need_category) new_prod = Product() new_prod.name = prod.get('name') new_prod.slug = slugify(prod.get('name')) new_prod.artikul = artikul new_prod.category = need_category new_prod.save() print(new_prod.pk) else: ext_prod.price_opt = prod.get('price_opt') ext_prod.price = prod.get('price') ext_prod.old_price = prod.get('old_price') if not ext_prod.img: ext_prod.img = self.add_image(prod.get('img_url')) ext_prod.save() except Exception as e: print(str(e))
def process_request(request, p: m.Product=None): if request.user.is_superuser: if request.method == 'GET': if type(p) is m.BulkProduct: t = "1" elif type(p) is m.IndividualProduct: t = "2" elif type(p) is m.RentalProduct: t = "3" form = ProductForm(request, initial={ 'id': p.id, 'type': t, 'name': p.name, 'price': p.price, 'status': 'Active' if p.status == '1' else 'Inactive', 'description': p.description, 'category': p.category.name, 'imageFile': m.ProductImage.objects.all().first().filename, # unique fields 'unit': p.unit if type(p) is m.BulkProduct else None, 'order_trigger': p.order_trigger if type(p) is m.BulkProduct else None, 'order_quantity': p.order_quantity if type(p) is m.BulkProduct else None, 'rental_period': p.rental_period if type(p) is m.RentalProduct else None, 'retire_date': p.retire_date if type(p) is m.RentalProduct else None, }) elif request.method == 'POST': form = ProductForm(request) if form.is_valid(): p = m.Product.objects.get(id=int(request.dmp.urlparams[0])) # unbind images m.ProductImage.objects.filter(product_id=p.id).delete() p.name = form.cleaned_data.get('name') p.price = form.cleaned_data.get('price') p.status = form.cleaned_data.get('status') p.description = form.cleaned_data.get('description') p.category = form.cleaned_data.get('category') if form.cleaned_data.get('type') == '1': p.unit = form.cleaned_data.get('unit') p.order_trigger = form.cleaned_data.get('order_trigger') p.order_quantity = form.cleaned_data.get('order_quantity') if form.cleaned_data.get('type') == '2': pass if form.cleaned_data.get('type') == '3': p.rental_period = form.cleaned_data.get('rental_period') p.retire_date = form.cleaned_data.get('retire_date') p.save() myfiles = request.FILES.getlist('imageFile') fs = FileSystemStorage(location="catalog/media/products/") for myfile in myfiles: filename = fs.save(myfile.name, myfile) fs.url(filename) form.bind_images(myfile, p.id) return HttpResponseRedirect('/manager/') context = { 'form': form, 'id': p.id } return request.dmp.render('edit.html', context) else: return HttpResponseRedirect('/index/')