Example #1
0
def add_item():
    if request.method == 'GET':
        if (login_session['username'] is not None):
            categories = db.query(Category).all()
            return render_template('add_item.html',
                                   login_session=login_session,
                                   categories=categories)
        else:
            return render_template('login.html',
                                   error="You must be logged in to do that!")
    elif request.method == 'POST':
        if login_session['username'] is not None:
            categories = db.query(Category).all()
            item_name = request.form.get('item_name')
            price = request.form.get('price')
            description = request.form.get('description')
            category = request.form.get('category')
            new_category = request.form.get('new_category')

            if item_name is not None and item_name != '':
                item = Items(name=item_name)
                if price is not None and item.price != '':
                    item.price = price
                if description is not None and description != '':
                    item.description = description
                item.author = getUserInfo(login_session['user_id'])
            else:
                flash("You need to give an item!")
                return redirect(url_for('add_item'))

            if category is not None and category != '':
                c = db.query(Category).filter_by(name=category).first()
                item.category = c
            elif new_category is not None and new_category != '':
                c = db.query(Category).filter_by(name=new_category).first()
                if (c):
                    flash("You cannot add a category that already exists!")
                    return redirect(url_for('add_item'))
                new_category = Category(name=new_category)
                item.category = new_category
                db.add(new_category)
            else:
                flash("You need to provide a category!")
                return redirect(url_for('add_item'))

            db.add(item)
            db.commit()
            return redirect(url_for('index'))
        else:
            flash("Please log in to add items")
            return redirect(url_for('index'))