Exemple #1
0
def newMenuItem(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if 'username' not in login_session:
        return redirect('/login')
    if login_session['user_id'] != restaurant.user_id:
        return """<script>
        function myFunction() {alert('You are not authorized to add new item to this restaurant.'); 
        window.location.href = '/restaurants/%d/';}
        </script>
        <body onload='myFunction()'> """ % restaurant_id
    if request.method == 'POST':
        newItem = MenuItem(name = request.form['name'], restaurant_id = restaurant_id, 
            description=request.form['description'], price=request.form['price'], 
            course=request.form['course'], user_id=restaurant.user_id)
        # uploads and saves the file in directory and the name of the file is stored in the database
        if request.files['picture_file']:
            filename = upload_file(restaurant_id)
            savedFile = str(filename)
            newItem.picture = savedFile
        session.add(newItem)
        session.commit()
        flash("new menu item created")
        return redirect(url_for('restaurantMenu', restaurant_id = restaurant_id))
    else:
        return render_template('newmenuitem.html', restaurant_id=restaurant_id)
def newMenuItem(restaurant_id):
    """

    Args:
        restaurant_id: An integer value corresponding to an existing restaurant

    Returns: Responds to the user request to show the page for creating a new menu item and also handles the posted
    attempt at creating the new menu item

    """
    # First, make sure the user is authenticated (cannot create a new menu item if not logged in)
    if not isLoggedIn():
        return redirect('/login')

    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()

    # Receive the attempt to create the new menu item or return the page for the user to create one
    if request.method == 'POST':
        # Validate the form
        if not formHasMember(request.form, 'name'):
            flash("new menu items must have a name")
        else:
            newItem = MenuItem(
                name=request.form['name'],
                description=request.form['description'],
                price=request.form['price'],
                course=request.form['course'],
                restaurant_id=restaurant_id,
                user_id=login_session['user_id']
            )
            if formHasMember(request.form, 'picture'):
                newItem.picture = request.form['picture']

            session.add(newItem)
            session.commit()

            flash("new menu item %s created successfully!" % newItem.name)
            return redirect(url_for('showMenu', restaurant_id=restaurant_id))

    return render_template('new-menu-item.html', restaurant=restaurant, auth=True)