def add_product(): if session["user_type"] != "Klient": form = ProductForm() form2 = DeleteUserForm() if request.method == "POST": cur = get_db().cursor() form.validate_on_submit() cur.execute( "insert into Produkt values (null, ?, ?, ?, ?)", ( form.name.data, form.net_price.data, form.vat.data, request.getlist("przycisk")[0], ), ) get_db().commit() return redirect(url_for("products")) cur = get_db().cursor() cur.execute("Select id, imie, nazwisko from Osoba") return render_template("html/add_product.html.j2", form=form, persons=cur.fetchall(), form2=form2) return redirect(url_for("index"))
def upload_product(): form = ProductForm() if request.method == 'POST': file = request.files['violin_product'] print(file.filename) path = (os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) file.save(path) #return redirect(url_for('uploaded_product',filename=filename)) # check if the post request has the file part if 'violin_product' not in request.files: flash('No file part') return redirect(request.url) # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect('upload_product') if form.validate_on_submit(): product = Violin(product_images=file.filename, product_name=form.product_name.data, price=form.product_price.data) db.session.add(product) db.session.commit() flash('Your picture has been created!', 'success') return redirect(url_for('view_product')) return render_template("create_product.html", form=form)
def extract(): form = ProductForm() if form.validate_on_submit(): product_id = form.product_id.data scraper(product_id) return redirect(url_for('product', id=product_id)) return render_template("extract.html", form=form)
def extract(): form = ProductForm() if form.validate_on_submit(): product_id = form.product_id.data scraper(product_id) return redirect(url_for('product', id=product_id)) return render_template("extract.html", form=form @app.route('/product/<id>') def product(id): input_directory = "app/opinions_json" opinions = pd.read_json(input_directory+"/"+id+".json") return render_template( "product.html", tables=[ opinions.to_html( classes="table table-hover table-responsive", table_id = "opinions", index = False ) ] ) @app.route('/products') def products(): input_directory = "app/opinions_json" products = [product.replace(".json","") for product in os.listdir(input_directory)] return render_template("products.html", products=products)
def index(): form = ProductForm() products = Product.query.all() context = { "name": "Derek", "title": "Home", "form": form, "products": products } if form.validate_on_submit(): basedir = os.path.abspath( os.path.dirname(__file__)) + '/static/products/uploads/' filename = ''.join([str(random.randint(0, 9)) for i in range(0, 9)]) + '.png' print(basedir + filename) if not os.path.exists(basedir): os.makedirs(basedir) product = Product(name=form.name.data, price=form.price.data, inventory=form.inventory.data) product.image = filename form.image.data.save(basedir + filename) flash("Product created!") db.session.add(product) db.session.commit() return redirect(url_for('index')) return render_template("index.html", **context)
def create_product(): user = current_user form = ProductForm() form['csrf_token'].data = request.cookies['csrf_token'] flavours = [] for x in range(1, 5): if request.form.get(f"flavour-{x}"): el = request.form.get(f"flavour-{x}") flavours.append(el) # find roaster id roaster = Roaster.query.filter(Roaster.user_id == user.id).first() if form.validate_on_submit(): product = Product(name=form.data["name"], roaster_id=roaster.id, price=form.data["price"], description=form.data["description"], sweetness=form.data["sweetness"], acidity=form.data["acidity"], mouthfeel=form.data["mouthfeel"], flavour=flavours) db.session.add(product) db.session.commit() return product.to_dict(), 201 return {"errors": validation_errors_to_error_messages(form.errors)}, 400
def create(): product = ProductForm() register = RegisterForm() if not (register.validate_on_submit()) or not ( product.validate_on_submit()): return redirect(url_for('editor.edit')) reg_user = register_user(register.data.get('email'), register.data.get('password')) if not reg_user: return redirect(url_for('editor.edit')) if str(product.data.get('item_price')).endswith('.0') or str( product.data.get('item_price')): item_price = int(product.data.get('item_price')) else: item_price = product.data.get('item_price') add_product = Product( store_name=request.form.get('store_name'), item_name=product.data.get('item_name'), item_desc=product.data.get('item_desc'), item_currency=product.data.get('item_currency'), item_price=item_price, image=Uploads(request.files['item_img']).save_upload(), contact_email=product.data.get('contact_email')).create_product() if not add_product: return redirect(url_for('editor.edit')) Product.appendTable(reg_user, add_product) return redirect(url_for('seller.dashboard'))
def edit(product_id): product = Product.query.get_or_404(product_id) form = ProductForm(obj=product) if form.validate_on_submit(): product.name = form.name.data product.description = form.description.data db.session.add(product) db.session.commit() return redirect(url_for('.details', product_id=product.id)) return render_template('products/edit.html', form=form, product=product)
def products(): form = ProductForm() shop_session = sfy.Session(session['shop_url'], '2019-04', session['token']) # activate the shopify session to use resources. sfy.ShopifyResource.activate_session(shop_session) if request.method == 'POST': if form.validate_on_submit(): # generate_fake_customer_data(form.number_of_customers_field.data) create_fake_products_and_variants(form.number_of_products_field.data, 5) return render_template('products.html', form=form)
def extract(): form = ProductForm() if form.validate_on_submit(): product_id = form.product_id.data page_respons = requests.get("https://www.ceneo.pl/"+product_id) if page_respons.status_code == requests.codes['ok']: product = Product(product_id) product.extract_product() product.save_product() return redirect(url_for("product", id=product_id)) else: form.product_id.errors.append("Podana wartość nie jest poprawnym kodem ptoduktu.") return render_template("extract.html", form=form)
def extract(): form = ProductForm() if form.validate_on_submit(): product_id = form.product_id.data page_respons = requests.get('https://www.ceneo.pl/'+product_id) if page_respons.status_code == requests.codes['ok']: product = Product(product_id) product.extract_product product.save_product return redirect(url_for('product', id=product_id)) else: form.product_id.errors.append('Podana wartość nie jest poprawnym kodym produktu w serwisie Ceneo.') return render_template('extract.html', form=form)
def extraction(): form = ProductForm() if form.validate_on_submit(): page_response = requests.get("https://www.ceneo.pl"+request.form['product_code']) if page_response.status_code == 200: product = Product(request.form['product_code']) product.extract_product() product.save_product() return redirect(url_for(product, product_id=product.product_id)) else: form.product_code.errors.append("Dla podanego kodu nie ma produktu") return render_template("extraction.html", form=form) return render_template("extraction.html", form=form)
def add_product(company): compname = Company.query.filter_by(company_name=company).first() form = ProductForm() if form.validate_on_submit(): product = Product(name=form.name.data, description=form.description.data, manf_id=form.company.data) db.session.add(product) db.session.commit() flash('Successfully added product') return redirect(url_for('home')) if request.method == 'GET': form.company.data = compname.id return render_template('add_product.html', form=form)
def add_product(): form = ProductForm() if form.validate_on_submit(): if form.photo_url.data: photo_filename = save_photo(form.photo_url.data) product = Product(name=form.name.data, description=form.description.data, price=form.price.data, photo_url=photo_filename) db.session.add(product) db.session.commit() flash('Product created successfully!', 'success') return redirect(url_for('products')) return render_template('add_product.html', title='Add Product', form=form)
def admin(): context = { 'form': ProductForm() } form = ProductForm() if form.validate_on_submit(): filename = time.strftime("%Y%m%d%H%M%S") + '.png' new_product = Product(name=form.name.data, image=filename, price=form.price.data, inventory=form.inventory.data,pr_type=form.pr_type.data, description=form.description.data) file = request.files['image'] file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) db.session.add(new_product) db.session.commit() flash("Added new product to database") return redirect(url_for('admin')) return render_template('admin.html', **context)
def create(): form = ProductForm() if form.validate_on_submit(): price = form.price.data or 0 product = Product(name=form.name.data, description=form.description.data, price_cents=int(price*100), picture_url=form.picture_url.data, creator=current_user, store=current_user.store) db.session.add(product) db.session.commit() return redirect(url_for('products.details', product_id=product.id)) return render_template('products/create.html', form=form)
def newproduct(): form = ProductForm() if form.validate_on_submit(): f = form.image.data filename = secure_filename(f.filename) save_url = os.path.join('app', 'static', filename) f.save(save_url) product = Product(name=form.name.data, price=float(form.price.data), stock=form.stock.data, seller_id=current_user.id, image_url=filename) db.session.add(product) db.session.commit() return redirect(url_for('user', username=current_user.username)) return render_template('newproduct.html', form=form)
def add_product(): if not current_user.is_authenticated: return redirect(url_for('login')) # add product to database # declare the Product Form form = ProductForm(request.form) form.product_type.choices = [(x.id, x) for x in Producttype.query.all()] msg = None if request.method == 'GET': form.process() return render_template('layouts/default.html', content=render_template( 'pages/add-product.html', form=form, message=msg)) print(request.form) # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables name = request.form.get('name', '', type=str) product_type = request.form.get('product_type', '', type=int) description = request.form.get('description', '', type=str) imageurl = request.form.get('imageurl', '', type=str) # see if product already exists product = Product.query.filter_by(name=name, producttype_id=product_type).first() # if product: flash(f'Error: A product named {product.name} already exists!') else: product = Product(name, description, product_type) product.save() flash( f'{name} successfully created! Return to product page or add another product.' ) else: print(form.e) flash('I am sorry but the details you entered cannot be saved') return render_template('layouts/default.html', content=render_template('pages/add-product.html', message=msg, form=form))
def extract(): form = ProductForm() if form.validate_on_submit(): page_response = requests.get("https://www.ceneo.pl/" + request.form["product_code"]) print("problem " + str(page_response.status_code)) print(str(form.product_code)) if page_response.status_code == 200: product = Product(request.form['product_code']) product.extract_product() product.save_product() return redirect(url_for("product", product_id=product.product_id)) else: form.product_code.errors.append( "Dla podanego kodu nie ma produktu") return render_template("extract.html", form=form) # return "Przesłano formularz" return render_template("extract.html", form=form)
def edit_product(id): if not current_user.is_authenticated: return redirect(url_for('login')) # declare the Product Form form = ProductForm(request.form) msg = None # print (current_user) # check if product already exists product = Product.query.filter_by(id=id).first() # update select component value form.product_type.default = product.producttype_id form.product_type.choices = [(x.id, x.name) for x in Producttype.query.all()] if request.method == 'GET': form.process() return render_template('layouts/default.html', content=render_template( 'pages/edit-product.html', form=form, product=product, message=msg)) # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables name = request.form.get('name', '', type=str) product_type = request.form.get('product_type', '', type=int) description = request.form.get('description', '', type=str) imageurl = request.form.get('imageurl', '', type=str) # if the requested product exists if product: product.name = name product.producttype_id = product_type product.description = description db.session().commit() flash(f'{name} successfully edited!') else: flash(f'Error: A product named {product.name} does not exist!') else: flash('I am sorry but the details you entered cannot be saved') return redirect('/psalm2vs8/products')
def save(): log(log.INFO, '/product_save') form = ProductForm(request.form) if form.validate_on_submit(): if form.id.data > 0: product = Product.query.filter(Product.id == form.id.data).first() if product is None: flash("Wrong product id.", "danger") return redirect(url_for('main.products')) for k in request.form.keys(): product.__setattr__(k, form.__getattribute__(k).data) else: product = Product(name=form.name.data, status=form.status.data) product.save() log(log.INFO, "Product-{} was saved".format(product.id)) return redirect(url_for('main.products', id=product.id)) else: flash('Form validation error', 'danger') log(log.WARNING, "Form validation error") return redirect(url_for('product.edit', id=form.id.data))
def handle_product(id): product = Product.query.filter(Product.id == id).first() if product is None: return {"error": "product does not exist"}, 404 if request.method == "PATCH": form = ProductForm() form['csrf_token'].data = request.cookies['csrf_token'] flavours = [] for x in range(1, 4): if request.form.get(f"flavour-{x}"): el = request.form.get(f"flavour-{x}") flavours.append(el) if form.validate_on_submit(): product.name = form.data["name"], product.price = form.data["price"], product.description = form.data["description"], product.sweetness = form.data["sweetness"], product.acidity = form.data["acidity"], product.mouthfeel = form.data["mouthfeel"], product.flavour.clear(), product.flavour = flavours, product.updated_at = datetime.now() db.session.add(product) db.session.commit() return product.to_dict(), 201 if request.method == "DELETE": db.session.delete(product) db.session.commit() return {"message": "Product Deleted"}, 200 return {"message": "Product created"}, 200
def gestionar_productos(): if current_user.tipo == 'cajero': return redirect(url_for('show_cajero_menu')) product_form = ProductForm() current_user.db.conexion.iniciar() cur = current_user.db.conexion.conn.cursor() cur.execute( 'SELECT referencia, nombre, precio, unidades, foto FROM Productos') itemData = cur.fetchall() current_user.db.conexion.cerrar() itemData = parse(itemData) context = {'product_form': product_form, 'itemData': itemData} if product_form.validate_on_submit(): # Tomando datos del formulario ref_number = product_form.ref_number.data product_name = product_form.product_name.data price = product_form.price.data qty = product_form.qty.data photo = product_form.photo.data print('\nRequest form dentro del main:\n{}'.format(request.form)) filename = photo.filename if 'create_button' in request.form: # flash('PRESIONE EL BOTON CREAR', 'info') # Nombrando la imagen que se guardará en el servidor (el path donde sera guardada) if filename: save_filename = secure_filename( product_name + '.' + filename.rsplit('.', 1)[1].lower()) else: save_filename = 'coffee-shop.png' file_path = os.path.join(images_path, save_filename) # Creamos el objeto producto, si no existe se agrega a la BBDD, de lo contrario no y se avisa al user nuevo_producto = Producto(ref_number, product_name, price, qty, save_filename) if current_user.agregar_producto(nuevo_producto): print('\nProducto creado:') # print('Ref: {}\nName: {}\nPrice: {}\nQty: {}\nPath: {}\n'.format(ref_number, # product_name, price, qty, save_filename)) if save_filename == 'coffee-shop.png': pass else: photo.save(file_path) flash('Producto agregado con éxtio!', 'success') else: flash( 'Error, referencia o nombre ya existe en la base de datos.', 'danger') return redirect(url_for('gestionar_productos')) elif 'update_button' in request.form: # flash('PRESIONE EL BOTON ACTUALIZAR', 'info') # Instanciamos un objeto con la informacion del formulario if filename: # Si se va a actualizar la imagen, debemos buscar la referencia a la imagen anterior ddbb_info = current_user.buscar_producto(ref_number) prior_filename = ddbb_info['foto'] delete_path = os.path.join(images_path, prior_filename) # Si la imagen relacionada es la estandar para archivos sin imagen, no hay que eliminar nada if prior_filename == 'coffee-shop.png': pass # Si tiene una referencia distinta a la imagen default, la eliminamos elif os.path.exists(delete_path): os.remove(delete_path) else: print('No se eliminó el archivo') flash('No se eliminó el archivo anterior', 'info') #En caso de que al actualizar el usuario no haya pasado un nuevo product name al formulario # le asignamos el nombre que ya traía, para guardar la imagen if not product_name: product_name = ddbb_info['nombre'] save_filename = secure_filename( ref_number + '.' + filename.rsplit('.', 1)[1].lower()) file_path = os.path.join(images_path, save_filename) else: save_filename = filename producto_a_actualizar = Producto(int(ref_number), product_name, price, qty, save_filename) if current_user.actualizar_producto(producto_a_actualizar): if save_filename == '': pass else: photo.save(file_path) flash('Producto actualizado con éxtio!', 'success') else: flash( 'Error, no existe un producto con esa referencia en la base de datos.', 'danger') return redirect(url_for('gestionar_productos')) elif 'delete_button' in request.form: # flash('PRESIONE EL BOTON ELIMINAR', 'info') producto_a_eliminar = Producto(int(ref_number), product_name, price, qty, filename) # print('\nProducto a eliminar\n{}\n'.format(producto_a_eliminar.__dict__)) ddbb_info = current_user.buscar_producto(ref_number) # print(ddbb_info) if current_user.eliminar_producto(producto_a_eliminar): # Accedemos a la info de la BBDD perteneciente a ese producto, necesitamos el nombre de la imagen #del producto, para poder eliminarla save_filename = ddbb_info['foto'] file_path = os.path.join(images_path, save_filename) if save_filename == 'coffee-shop.png': pass elif os.path.exists(file_path): os.remove(file_path) print( '\nEl producto fue eliminado de la base de datos y el archivo de la carpeta\n' ) else: print("The file does not exist") flash("The file does not exist", 'danger') flash('Producto eliminado con éxito!', 'success') else: flash('No existe un producto con esa referencia', 'warning') # print('\nAl presionar el boton Eliminar vemos') # print('Info de la imagen cargada - product_form.photo.data = {}'.format(photo)) # print('Uploaded filename ', photo.filename) # print(photo.filename == '') # print(help(photo)) return redirect(url_for('gestionar_productos')) return render_template('gestionar_productos.html', isLogged=True, **context)