Esempio n. 1
0
def new_product():
    form = NewProductForm()
    if not form.validate_on_submit():
        return render_template('new_product.html', form=form)

    category = form.category.data.strip()
    name = form.name.data.strip()
    price = int(form.price.data)
    product_des = form.product_des.data.strip()

    if Product.query.filter(Product.name == name).count():
        flash(f'Error: {name} already exists')
        return render_template('new_product.html', form=form)

    prod_cat = Category.query.filter(Category.name == category).first()

    if not Category.query.filter(Category.name == category).count():
        flash(f'Error: {name} needs existing category {category}')
        return render_template('new_product.html', form=form)

    product = Product(category=prod_cat, name=name, product_des=product_des, price=price)
    db.session.add(product)
    db.session.commit()
    flash(f'New product {name} created')
    return redirect('/products')