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 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')