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 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 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 handle(self, *args, **option): print('-' * 150) with open('atmosfera.csv', 'r', encoding='utf-8') as file: reader = csv.DictReader(file, delimiter=';') index = 0 for row in reader: if row['Название_позиции'] \ and row['Описание'] \ and row['Название_позиции'] != row['Описание']: print(' ' * 50, index) url = row['Ссылка_изображения'].split(',')[0] product = Product() product.title = row['Название_позиции'] product.slug = self.slugify(row['Название_позиции']) product.meta_keywords = row['Ключевые_слова'] product.description = row['Описание'] product.active = True product.save() product.category.add( Category.objects.get( title='Альтернативная энергетика').pk) if row.get('Атрибут_Гарантийный срок(мес.)'): feature_1 = Feature( title='Гарантия', value=row['Атрибут_Гарантийный срок(мес.)'], product=product, ) feature_1.save() if row.get('Атрибут_Вес(кг)'): feature_2 = Feature( title='Вес', value=row['Атрибут_Вес(кг)'], product=product, ) feature_2.save() if row.get('Страна_производитель'): feature_3 = Feature( title='Страна производитель', value=row['Страна_производитель'], product=product, ) feature_3.save() if url: ext = self.get_file_ext(url) filename = self.make_filename(product.pk, ext) self.get_and_save_image(url, filename) product.image = filename product.save(update_fields=('image', )) else: product.delete() index += 1
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))