Example #1
0
def editrecipe(recipe_id):
    if 'username' not in session:  # Same for editing, logged in users ONLY
        flash('Not possible for non-members! Please create an account.')
        return redirect(url_for('register'))

    form = RecipeForm()
    getrep = mongo.db.Recipes.find_one({'_id': ObjectId(recipe_id)})
    # Find the recipe to edit
    if request.method == 'GET':  # GET the recipe
        form = RecipeForm(data=getrep)
        return render_template('edit_recipe.html', recipe=getrep,
                               form=form, title="Edit Recipe")
    if form.validate_on_submit:
        rec = mongo.db.Recipes
        rec.update_one({'_id': ObjectId(recipe_id), }, {
            '$set': {'recipe_name': request.form['recipe_name'],
                     # Populates the fields with the data to be edited.
                     'recipe_type': request.form['recipe_type'],
                     'recipe_desc': request.form['recipe_desc'],
                     'serving': request.form['serving'],
                     'prep_time': request.form['prep_time'],
                     'cook_time': request.form['cook_time'],
                     'ingredients': request.form.getlist('ingredients'),
                     'method': request.form.getlist('methods'),
                     # Lists for Ingredients and Method to store in an array.
                     'img_url': request.form['img_url']}})
        flash('Recipe Succesfully Updated.')
        return redirect(url_for('recipe', recipe_id=recipe_id))
    return render_template(url_for('recipe', recipe_id=recipe_id))
def edit_recipe(recipe_id):
    if not ObjectId.is_valid(recipe_id):
        return render_template('recipe_error.html',
                               message="No recipe found",
                               message_class='warning',
                               btn_class='red darken-4')
    recipe = recipe_model.get_edit_data(ObjectId(recipe_id),
                                        session['user']['username'])
    if recipe is False:
        return render_template('recipe_error.html',
                               message="You can't edit someone recipe",
                               message_class='error',
                               btn_class='')
    init_form = RecipeForm(recipe, request.form)
    if request.method == 'POST' and init_form.validate():
        data = RecipeForm(request.form)
        recipe_model.update(data, ObjectId(recipe_id))
        flash('Recipe has been edited', 'success')
        return redirect(url_for('view_recipe', recipe_id=recipe_id))

    return render_template('recipe_edit.html',
                           form=init_form,
                           form_action=url_for('edit_recipe',
                                               recipe_id=recipe_id),
                           recipe_id=recipe_id,
                           title='Edit recipe',
                           body_class='edit_recipe')
Example #3
0
def edit_recipe(id=1):
    recipe = Recipe.query.filter_by(id = id).first()
    app.logger.info('Editing Recipe ' + str(id))
    form = RecipeForm(obj = recipe)
    if recipe == None:
        flash('Recipe not found.')
        return redirect(url_for('index'))
    if request.method == 'POST':
        app.logger.debug('request.data')
        app.logger.debug(request.data)
        app.logger.debug('Method = POST')
        valid = form.validate_on_submit()
        if valid:
            app.logger.info('Validation Successful - ' + str(form.recipe_name.data))
            form.populate_obj(recipe)
            if len(request.files) > 0 and request.files['image_file'].filename:
                req = request
                filename = req.files['image_file'].filename
                recipe_name = recipe.recipe_name
                recipe.image_path = upload_image(req, filename, recipe_name)
                if recipe.image_path is None:
                    app.logger.error('Error uploading image')
                    flash("Error uploading image")
                
            db.session.add(recipe)
            db.session.commit()
            flash('Your changes have been saved.')
            return redirect(url_for('view_recipe', id=id))
        else:
            app.logger.info("Failed Validation")
            
    return render_template('recipe_form.html',
        title="Edit a Recipe",
        form = form)
Example #4
0
def create_task():
    """Create a new recipe to db collection"""
    if 'logged_in' not in session:  # Check if its a logged in user
        flash(
            'Sorry, only logged in users can create recipes. Please register/login',
            'info')
        return redirect(url_for('index'))

    form = RecipeForm(request.form)  # Initialise the form
    user = mongo.db.user.find_one({"name": session['username'].title()})

    if form.validate_on_submit():  # Insert new recipe if form is submitted
        tasks = mongo.db.tasks
        tasks.insert_one({
            'recipe_name': request.form['recipe_name'],
            'recipe_image': request.form['recipe_image'],
            'ingredients': request.form['ingredients'],
            'serving_size': request.form['serving_size'],
            'recipe_course': request.form['recipe_course'],
            'allergen': request.form['allergen'],
            'calories': request.form['calories'],
            'description': request.form['description'],
            'cooking_time': request.form['cooking_time'],
            'instruction': request.form['instruction'],
            'instruction1': request.form['instruction1'],
            'instruction2': request.form['instruction2'],
            'instruction3': request.form['instruction3'],
            'instruction4': request.form['instruction4'],
            'instruction5': request.form['instruction5'],
            'instruction6': request.form['instruction6'],
            'username': session['username'].title(),
        })
        flash('Your Recipe has been added successfully', 'success')
        return redirect(url_for('index'))
    return render_template('add_recipe.html', form=form, title="Add Recipe")
Example #5
0
def create_recipe():
    """Create new recipe"""
    if 'username' not in session:
        flash("Please log in to view this page", "danger")
        return redirect('/login')

    form = RecipeForm()
    username = session['username']

    if form.validate_on_submit():
        title = form.title.data
        image = form.image.data
        calories = form.calories.data
        total_yield = form.total_yield.data
        time = form.time.data
        ingredients = form.ingredients.data

        user = User.query.get_or_404(username)
        recipe = Recipe(title=title,
                        image=image,
                        url=None,
                        calories=calories,
                        total_yield=total_yield,
                        time=time,
                        ingredients=ingredients,
                        username=username)
        db.session.add(recipe)
        db.session.commit()

        flash('Recipe added', "success")
        return redirect(f"/users/{username}")
    return render_template("new_recipe.html", form=form)
Example #6
0
def create_recipe():
    """Create a new recipe to db collection"""
    if 'logged_in' not in session:  # Check if its a logged in user
        flash('Sorry, only logged in users can create recipes.')
        return redirect(url_for('index'))

    form = RecipeForm(request.form)  # Initialise the form
    user = mongo.db.user.find_one({"name": session['username'].title()})

    if form.validate_on_submit():  # Insert new recipe if form is submitted
        recipes = mongo.db.recipe
        recipes.insert_one({
            'recipe': request.form['recipe_name'],
            'recipe_name': request.form['recipe_name'],
            'recipe_image': request.form['recipe_image'],
            'serving_size': int(request.form['serving_size']),
            'diet_labels': request.form['diet_labels'],
            'health_labels': request.form['health_labels'],
            'ingredients': request.form['ingredients'],
            'calories': request.form['calories'],
            'cooking_time': request.form['cooking_time'],
            'i-made-it': int(0),
            'description': request.form['description'],
            'source': request.form['source'],
            'username': session['username'].title(),
            'created_by': {
                '_id': user['_id'],
                'name': user['name']
            }
        })
        flash('Recipe Added!')
        return redirect(url_for('index'))
    return render_template('add_recipe.html', form=form, title="Add Recipe")
Example #7
0
def correct_recipe(request):
	if request.method == 'POST':
		form = RecipeForm(request.POST, request.FILES)
		if form.is_valid():
			recipe = form.save(commit=False)
			recipe.user = request.user
			recipe.save()
			junk_id = request.POST['junkid']
			junk = JunkRecipe.objects.get(id = junk_id)
			formset = RecipeIngredientsFormset(request.POST, request.FILES, instance=recipe)
			if formset.is_valid():
				formset.save()
				recipe.save()
				junk.is_added = True
				junk.derived_recipe = recipe
				junk.save()
				return render_to_response('recipes/view_recipe.html', {'recipe': recipe,}, context_instance=RequestContext(request))
			else:
				recipe.delete()
		else:
			junk_id = request.POST['junkid']
			junk = JunkRecipe.objects.get(id = junk_id)
			formset = RecipeIngredientsFormset(request.POST, request.FILES)
	else:
		junk = random.choice(JunkRecipe.objects.filter(is_added = False))
		form = RecipeForm()
		formset = RecipeIngredientsFormset()
	return render_to_response('recipes/correct_recipe.html', {'form': form, 'formset': formset, 'junk': junk}, context_instance=RequestContext(request))
Example #8
0
def new_recipe():
    form = RecipeForm()
    if form.validate_on_submit():
        recipe = Recipes(name=form.name.data,note=form.description.data, category=form.category.data, subcategory=form.subcategory.data, food_type=form.cuisine.data,prep_time=form.prep_time.data,favourite=form.favourite.data)
        db.session.add(recipe)        
        db.session.flush()
        for p in form.photos.entries:
            photo = Photos.query.filter_by(filename=p.data).first()
            if photo:
                recipe.recipephotos.append(photo)
                db.session.add(recipe)
                db.session.flush()
            
        for i in form.ingridients.entries:
            i_list = IngidientList(recipe_id=recipe.id,quantity = i.data['quantity'], unit = i.data['unit'], ingridient_id=i.data['name'].id)
            db.session.add(i_list)
            db.session.flush()
            
        for idx, s in enumerate(form.steps.entries):
            s_name = "Step-"+str(idx+1)
            s_list = Steps(description = s.data['description'], recipe_id=recipe.id, name=s_name)
            db.session.add(s_list)
            db.session.flush()
            
            photo = Photos.query.filter_by(filename=s.data['photo']).first()
            if photo:
                s_list.photo_id = photo.id
        db.session.commit()
        flash('Recipe added successfully!','alert-success')
        return redirect(url_for('recipeapp.new_recipe'))
    if form.errors:
        flash(form.errors,'alert-danger')
    return render_template('recipeapp/editor.html',form=form)
Example #9
0
def index():
  recipe_form = RecipeForm(csrf_enabled=False)
  if recipe_form.validate_on_submit():
    new_id = len(recipes)+1
    recipes[new_id] = recipe_form.recipe.data
    types[new_id] = recipe_form.recipe_type.data
    descriptions[new_id] = recipe_form.description.data
    new_igredients = recipe_form.ingredients.data
    new_instructions = recipe_form.instructions.data
    add_ingredients(new_id, new_igredients)
    add_instructions(new_id, new_instructions)
    "I'm not sure why Codecademy added the following line for the '/' route, when comments aren't utilized"
    #comments[new_id] = []

    """
    When the new recipe is added, the browswe redirects to the newly added recipe's page
    """
    
    return redirect(
      url_for(
        "recipe",
        id = new_id,
        _external = True,
        _scheme="https"
      )
    )

  return render_template("index.html", template_recipes=recipes, template_form=recipe_form)
Example #10
0
def edit_recipe(id):
    """ function that allows users to edit a recipe they
        have already posted to the database """

    chosen_recipe = mongo.db.recipes.find_one({'_id': ObjectId(id)})
    form = RecipeForm(data=chosen_recipe)

    if request.method == "GET":
        return render_template('edit_recipe.html',
                               form=form,
                               title="Edit Recipe")
    elif request.method == "POST":
        if form.validate_on_submit():
            recipes = mongo.db.recipes

            recipes.update_one({'_id': ObjectId(id)}, {
                '$set': {
                    'recipe_name': request.form['recipe_name'],
                    'summary': request.form['summary'],
                    'description': request.form['description'],
                    'ingredients': request.form['ingredients'],
                    'equipment': request.form['equipment'],
                    'prep_time': request.form['prep_time'],
                    'cook_time': request.form['cook_time'],
                    'serves_num': request.form['serves_num'],
                    'method': request.form['method'],
                    'course': request.form['course'],
                    'cuisine': request.form['cuisine'],
                }
            })
            flash('Recipe Updated ', 'success')
            return redirect(url_for('recipe', id=id))
    else:
        flash('An error occured', 'danger')
        return render_template('index.html')
Example #11
0
def add_recipe():
    if request.query_string[:4] == "url=":
       app.logger.info("Adding from source:  " + request.query_string[4:])
       form = fillout_form( request.query_string[4:] )
    else:
        form = RecipeForm(request.form)
    if request.method == "POST":
        if form.validate_on_submit():
            app.logger.info("Adding a new Recipe")
            recipe=Recipe()
            form.populate_obj(recipe)
            if len(request.files) > 0:
                app.logger.debug("Image uploaded")
                req = request
                filename = req.files['image_file'].filename
                recipe_name = recipe.recipe_name
                recipe.image_path = upload_image(req, filename, recipe_name)
                if recipe.image_path is None:
                    flash("Error uploading image")
            recipe.user_id = 1
            recipe.timestamp = date.today()
            db.session.add(recipe)
            db.session.commit()
            
            new_rec = Recipe.query.filter(Recipe.recipe_name==  str(recipe.recipe_name)).first()
            #import pdb; pdb.set_trace()
            return redirect(url_for('view_recipe', id=new_rec.id))
        else:
            flash('Invalid data')
            return render_template('recipe_form.html',form = form, title="Add A New Recipe")
    elif request.method != "POST":
        return render_template('recipe_form.html',form = form, title="Add A New Recipe")
    return redirect(url_for('add_recipe'))
Example #12
0
def edit_task(task_id):
    count_tasks = mongo.db.tasks.find().count()
    favourite_count = mongo.db.tasks.find({'favourite': True}).count()
    if 'logged_in' not in session:  # Check if its a logged in user
        flash('Apologies, only logged in users can edit recipes.')
        return redirect(url_for('index'))

    user = mongo.db.user.find_one({"name": session['username'].title()})
    task = mongo.db.tasks.find_one_or_404({"_id": ObjectId(task_id)})
    form = RecipeForm()
    """
    Find a particular task, parameter passed is 'id', looking
    for a match to 'id' in MongoDB, then wrapped for editing
    purposes.
    Reuse much of the layout in 'add_tasks' function,
    but with pre-populated fields.
    """
    if user['name'].title() == task['username'].title():
        if request.method == 'GET':
            form = RecipeForm(data=task)
            current_user = mongo.db.user.find_one(
                {'name': session['username'].title()})
            return render_template('editrecipe.html',
                                   task=task,
                                   current_user=current_user,
                                   count_tasks=count_tasks,
                                   favourite_count=favourite_count,
                                   form=form,
                                   title="Edit Recipe")
        if form.validate_on_submit():
            tasks = mongo.db.tasks  # Access to the tasks collection in mongo.db
            tasks.update_one({
                '_id': ObjectId(task_id),
            }, {
                '$set': {
                    'category_name': request.form['category_name'],
                    'complexity': request.form['complexity'],
                    'recipe_name': request.form['recipe_name'],
                    'author_name': request.form['author_name'],
                    'prep_time_mins': int(request.form['prep_time_mins']),
                    'cook_time_mins': int(request.form['cook_time_mins']),
                    'calories': int(request.form['calories']),
                    'servings': int(request.form['servings']),
                    'brief_description': request.form['brief_description'],
                    'ingredients': request.form['ingredients'],
                    'instructions': request.form['instructions'],
                    'recipe_image': request.form['recipe_image'],
                    'favourite': 'favourite' in request.form
                }
            })
            flash('Your recipe has been updated!')
            return redirect(url_for('task', tasks_id=task_id))
    flash("Apologies, this is not your recipe to edit!")
    return redirect(url_for('task', tasks_id=task_id))
Example #13
0
def new_recipe():
    form = RecipeForm(request.form)
    if request.method == 'POST' and form.validate():
        added_id = recipe_model.add(form, session['user']['username'])
        flash('Recipe has been added', 'success')
        return redirect(url_for('view_recipe', recipe_id=added_id))
    return render_template('recipe_edit.html',
                           form=form,
                           form_action=url_for('new_recipe'),
                           title='Add recipe',
                           body_class='edit_recipe')
Example #14
0
def add_tasks():
    """
    Add a new recipe to mongodb database collection
    """
    count_tasks = mongo.db.tasks.find().count()
    favourite_count = mongo.db.tasks.find({'favourite': True}).count()
    # Allows task categories in MongoDB to connect with addtask.html file
    if 'logged_in' not in session:  # Check for user logged in
        flash('Apologies, only logged in users can add recipes.')
        return redirect(url_for('index'))

    form = RecipeForm(request.form)  # Initialise the form
    user = mongo.db.user.find_one({"name": session['username'].title()})
    if 'logged_in' in session:
        form = RecipeForm(request.form)
        current_user = mongo.db.user.find_one(
            {'name': session['username'].title()})
    else:
        return render_template('addrecipe.html',
                               count_tasks=count_tasks,
                               favourite_count=favourite_count,
                               page_title='Add New Recipe',
                               form=form,
                               current_user=current_user)
    if form.validate_on_submit():  # Insert new recipe if form is submitted
        tasks = mongo.db.tasks
        tasks.insert_one({
            'category_name': request.form['category_name'],
            'complexity': request.form['complexity'],
            'recipe_name': request.form['recipe_name'],
            'author_name': request.form['author_name'],
            'prep_time_mins': int(request.form['prep_time_mins']),
            'cook_time_mins': int(request.form['cook_time_mins']),
            'calories': int(request.form['calories']),
            'servings': int(request.form['servings']),
            'brief_description': request.form['brief_description'],
            'ingredients': request.form['ingredients'],
            'instructions': request.form['instructions'],
            'recipe_image': request.form['recipe_image'],
            'favourite': 'favourite' in request.form,
            'username': session['username'].title(),
            'created_by': {
                '_id': user['_id'],
                'name': user['name']
            }
        })
        return redirect(url_for('index'))
    return render_template('addrecipe.html',
                           count_tasks=count_tasks,
                           favourite_count=favourite_count,
                           current_user=current_user,
                           form=form,
                           title="Add New Recipe")
Example #15
0
def edit(request, rpID):
    rp = get_object_or_404(Recipe, pk=rpID, ruser=request.user)
    if not request.user.is_active:
        HttpResponseForbidden()
    if request.method == "POST":
        form = RecipeForm(request.POST, request.FILES)
        if form.is_valid():
            rp = form.save()
            create_thumb(rp)
            return HttpResponseRedirect(reverse("recipedia.views.create_edit", args=[rp.pk]))
    else:
        form = RecipeForm()
    return render_to_response("new_recipe.html", {"form": form}, context_instance=RequestContext(request))
 def test_recipe(self):
     data = [
         ('title', 'Test recipe'),
         ('introduction', None),
         ('method-0', 'Method'),
         ('ingredients-0', 'Ingredient'),
         ('categories-0', None),
         ('cuisines-0', None),
         ('allegrens-0', None)
     ]
     form = RecipeForm(MultiDict(data))
     self.assertTrue(form.validate())
     self.assertEqual(form.title.data, 'Test recipe')
Example #17
0
def update_task(task_id):
    # Check if user is logged in
    if 'logged_in' not in session:  # Check if its a logged in user
        flash(
            'Sorry, only logged in users can edit their own recipes. Please login',
            'info')
        return redirect(url_for('index'))

    user = mongo.db.user.find_one({"name": session['username'].title()})
    the_task = mongo.db.tasks.find_one_or_404({'_id': ObjectId(task_id)})
    form = RecipeForm()

    # If user created then they can edit
    if user['name'].title() == the_task['username'].title():

        if request.method == 'GET':
            form = RecipeForm(data=the_task)
            return render_template('edit_recipe.html',
                                   task=the_task,
                                   form=form,
                                   title='Edit Recipe')

        if form.validate_on_submit():
            task = mongo.db.tasks
            task.update_one({
                '_id': ObjectId(task_id),
            }, {
                '$set': {
                    'recipe_name': request.form['recipe_name'],
                    'recipe_image': request.form['recipe_image'],
                    'ingredients': request.form['ingredients'],
                    'serving_size': request.form['serving_size'],
                    'recipe_course': request.form['recipe_course'],
                    'allergen': request.form['allergen'],
                    'calories': request.form['calories'],
                    'description': request.form['description'],
                    'cooking_time': request.form['cooking_time'],
                    'instruction': request.form['instruction'],
                    'instruction1': request.form['instruction1'],
                    'instruction2': request.form['instruction2'],
                    'instruction3': request.form['instruction3'],
                    'instruction4': request.form['instruction4'],
                    'instruction5': request.form['instruction5'],
                    'instruction6': request.form['instruction6'],
                }
            })
            flash('Your Recipe has been updated', 'info')
            return redirect(url_for('task', task_id=task_id))
    flash('Sorry not your recipe to edit!', 'danger')
    return redirect(url_for('task', task_id=task_id))
def index():
    recipe_form = RecipeForm(csrf_enabled=False)
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_ingredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_ingredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Example #19
0
def new_recipe():
    
    class IngredientSelector(Form):
        ingredients = models.Ingredient.query.order_by(models.Ingredient.name.asc())
        choices = []
        for each in ingredients:
            choices.append((str(each.id), each.name.title()))

        ingredient = SelectMultipleField(u'Ingredients', choices = choices)

    form = RecipeForm()
    selector = IngredientSelector()
    rid = models.Recipe
    if form.validate_on_submit():
        recipe = models.Recipe(
                name = form.name.data,
                difficulty = form.difficulty.data,
                time = form.time.data,
                servings = form.servings.data,
                instructions = form.instructions.data,
                user_id = g.user.get_id(),
                image = form.image.data
        )
        if form.image:
            form.image.data.save(os.path.join(RECIPE_IMAGE_PATH, '%s.jpg' % recipe.name))
            recipe.image = "/uploads/recipe_images/%s.jpg"% recipe.name
        if Recipe.query.filter_by(name = recipe.name).count() > 0:
            flash('A recipe with this name already exists!');
            return render_template('new_recipe.html', form = form, selector = selector)
        db.session.add(recipe)
        db.session.commit()
        
        selected_ingredients = selector.ingredient.data

        for each in selected_ingredients:
            i = Ingredient.query.get(each)
            recipe.add_ingredient(i)

        db.session.commit()

        flash(recipe.name + ' created!')
        return redirect(url_for('user', email = g.user.email))
    
    if form.errors:
        flash('A field in the recipe form was invalid!')
    
    return render_template('new_recipe.html', form = form, selector = selector)
Example #20
0
def edit_recipe(recipe_id):
    form = RecipeForm(request.form)
    recipe = Recipe.query.filter_by(id=recipe_id).first_or_404()
    if request.method == 'POST' and form.validate():
        recipe.title = form.title.data
        recipe.ingredients = form.ingredients.data
        recipe.time_needed = form.time_needed.data
        recipe.steps = form.steps.data
        recipe.status = form.status.data
        db.session.commit()
        flash('Recipe edited successfully', 'success')
        return redirect(url_for('my_recipes'))
    # I need to set the values for ingredients and steps, because they're from textarea, and that
    # doesn't support value for field.
    form.ingredients.data = recipe.ingredients
    form.steps.data = recipe.steps
    return render_template('recipes/edit.html', form=form, recipe=recipe)
Example #21
0
def index(request):
    if request.method == 'POST':
        form = RecipeForm(request.POST)
        if form.is_valid():
            recipes = Recipe.objects.all().order_by("name")

            for filter_method in FILTER_METHODS:
                recipes = filter_method(form, recipes)

            return render(request, 'home.html', {'form': form, 'recipe_list': recipes})
    else:
        reset = request.GET.get('reset', None) != None
        load(reset=reset)
        form = RecipeForm

    return render_to_response('home.html', {'form': form, 'recipe_list': Recipe.objects.all().order_by("name")},
                              context_instance=RequestContext(request))
Example #22
0
def create(request):
    # the 1st step of 3 phases recipe creation
    if not request.user.is_active:
        HttpResponseForbidden()
    if request.method == "POST":
        form = RecipeForm(request.POST, request.FILES)
        if form.is_valid():
            rp = form.save(commit=False)
            data = form.cleaned_data
            rp.activation_key = activation_key(request)
            rp.ruser = request.user
            rp.save()
            create_thumb(rp)
            return HttpResponseRedirect(reverse("recipedia.views.create_edit", args=[rp.pk]))
    else:
        form = RecipeForm()
    return render_to_response("new_recipe.html", {"form": form}, context_instance=RequestContext(request))
Example #23
0
def index():
    recipe_form = RecipeForm()
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_ingredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_ingredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
        #### Redirect to recipe route here
        return redirect(url_for('recipe', id=new_id))
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Example #24
0
def index():
    recipe_form = RecipeForm(csrf_enabled=False)
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_igredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_igredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
        return redirect(
            url_for("recipe", id=new_id, _external=True, _scheme='https'))
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Example #25
0
def get_recipes():
    form = RecipeForm()
    if form.validate_on_submit():
        name = form.name.data
        contents = [
            r.ingredient_name
            for r in db.session.query(MenuDish.ingredient_name).filter_by(
                dish_name=name).distinct()
        ]
        if not contents:
            flash("That item is not in the inventory!")
            return render_template('recipes.html', form=form)
        results = f"{name}"
        return render_template('recipe_results.html',
                               contents=contents,
                               results=results)
    return render_template('recipes.html', form=form)
Example #26
0
def index():
    recipe_form = RecipeForm(request.form, meta={'csrf': False})
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_igredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_igredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
        #### Redirect to recipe route here
        return redirect(
            url_for("recipe", id=new_id, _external=True, _scheme='http'))
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Example #27
0
def add(request):
    def storeInS3(recipe_id, filename, content):
        conn = S3Connection(settings.AWS_ACCESS_KEY_ID,
                            settings.AWS_SECRET_ACCESS_KEY)
        b = conn.create_bucket(settings.S3BUCKET)
        mime = mimetypes.guess_type(filename)[0]
        k = Key(b)
        k.key = 'recipe_id_' + str(recipe_id) + '_' + filename
        k.set_metadata("Content_Type", mime)
        content.seek(0)
        k.set_contents_from_file(content)
        k.set_acl("public-read")

    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES)
        recipeName = request.POST['name']
        if Recipe.objects.filter(name=recipeName).count() > 0:
            messages.add_message(
                request, messages.ERROR, "The recipe name " + recipeName +
                " has been taken. Please choose another name for your recipe.")
            return render(request, 'shakeapp/add.html')
        if form.is_valid():
            newRecipe = form.save(commit=False)
            pictureFile = form.cleaned_data['picture']
            newRecipe.picture.save(pictureFile.name, pictureFile)
            filename = pictureFile.name

            storeInS3(newRecipe.id, filename, pictureFile.file)
            newRecipe.url = settings.S3URL + 'recipe_id_' + str(
                newRecipe.id) + "_" + filename
            newRecipe.save()
            return HttpResponseRedirect("/shakeapp/")
        else:
            print
            print form.errors
            messages.add_message(
                request, messages.ERROR,
                "There has been an error in the form. Please make sure your inputs are correct."
            )
            return render(request, 'shakeapp/add.html')
    return render_to_response('shakeapp/add.html',
                              context_instance=RequestContext(request))
Example #28
0
def edit_recipe(request, id):
	recipe = get_object_or_404(Recipe, id=id)
	tag_prepop = Tag.objects.get_for_object(recipe)
	tool_prepop = recipe.tools.all()
	if recipe.user != request.user and request.user.is_superuser == False:
		return render_to_response('recipes/forbidden.html', context_instance=RequestContext(request))
	if request.method == 'POST':
		form = RecipeForm(request.POST, request.FILES, instance=recipe)
		formset = RecipeIngredientsFormset(request.POST, request.FILES, instance=recipe)
		if form.is_valid():
			recipe = form.save(commit=False)
			if formset.is_valid():
				formset.save()
				recipe.save()
				return render_to_response('recipes/view_recipe.html', {'recipe': recipe,}, context_instance=RequestContext(request))
	else:
		form = RecipeForm(instance=recipe)
		formset = RecipeIngredientsFormset(instance=recipe)
	return render_to_response('recipes/edit_recipe.html', {'recipe': recipe, 'form': form, 'formset': formset, 'tag_prepop': tag_prepop, 'tool_prepop': tool_prepop}, context_instance=RequestContext(request))
Example #29
0
def add_recipe(request):
	if request.method == 'POST':
		form = RecipeForm(request.POST, request.FILES)
		if form.is_valid():
			recipe = form.save(commit=False)
			recipe.user = request.user
			recipe.save()
			formset = RecipeIngredientsFormset(request.POST, request.FILES, instance=recipe)
			if formset.is_valid():
				formset.save()
				recipe.save()
				return render_to_response('recipes/view_recipe.html', {'recipe': recipe,}, context_instance=RequestContext(request))
			else:
				recipe.delete()
		else:
			formset = RecipeIngredientsFormset(request.POST, request.FILES)
	else:
		form = RecipeForm()
		formset = RecipeIngredientsFormset()
	return render_to_response('recipes/add_recipe.html', {'form': form, 'formset': formset}, context_instance=RequestContext(request))
Example #30
0
def newMealPlan():
    form = RecipeForm()
    choice = form.diet_type.data
    firstconnection = mysql.connection.cursor()
    firstconnection.execute(
        '''SELECT * FROM meals WHERE meal_id IN (SELECT creates.meal_id FROM creates WHERE creates.meal_id IN(SELECT recipes.recipe_id FROM recipes WHERE recipes.recipe_diet_type = ))'''
    )  #+ '"'+choice+'"' + "))")
    result = list(firstconnection.fetchall())
    for i in range(0, 22):
        print(list[i])
    return result
Example #31
0
def add_recipe():
    """ function that allows user to create a new recipe
        and store it in the database """

    form = RecipeForm()

    # If they are trying to add a recipe and the form validates
    if request.method == "POST":
        if form.validate_on_submit():
            # Using base64 to store photo in database
            code_str = base64.b64encode(form.photo.data.read()).decode("utf-8")

            recipes = mongo.db.recipes
            # Add the recipe and tell the user it's added
            recipes.insert_one({
                'recipe_name': request.form['recipe_name'],
                'summary': request.form['summary'],
                'description': request.form['description'],
                'photo': "data:image/png;base64," + code_str,
                'ingredients': request.form['ingredients'],
                'equipment': request.form['equipment'],
                'prep_time': request.form['prep_time'],
                'cook_time': request.form['cook_time'],
                'serves_num': request.form['serves_num'],
                'method': request.form['method'],
                'course': request.form['course'],
                'cuisine': request.form['cuisine'],
                'username': session['username'],
            })
            flash('Recipe added', 'success')
            return redirect(url_for('user_profile'))
        else:
            flash('Please make sure form is filled out correctly', 'danger')
            return redirect(url_for('add_recipe'))
    elif request.method == "GET":
        return render_template('add_recipe.html',
                               form=form,
                               title='Add Recipe')
    else:
        flash('An error occured', 'danger')
        return render_template('index.html')
Example #32
0
def new_recipe():
    form = RecipeForm(request.form)
    if request.method == 'GET':
        return render_template('recipes/new.html', form=form)
    if form.validate():
        # https://stackoverflow.com/questions/33429510/wtforms-selectfield-not-properly-coercing-for-booleans f**k
        if form.status.data == '':
            form.status.data = False
        recipe = Recipe(title=form.title.data,
                        ingredients=form.ingredients.data,
                        time_needed=form.time_needed.data,
                        steps=form.steps.data,
                        status=form.status.data,
                        user_id=current_user.id)
        db.session.add(recipe)
        db.session.commit()
        flash('Recipe added successfully', 'success')
        return redirect(url_for('show_recipe', recipe_id=recipe.id))

    flash('There are some problems here', 'danger')
    return render_template('recipes/new.html', form=form)
Example #33
0
def addrecipe():
    if 'username' not in session:
        flash('Not possible for non-members! Please create an account.')
        return redirect(url_for('register'))

    form = RecipeForm()
    if request.method == 'POST' and form.validate_on_submit():
        recipe = mongo.db.Recipes
        recipe.insert({'recipe_name': request.form['recipe_name'],
                       'recipe_type': request.form['recipe_type'],
                       'recipe_desc': request.form['recipe_desc'],
                       'serving': request.form['serving'],
                       'prep_time': request.form['prep_time'],
                       'cook_time': request.form['cook_time'],
                       'ingredients': request.form.getlist('ingredients'),
                       'method': request.form.getlist('methods'),
                       # Lists for Ingredients and Method to store in an array.
                       'img_url': request.form['img_url']})
        flash('Recipe successfully added.')
        return redirect(url_for('index'))
    return render_template('addrecipe.html', form=form)
Example #34
0
def edit_recipe(recipe_id):
    """Function to edit selected recipe"""
    if 'logged_in' not in session:  # Check if its a logged in user
        flash('Sorry, only logged in users can create recipes.')
        return redirect(url_for('index'))

    user = mongo.db.user.find_one({"name": session['username'].title()})
    the_recipe = mongo.db.recipe.find_one_or_404({'_id': ObjectId(recipe_id)})
    form = RecipeForm()

    if user['name'].title() == the_recipe['username'].title():
        if request.method == 'GET':
            form = RecipeForm(data=the_recipe)
            return render_template('edit_recipe.html',
                                   recipe=the_recipe,
                                   form=form,
                                   title="Edit Recipe")
        if form.validate_on_submit():
            recipe = mongo.db.recipe
            recipe.update_one({
                '_id': ObjectId(recipe_id),
            }, {
                '$set': {
                    'recipe': request.form['recipe_name'],
                    'recipe_name': request.form['recipe_name'],
                    'recipe_image': request.form['recipe_image'],
                    'serving_size': int(request.form['serving_size']),
                    'diet_labels': request.form['diet_labels'],
                    'health_labels': request.form['health_labels'],
                    'ingredients': request.form['ingredients'],
                    'calories': request.form['calories'],
                    'cooking_time': request.form['cooking_time'],
                    'description': request.form['description'],
                    'source': request.form['source']
                }
            })
            flash('Recipe updated.')
            return redirect(url_for('recipe', recipe_id=recipe_id))
    flash("Sorry this is not your recipe to edit!")
    return redirect(url_for('recipe', recipe_id=recipe_id))
Example #35
0
def edit_recipe(request, id):
    recipe = get_object_or_404(Recipe, id=id)
    tag_prepop = Tag.objects.get_for_object(recipe)
    tool_prepop = recipe.tools.all()
    if recipe.user != request.user and request.user.is_superuser == False:
        return render_to_response('recipes/forbidden.html',
                                  context_instance=RequestContext(request))
    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES, instance=recipe)
        formset = RecipeIngredientsFormset(request.POST,
                                           request.FILES,
                                           instance=recipe)
        if form.is_valid():
            recipe = form.save(commit=False)
            if formset.is_valid():
                formset.save()
                recipe.save()
                return render_to_response(
                    'recipes/view_recipe.html', {
                        'recipe': recipe,
                    },
                    context_instance=RequestContext(request))
    else:
        form = RecipeForm(instance=recipe)
        formset = RecipeIngredientsFormset(instance=recipe)
    return render_to_response('recipes/edit_recipe.html', {
        'recipe': recipe,
        'form': form,
        'formset': formset,
        'tag_prepop': tag_prepop,
        'tool_prepop': tool_prepop
    },
                              context_instance=RequestContext(request))
Example #36
0
def recipe(request,user=None, slug=None):
    '''used to create or edit a recipe'''
    IngFormSet = inlineformset_factory(Recipe, Ingredient, extra=15, formset=IngItemFormSet) #create the ingredient form with 15 empty fields

    if user and slug: #must be editing a recipe
        recipe_inst = get_object_or_404(Recipe, author__username=request.user.username, slug=slug)
    else:
        recipe_inst = Recipe()

    if request.method=='POST':
        form = RecipeForm(data = request.POST, files = request.FILES,instance=recipe_inst)
        formset = IngFormSet(request.POST, instance=recipe_inst)
        if form.is_valid() and formset.is_valid():
            new_recipe = form.save()
            instances = formset.save(commit=False)#save the ingredients seperatly
            for instance in instances:
                instance.recipe_id = new_recipe.id #set the recipe id foregin key to the this recipe id
                instance.save()
            form.save(commit=False)
            return redirect(new_recipe.get_absolute_url())
    else:
        form = RecipeForm(instance=recipe_inst)
        form.fields['related'].queryset =  Recipe.objects.filter(author__username=request.user.username).exclude(related = F('id')).filter(related__isnull=True).order_by('-pub_date')[:5]

        if recipe_inst.id:  #if we are editing an existing recipe disable the title field so it can't be changed
            form.fields['title'].widget.attrs['readonly'] = True
        
        formset = IngFormSet(instance=recipe_inst)
    return render_to_response('recipe/recipe_form.html', {'form': form, 'formset' : formset,}, context_instance=RequestContext(request))
Example #37
0
def add_recipe(request):
    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES)
        if form.is_valid():
            recipe = form.save(commit=False)
            recipe.user = request.user
            recipe.save()
            formset = RecipeIngredientsFormset(request.POST,
                                               request.FILES,
                                               instance=recipe)
            if formset.is_valid():
                formset.save()
                recipe.save()
                return render_to_response(
                    'recipes/view_recipe.html', {
                        'recipe': recipe,
                    },
                    context_instance=RequestContext(request))
            else:
                recipe.delete()
        else:
            formset = RecipeIngredientsFormset(request.POST, request.FILES)
    else:
        form = RecipeForm()
        formset = RecipeIngredientsFormset()
    return render_to_response('recipes/add_recipe.html', {
        'form': form,
        'formset': formset
    },
                              context_instance=RequestContext(request))
Example #38
0
def add_recipe(request):
    if request.method == 'POST':
        recipe_form = RecipeForm(request.POST, request.FILES)
        hop_type_form = HopTypeForm(request.POST)
        hop_counter = request.POST.get('hop-counter')
        hop_counter = int(hop_counter) + 1

        if recipe_form.is_valid():
            recipe = recipe_form.save()

            for i in range(hop_counter):
                if i == 0:
                    hop_type_dict = {'hop_type': request.POST.get('hop_type')}
                else:
                    hop_type_dict = {
                        'hop_type': request.POST.get('hop_type_%d' % i)
                    }

                hop_type_form = HopTypeForm(hop_type_dict)
                if hop_type_form.is_valid():
                    hop = hop_type_form.save(commit=False)
                    hop.recipe = recipe
                    hop.save()

            return HttpResponseRedirect('/thanks/')
    else:
        recipe_form = RecipeForm()
        hop_type_form = HopTypeForm()
    return render(request, 'add-recipe.html', {
        'hop_type_form': hop_type_form,
        'recipe_form': recipe_form
    })
Example #39
0
def recipe():
    form = RecipeForm()
    if form.validate_on_submit():

        #retrieve proportion data from form. 1 if (optionally) empty
        amount1 = (int(form.word1.data != "")
                   if form.amount1.data == None else form.amount1.data)
        amount2 = (int(form.word2.data != "")
                   if form.amount2.data == None else form.amount2.data)
        amount3 = (int(form.word3.data != "")
                   if form.amount3.data == None else form.amount3.data)
        amounts = [amount1, amount2, amount3]

        #retrieve word data from form. ""->" " if (optionally) empty
        word1 = (" "
                 if form.word1.data == "" else form.word1.data.strip().lower())
        word2 = (" "
                 if form.word2.data == "" else form.word2.data.strip().lower())
        word3 = (" "
                 if form.word3.data == "" else form.word3.data.strip().lower())
        words = [word1, word2, word3]

        #format and flash the input
        amount1 = int(amount1) if isinstance(
            amount1, float) and amount1.is_integer() else amount1
        amount2 = int(amount2) if isinstance(
            amount2, float) and amount2.is_integer() else amount2
        amount3 = int(amount3) if isinstance(
            amount3, float) and amount3.is_integer() else amount3
        flash(
            '{} {}{:+} {}{:+} {} ~'.format(amount1, word1, amount2, word2,
                                           amount3, word3), 'input')

        #look up synonyms from vector sum
        result = nearest_words(amounts, words)
        for word in result:
            flash(word, 'output')

        return redirect('/')
    return render_template('recipe.html', title='word+chef', form=form)
Example #40
0
def add_recipe(username):
  user = User.query.filter_by(username=username).first()
  form = RecipeForm()
  if form.validate_on_submit():
    name = request.form['name'];
    image = request.form['recipe_image']
    ingredients = request.form['ingredients'].splitlines()
    response = Macro_Api_Caller.get_Data(Macro_Api_Caller, name, ingredients)
    if 'error' in response:
      flash("Ingredients not valid, make sure ingredients are on separate lines.", "danger")
      return redirect(f"/users/{session['username']}/recipes/add")
    else:
      recipe = Recipe_Factory.process_Recipe(name, image, user, response)
      db.session.add(recipe)
      db.session.commit()
      add_Ingredients = [Ingredient(amount=ingredient, recipe_id=recipe.id) for ingredient in ingredients]
      db.session.add_all(add_Ingredients)
      db.session.commit()
      flash("Recipe added successfully!", "success")
      return redirect(f"/users/{user.username}/recipes")
  else: 
    return render_template("/recipes/add_recipe.html", form=form, user=user)
Example #41
0
def add_recipe():
    form = RecipeForm()
    if request.method == 'POST' and form.validate():
        # Add recipe to database and create ingredient links
        recipe = Recipe(name=form.name.data, type=form.type.data,
                        time=form.time.data, category=form.category.data,
                        serves=form.serves.data, method=form.method.data)
        db.session.add(recipe)
        # Create links between recipe and all ingredients required
        for ingredient in session['ingredients']:
            find_ingredient = Ingredient.query.filter_by(name=ingredient[0]).first()
            ing_recipe_link = RI_Link(r_id=recipe.id, i_id=find_ingredient.id,
                                      quantity=ingredient[1], q_type=ingredient[2])
            recipe.ingredients.append(ing_recipe_link)
            find_ingredient.recipes.append(ing_recipe_link)
        # Add calorie value for the recipe
        calories = 0
        for ingredient in session['ingredients']:
            find_ing = Ingredient.query.filter_by(name=ingredient[0]).first()
            if ingredient[2] == 'g':
                calories += int(ingredient[1])*int(find_ing.calories_per_g)
            elif ingredient[2] == 'mL':
                calories += int(ingredient[1])*int(find_ing.calories_per_ml)
            elif ingredient[2] == 'tbs':
                calories += int(ingredient[1])*int(find_ing.calories_per_tbs)
            elif ingredient[2] == 'tsp':
                calories += int(ingredient[1])*int(find_ing.calories_per_tsp)
            elif ingredient[2] == 'each':
                calories += int(ingredient[1])*int(find_ing.calories_per_each)
        recipe.calories = int(calories/(int(recipe.serves)))
        db.session.commit()
        return redirect(url_for('index'))
    session['ingredients'] = []
    session.modified = True
    form = RecipeForm()
    return render_template('add-recipe.html', title= 'Add Recipe', form = form)
Example #42
0
def add(request):
    def storeInS3(recipe_id, filename, content):
        conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
        b = conn.create_bucket(settings.S3BUCKET)
        mime = mimetypes.guess_type(filename)[0]
        k = Key(b)
        k.key = 'recipe_id_'+str(recipe_id) +'_'+filename 
        k.set_metadata("Content_Type", mime)
        content.seek(0)
        k.set_contents_from_file(content)
        k.set_acl("public-read")
        
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES )
        recipeName = request.POST['name']
        if Recipe.objects.filter(name=recipeName).count() > 0:
            messages.add_message(request, messages.ERROR,"The recipe name "+recipeName+" has been taken. Please choose another name for your recipe.")
            return render(request, 'shakeapp/add.html')
        if form.is_valid():
            newRecipe = form.save(commit=False)
            pictureFile = form.cleaned_data['picture']
            newRecipe.picture.save(pictureFile.name, pictureFile)
            filename = pictureFile.name 
            
            storeInS3(newRecipe.id, filename, pictureFile.file)
            newRecipe.url = settings.S3URL+'recipe_id_'+str(newRecipe.id)+"_"+filename
            newRecipe.save()
            return HttpResponseRedirect("/shakeapp/")
        else:
            print
            print form.errors
            messages.add_message(request, messages.ERROR,"There has been an error in the form. Please make sure your inputs are correct.")
            return render(request, 'shakeapp/add.html')
    return render_to_response('shakeapp/add.html',context_instance = RequestContext(request) )