def addcontent(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): current_user = request.user data = Product() data.user_id = current_user.id data.category = form.cleaned_data['category'] data.title = form.cleaned_data['title'] data.keywords = form.cleaned_data['keywords'] data.description = form.cleaned_data['description'] data.image = form.cleaned_data['image'] data.Yazar = form.cleaned_data['Yazar'] data.price = form.cleaned_data['price'] data.amount = form.cleaned_data['amount'] data.detail = form.cleaned_data['detail'] data.slug = form.cleaned_data['slug'] data.status = 'False' data.save() messages.success(request, 'Admine Gönderildi onay bekleniyor') return HttpResponseRedirect('/user/contents') else: messages.warning(request, 'Hata var : ' + str(form.errors)) return HttpResponseRedirect('/') else: category = Category.objects.all() menu = Menu.objects.all() form = ProductForm() context = { 'category': category, 'form': form, 'menu': menu, } return render(request, 'user_addcontent.html', context)
def user_newproduct(request): current_user = request.user if request.method == 'POST': # Form post edildiyse form = ProductForm(request.POST, request.FILES) if form.is_valid(): data = Product() # model ile bağlantı kur data.category = form.cleaned_data['category'] # formdan bilgiyi al data.user = current_user data.title = form.cleaned_data['title'] data.keywords = form.cleaned_data['keywords'] data.description = form.cleaned_data['description'] data.price = form.cleaned_data['price'] data.image = form.cleaned_data['image'] data.amount = form.cleaned_data['amount'] data.detail = form.cleaned_data['detail'] data.slug = form.cleaned_data['slug'] data.ip = request.META.get('REMOTE_ADDR') data.save() # veritabanına kaydet messages.success(request, "Ürününüz başarı ile gönderilmiştir.") return HttpResponseRedirect('/user/products') else: messages.warning(request, "Hata:" + str(form.errors)) return HttpResponseRedirect('/user/products') category = Category.objects.all() form = ProductForm() context = {'form': form, 'category': category, } return render(request, 'user_newproduct.html', context)
def addcontent(request): if request.method == 'POST': # form post edildiyse form = ContentForm(request.POST, request.FILES) if form.is_valid(): current_user = request.user data = Product() data.user_id = current_user.id data.category = form.cleaned_data['category'] data.title = form.cleaned_data['title'] data.keywords = form.cleaned_data['keywords'] data.description = form.cleaned_data['description'] data.price = form.cleaned_data['price'] data.amount = form.cleaned_data['amount'] data.detail = form.cleaned_data['detail'] data.slug = form.cleaned_data['slug'] data.status = 'False' data.save() messages.success(request, "Your Content Inserted successfully.") return HttpResponseRedirect('/user/contents') else: messages.success(request, "Content Form error :" + str(form.errors)) return HttpResponseRedirect('/user/addcontent') else: category = Category.objects.all() form = ContentForm() context = { 'form': form, 'category': category, } return render(request, 'user_addcontent.html', context)
def import_ws_product_detail(re_notice): msg = '' success_ids = [] for j in re_notice: p = Product.objects.filter(choies_sku=re_notice[j]['model']).first() if p: continue pass else: try: product = Product() product.category_id = re_notice[j]['category'] product.name = re_notice[j]['name'] product.cn_name = re_notice[j]['cn_name'] product.cost = re_notice[j]['cost'] product.manager_id = 1 product.choies_sku = re_notice[j]['model'] product.weight = re_notice[j]['weight'] product.description = re_notice[j]['size'] product.choies_supplier_name = re_notice[j]['supplier_name'] product.choies_site_url = re_notice[j]['site_url'] product.price = re_notice[j]['other'] product.save() success_ids.append(product.id) supplier = Supplier.objects.filter( deleted=False, name=re_notice[j]['supplier_name']).first() if not supplier: supplier = Supplier.objects.create( name=re_notice[j]['supplier_name']) except Exception, e: msg += "失败创建product:%s%s%s |" % ( re_notice[j]['model'], re_notice[j]['category'], str(e))
def edit_jielong_product(dict, jielong_id): jp = JielongProductRelation.objects.filter(jielong_id=jielong_id, is_valid=0) if jp: for j in jp: j.is_valid = 1 j.save() logger.info("edit_jielong_product activity_id: %s;product_id: %s" % (jielong_id, j.product.id)) else: logger.info("edit_jielong_product activity_id: %s" % (jielong_id)) goods = dict.get("goods") for i in goods: if "id" in i: goods_id = i["id"] else: goods_id = None images = i["images"] small_image = " ".join(images) title = i["title"] description = i["info"] sku_desc = i["specifications"] zk_final_price = i["price"] sku_num = i["count"] if not goods_id: prod = Product() prod.title = title prod.description = description prod.sku_desc = sku_desc prod.zk_final_price = zk_final_price prod.sku_num = sku_num prod.max_buy_limit = 100 prod.small_images = small_image prod.volume = 0 prod.save() goods_id = prod.id # logger.info("edit_jielong_product add-product-info %s;goods_id:%s" % (prod, goods_id)) else: prod_dict = { "title": title, "description": description, "sku_desc": sku_desc, "zk_final_price": zk_final_price, "sku_num": sku_num, "small_images": small_image } Product.objects.update_or_create(id=goods_id, defaults=prod_dict) jp_dict = {"is_valid": 0} jielong_prod = JielongProductRelation.objects.update_or_create( product_id=goods_id, jielong_id=jielong_id, defaults=jp_dict) logger.info("edit_jielong_product param-info %s;jielong_id:%s" % (dict, jielong_id)) return True
def add(request): ImageFormSet = modelformset_factory(Images, fields=('image', ), extra=6) if request.method == 'POST': form = AddEstateForm(request.POST, request.FILES) formset = ImageFormSet(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): current_user = request.user data = Product() data.user_id = current_user.id data.category = form.cleaned_data['category'] data.title = form.cleaned_data['title'] data.keywords = form.cleaned_data['keywords'] data.description = form.cleaned_data['description'] data.price = form.cleaned_data['price'] data.image = form.cleaned_data['image'] data.m2 = form.cleaned_data['m2'] data.room_number = form.cleaned_data['room_number'] data.age_of_building = form.cleaned_data['age_of_building'] data.city = form.cleaned_data['city'] data.detail = form.cleaned_data['detail'] data.status = 'False' data.slug = str(data.category_id) + str(get_random()) + str( get_random()) data.save() for f in formset: try: photo = Images() photo.product_id = data.id photo.image = f.cleaned_data['image'] photo.title = str(data.category_id) + str( data.title) + str(get_random()) photo.save() except Exception as e: break messages.success(request, 'Your content is inserted') return HttpResponseRedirect('/add') else: messages.success(request, 'Form Error: ' + str(form.errors)) return HttpResponseRedirect('/') else: category = Category.objects.all() setting = Setting.objects.get(pk=1) form = AddEstateForm formset = ImageFormSet(queryset=Images.objects.none()) context = { 'category': category, 'form': form, 'formset': formset, 'setting': setting } return render(request, 'add.html', context)
def post(self, request): import pdb pdb.set_trace() body: str = request.body.decode('utf-8') req_body: Dict = loads(body) product = Product() product.name = req_body['name'] product.price = req_body['price'] product.description = req_body['description'] product.category = Category.objects.get(pk=req_body['category']) product.save() data = product_serializer(product) return JsonResponse(data=data, status=201)
def products_new(request): if request.POST: form = UserProductForm(request.POST, request.FILES) if form.is_valid(): user = request.user data = Product() data.user_id = user.id data.category_id = request.POST.get('category') data.title = form.cleaned_data['title'] data.keywords = form.cleaned_data['keywords'] data.description = form.cleaned_data['description'] data.image = form.cleaned_data['image'] data.marka = form.cleaned_data['marka'] data.model = form.cleaned_data['model'] data.renk = form.cleaned_data['renk'] data.year = form.cleaned_data['year'] data.kilometre = form.cleaned_data['kilometre'] data.vites = form.cleaned_data['vites'] data.durum = form.cleaned_data['durum'] data.price = form.cleaned_data['price'] data.amount = form.cleaned_data['amount'] data.detail = form.cleaned_data['detail'] data.slug = form.cleaned_data['slug'] data.status = 'Evet' data.save() messages.success(request, 'Ürününz Eklendi. <a href="/product/' + str(data.id) + '/' + str(data.slug) + '">Ürüne git >></a>', extra_tags='safe') return HttpResponseRedirect('/user/products') else: messages.error( request, 'Lütfen hatalı alanları düzeltiniz <br>' + str(form.errors)) return HttpResponseRedirect('/user/products/new') else: form = UserProductForm() user = request.user current_user = UserProfile.objects.get(user_id=user.id) context = { 'profile': current_user, 'form': form, } return render(request, 'user_products_new.html', context)
def addproduct(request): url = request.META.get('HTTP_REFERER') if request.method == 'POST': #POST EDİLDİYSE form = AddProductForm(request.POST, request.FILES) #forma gidiyor user modelsde if form.is_valid(): current_user = request.user #access user session information data = Product() data.user_id = current_user.id data.category = form.cleaned_data['category'] data.title = form.cleaned_data['title'] data.keywords = form.cleaned_data['keywords'] data.description = form.cleaned_data['description'] data.image = form.cleaned_data['image'] data.price = form.cleaned_data['price'] data.ili = form.cleaned_data['ili'] data.detail = form.cleaned_data['detail'] data.slug = form.cleaned_data['slug'] data.metrekare = form.cleaned_data['metrekare'] data.binayasi = form.cleaned_data['binayasi'] data.kati = form.cleaned_data['kati'] data.banyosayisi = form.cleaned_data['banyosayisi'] data.esyali = form.cleaned_data['esyali'] data.aidat = form.cleaned_data['aidat'] data.balkonsayisi = form.cleaned_data['balkonsayisi'] data.depozito = form.cleaned_data['depozito'] data.odasayisi = form.cleaned_data['odasayisi'] data.isitma = form.cleaned_data['isitma'] data.save() #veritabanına kaydet messages.success(request, "eklendi saolun") return HttpResponseRedirect(url) messages.warning(request, "gönderilemedi bişey bozuk") return HttpResponse('Please correct the error below.<br>' + str(form.errors))
def parse_single_product_page(self, html, cat_id): try: soup = BeautifulSoup(html, 'html.parser') except: return try: article = soup.find('span', class_='product-sku-num').text.strip() except: article = random.randint(1000000, 9999999) try: title = soup.find('h1', class_='product-header').text.strip() except: title = 'Unknown product title' try: price = float( soup.find('div', id='price-less-10').find( 'div', class_='price-cur').find('span', class_='num').text.replace( ',', '.').strip().replace(' ', '')) except: price = 0 try: old_price_container = soup.find('div', id='price-less-10').find( 'div', class_='price-old') except: old_price_container = None discount = 0 if old_price_container: old_price = float( old_price_container.text.strip().split()[0].replace( ',', '.').replace(' ', '')) percent_value = old_price - price discount = float((percent_value / old_price) * 100) brand = None try: characteristics_container = soup.find( 'div', id='product-1-inner').find( 'div', class_='collapse-list-content').find( 'div', class_='product-spec-wrap').find_all( 'div', class_='product-spec__item') except: characteristics_container = [] characteristics = list() for c_item in characteristics_container: holder = c_item.find('dl', class_='product-spec') key = holder.find('dt', class_='product-spec__name').text.strip() value = holder.find('dd', class_='product-spec__value').text.strip() if key.lower() != 'бренд': characteristics.append(dict(key=key.lower(), value=value)) else: brand = value try: description = soup.find('div', id='product-2-inner').find( 'div', class_='collapse-list-content').find('div').find( 'noindex').text except: description = "" documentation_container = soup.find('div', id='product-3') documentation = None if documentation_container: tab_title = documentation_container.find( 'a', class_='tab-link-collaps', recursive=False).text.strip() if tab_title == 'документация': documentation = documentation_container.find( 'div', class_='collapse-list', recursive=False).find('div', class_='collapse-list-content', recursive=False).find( 'div', recursive=False).text images = () try: img_container = soup.find( 'div', class_='product-summary-slider').find_all('div', class_='slider-item') for s in img_container: img = self.download_image(s.find('img').get('src')) if img: images += img, except: pass product = dict(article=article, title=title, price=price, discount=discount, brand=brand, characteristics=characteristics, description=description, documentation=documentation, images=images) print(product) files = list() if len(product['images']) > 0: for img in product['images']: files.append(('files', open(img, 'rb'))) kwargs = dict( data={ 'title': product['title'], 'price': product['price'], 'discount': product['discount'], 'brand': product['brand'], 'characteristics': json.dumps(product['characteristics']), 'description': product['description'], 'documentation': product['documentation'], 'category_id': cat_id, 'article': product['article'] }) brand = None if product['brand']: try: brand = Brand.objects.get(title=product['brand']) except ObjectDoesNotExist: brand = Brand.objects.create(title=product['brand'], slug=slugify(product['brand'])) try: cat = Category.objects.get(id=cat_id) except ObjectDoesNotExist: print('Category not found....') return _product = Product() _product.title = product['title'] _product.price = product['price'] _product.discount = product['discount'] _product.brand = brand _product.category = cat _product.description = product['description'] _product.documentation = product['documentation'] _product.discount = product['discount'] _product.main_image = files[0] _product.save() for c in product['characteristics']: if '?' in c['key']: _key = c['key'].split('?')[0] else: _key = c['key'] try: prop_key = AllProductProperties.objects.get( title=_key.strip().lower()) except ObjectDoesNotExist: prop_key = AllProductProperties.objects.create( title=_key.strip().lower()) if slugify(_key.strip()) == slugify('вес брутто'): value_holder = c['value'].strip().split() ProductProperty.objects.create( product=product, key=prop_key, value=float(value_holder[0].replace(',', '.')), value_type=value_holder[1]) else: if '?' in c['key']: ProductProperty.objects.create( product=product, key=prop_key, value=c['value'], prop_tip=c['key'].strip().split('?')[1]) else: ProductProperty.objects.create(product=product, key=prop_key, value=c['value']) for img in files: ProductImage.objects.create(product=product, image=img) if os.path.exists('logs/process.log'): open_role = 'a' else: open_role = 'w' # with open('logs/process.log', open_role) as f: # f.write( # """ # ================================================================================================= # Product uploaded, server message: %s; \n # Slug: %s; \n # Category_id: %s; \n # images: [%s]; \n # uploading date: %s; # ================================================================================================= # """ % ( # , # slugify(product['title']), # cat_id, # ', '.join(product['images']), # str(datetime.datetime.now()) # ) # ) # f.close() for f in files: f[1].close() for i in product['images']: os.remove(i)
sub3.save() # opens a file with urls of fake articles profilePicRead = open("generator/profile_pictures.txt", "r+") product_title = open("generator/product_names.txt", 'r+') sentencesRead = open("generator/sentences.txt", "r+") # then makes into an array split by endline articleUrl = profilePicRead.read().split("\n") productTitle = product_title.read().split("\n") sentences = re.findall(r"\s+[^.!?]*[.!?]", sentencesRead.read()) for i in range(80): seed = randint(0,200) product = Product() product.title = productTitle[seed%(len(productTitle)-1)] product.description = sentences[seed%(len(sentences)-1)] product.category = categories[randint(1,8888)%categories.count()] product.price = round(random.uniform(1.5, 111.9),3) product.thumbnail = articleUrl[seed%(len(articleUrl)-1)] if (int(product.price) % 2) == 0: product.discount = True product.price_discount_percent = round(random.random()*100) product.price_discount = product.price - product.price*product.price_discount_percent/100 else: product.discount = False rand_gender = round(random.random()*10)%3