Esempio n. 1
0
def edit_recipe(request, pk):
    recipe = get_object_or_404(Recipe, pk=pk)
    recipe_form = RecipeForm(request.POST or None, instance=recipe)

    ingredient = Ingredient.objects.filter(recipe=recipe)
    IngredientFormSet = formset_factory(IngredientForm, extra=5)
    ingredient_formset = IngredientFormSet(request.POST or None)

    if recipe_form.is_valid() and ingredient_formset.is_valid():
        recipe = recipe_form.save(commit=False)
        recipe.author = request.user
        recipe.save()

        for ingredient_form in ingredient_formset:
            ingredient = ingredient_form.save(commit=False)
            ingredient.recipe = recipe
            ingredient.save()

        return redirect('recipe:detail', pk=pk)

    context = {
        "recipe_form": recipe_form,
        "ingredient_formset": ingredient_formset,
    }
    return render(request, 'recipe/add_recipe.html', context)
Esempio n. 2
0
def recipe_create(request):
    """ Cоздание нового рецепта. """

    active_create = True
    form = RecipeForm(
        request.POST or None,
        files=request.FILES or None,
        initial={"request": request},
    )
    context = {}
    if is_negative_weight(request):
        context["ingredient_value_message"] = INGREDIENT_VALUE_ERROR
    elif form.is_valid():
        form.save()
        return redirect("index")

    context.update({
        "name": "name",
        "form": form,
        "description": "description",
        "cook_time": "cook_time",
        "picture": "picture",
        "active_create": active_create,
    })
    return render(request, "recipe/recipe_action.html", context)
Esempio n. 3
0
def add(request):
    form = RecipeForm()
    if request.method == 'POST':
        form = RecipeForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('recipe_home')
    return render(request, 'kitchen/add.html', {'form': form, 'subject': 'recept'})
Esempio n. 4
0
 def post(self, request, *args, **kwargs):
     user = request.user
     data = request.POST.dict()
     data['user'] = user.id
     form = RecipeForm(data=data, files=request.FILES)
     if form.is_valid():
         return self.form_valid(form)
     else:
         return self.form_invalid(form)
Esempio n. 5
0
def newrecipes(request):
    newrecipe = RecipeForm()
    if request.method == 'POST':
        newrecipe = RecipeForm(request.POST)
        if newrecipe.is_valid():
            nt=newrecipe.save()
            nt.user=request.user
            nt.save()
            return HttpResponseRedirect('/sharerecipes')
    categories = Category.objects.all().order_by("name")
    return render(request, "newrecipes.html",{"newrecipes": newrecipe, "categories": categories})
Esempio n. 6
0
def recipe_create(request):
	"""
	Page for create a new recipe
	"""    
	AmountFormSet = formset_factory(AmountForm, extra = 3)
	StepFormSet = formset_factory(StepForm, extra = 3)
	if request.method == 'POST':
		recipe_form = RecipeForm(request.POST)
		amount_formset = AmountFormSet(request.POST, prefix='amount')
		step_formset = StepFormSet(request.POST, prefix='step')
		if recipe_form.is_valid() and amount_formset.is_valid() and step_formset.is_valid():
			r = recipe_form.save()
			step = 1
			for form in step_formset:
				des = ''
				if 'description' in form.cleaned_data:
					des = form.cleaned_data['description']
				else:
					continue
				s = Step(recipe = r, step_num = step, description = des)
				s.step_image = form.cleaned_data['step_image'];
				s.save()
				step = step + 1

			unactive = get_object_or_404(FoodCategory, pk = 1)
			for form in amount_formset:
				if 'ingredient' in form.cleaned_data:
					f, created = Food.objects.get_or_create(name = form.cleaned_data['ingredient'], defaults={'category': unactive})
					a = Amount(ingredient = f, recipe = r, amount = form.cleaned_data['amount'], must = form.cleaned_data['must'])
					a.save()
				else:
					continue

			return redirect(r)

	else:
		recipe_form = RecipeForm(initial={'author': request.user.id})
		amount_formset = AmountFormSet(prefix='amount')
		step_formset = StepFormSet(prefix='step')
		food_name = Food.objects.all().only('name')

		return render(request, 'recipe/recipe_form.html',{
			'recipe_form': recipe_form,
			'amount_formset': amount_formset,
			'step_formset': step_formset,
			'Courses': RecipeCategory.objects.filter(parent__name='Courses').only('name'),
			'Cuisines': RecipeCategory.objects.filter(parent__name='Cuisines').only('name'),
			'Main_Ingredients': RecipeCategory.objects.filter(parent__name='Main Ingredients').only('name'),
			'Special_Diets': RecipeCategory.objects.filter(parent__name='Special Diets').only('name'),
			'food_name_list': food_name,
		})
Esempio n. 7
0
def new_recipe(request):
    form = RecipeForm(request.POST or None, files=request.FILES or None)
    if form.is_valid():
        recipe = save_form_m2m(request, form)

        return redirect("single", slug=recipe.slug)

    return render(
        request,
        "recipe/recipe_form.html",
        {
            "form": form,
        },
    )
Esempio n. 8
0
def recipe_edit(request, recipe_id):
    recipe = get_object_or_404(Recipe, id=recipe_id)

    if request.user != recipe.author:
        return redirect('index')

    if request.method == "POST":
        form = RecipeForm(request.POST or None,
                          files=request.FILES or None, instance=recipe)
        ingredients = get_ingredients(request)
        if form.is_valid():
            RecipeIngredient.objects.filter(recipe=recipe).delete()
            recipe = form.save(commit=False)
            recipe.author = request.user
            recipe.save()
            for item in ingredients:
                RecipeIngredient.objects.create(
                    units=ingredients[item],
                    ingredient=Ingredients.objects.get(name=f'{item}'),
                    recipe=recipe)
            form.save_m2m()
            return redirect('index')

    form = RecipeForm(request.POST or None,
                      files=request.FILES or None, instance=recipe)

    return render(request, 'recipe_edit.html',
                  {'form': form, 'recipe': recipe, })
Esempio n. 9
0
def addrecipe(request):
    args = {}
    args.update(csrf(request))
    args['form'] = RecipeForm()
    if auth.get_user(request).is_authenticated():
        args['user'] = auth.get_user(request)
        if request.POST:
            form = RecipeForm(request.POST)
            if form.is_valid():
                recipe = form.save(commit=False)
                recipe.author = args['user']
                form.save()
                return redirect('/recipes/' + str(recipe.id))
            args['form'] = form
    else:
        return redirect('/auth/login/')
    return render_to_response('addrecipe.html', args, context_instance=RequestContext(request))
Esempio n. 10
0
def edit_recipe(request, slug):
    recipe = get_object_or_404(Recipe, slug=slug)
    url = reverse("single", kwargs={"slug": slug})
    if recipe.author != request.user:
        return redirect(url)
    form = RecipeForm(request.POST or None,
                      files=request.FILES or None,
                      instance=recipe)
    if form.is_valid():
        recipe.amounts.all().delete()  # clean ingredients before m2m saving
        save_form_m2m(request, form)
        return redirect(url)
    used_ingredients = recipe.amounts.all()
    edit = True

    return render(request, "recipe/recipe_form.html", {
        "form": form,
        "used_ingredients": used_ingredients,
        "edit": edit,
    })
Esempio n. 11
0
def recipe_edit(request, id):
    """ Редактирование рецепта """
    recipe = get_object_or_404(Recipe, id=id)
    if request.user == recipe.author:
        if request.method == 'POST':
            form = RecipeForm(
                {
                    'name': request.POST['name'],
                    'text': request.POST['description'],
                    'time': request.POST['time'],
                    'tag_y': on_to_True(request.POST.get('dinner')),
                    'tag_o': on_to_True(request.POST.get('lunch')),
                    'tag_z': on_to_True(request.POST.get('breakfast'))
                },
                request.FILES or None,
                instance=recipe)
            if form.is_valid():
                recipe = form.save(commit=False)
                recipe.author = request.user
                try:
                    recipe.picture = request.FILES['file']
                except Exception:
                    pass
                recipe.save()
                ingridient_adder(request, recipe, False)
                return redirect(f'/recipe/{recipe.id}')
            else:
                return render(request, 'formRecipe.html', {'form': form})

        else:
            form = RecipeForm(instance=recipe)
            return render(request, 'formRecipe edit.html', {'recipe': recipe})
    else:
        raise Http404()
Esempio n. 12
0
def recipe_edit(request, recipe_id):
    """
    Редактирование рецепта
    """
    recipe = get_object_or_404(Recipe, id=recipe_id)
    if request.user != recipe.author:
        return redirect('recipe', recipe_id=recipe.id)
    recipe_form = RecipeForm(request.POST or None,
                             files=request.FILES or None,
                             instance=recipe)
    ingredients = get_ingredients_from_js(request)
    if recipe_form.is_valid():
        RecipeIngredient.objects.filter(recipe=recipe).delete()
        recipe = recipe_form.save(commit=False)
        recipe.author = request.user
        recipe.save()
        recipe.quantities.all().delete()
        for title, quantity in ingredients.items():
            ingredient = get_object_or_404(Ingredient, title=title)
            recipe_ingredient = RecipeIngredient(quantity=quantity,
                                                 ingredient=ingredient,
                                                 recipe=recipe)
            recipe_ingredient.save()
        recipe_form.save_m2m()
        return redirect('index')
    return render(request, 'recipe_change_form.html', {
        'form': recipe_form,
        'recipe': recipe,
    })
Esempio n. 13
0
def add_recipe(request):
    IngredientFormSet = formset_factory(IngredientForm, extra=5)

    if request.method == 'POST':
        recipe_form = RecipeForm(request.POST, request.FILES)
        ingredient_formset = IngredientFormSet(request.POST)

        if recipe_form.is_valid() and ingredient_formset.is_valid():
            recipe = recipe_form.save(commit=False)
            recipe.author = request.user
            recipe.save()

            for ingredient_form in ingredient_formset:
                ingredient = ingredient_form.save(commit=False)
                ingredient.recipe = recipe
                ingredient.save()

            return redirect('recipe:list')

    else:
        recipe_form = RecipeForm()
        ingredient_formset = IngredientFormSet()

    context = {
        "recipe_form": recipe_form,
        "ingredient_formset": ingredient_formset,
    }
    return render(request, 'recipe/add_recipe.html', context=context)
Esempio n. 14
0
def newrecipe(request):
    if request.method == 'GET':
        return render(request, 'formRecipe.html')
    else:
        form = RecipeForm(
            {
                'name': request.POST['name'],
                'text': request.POST['description'],
                'time': request.POST['time'],
                'tag_y': on_to_True(request.POST.get('dinner')),
                'tag_o': on_to_True(request.POST.get('lunch')),
                'tag_z': on_to_True(request.POST.get('breakfast'))
            }, request.FILES or None)
        if 'valueIngredient_1' not in request.POST:
            return render(request, 'formRecipe.html', {
                'form': form,
                "msg": 'Добавте ингридиенты'
            })
        if form.is_valid():
            if form.cleaned_data['tag_y'] == False and form.cleaned_data[
                    'tag_z'] == False and form.cleaned_data['tag_o'] == False:
                return render(request, 'formRecipe.html', {
                    'form': form,
                    "msg2": 'Добавте хотябы один тег'
                })
            recipe = form.save(commit=False)
            recipe.author = request.user
            try:
                recipe.picture = request.FILES['file']
            except Exception:
                pass
            recipe.save()
            ingridient_adder(request, recipe, True)
            return redirect('index')
        return render(
            request,
            'formRecipe.html',
            {'form': form},
        )
Esempio n. 15
0
def add(request):
    form = RecipeForm()
    if request.method == 'POST':
        form = RecipeForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('recipe_home')
    return render(request, 'kitchen/add.html', {
        'form': form,
        'subject': 'recept'
    })
Esempio n. 16
0
def create_recipe(request):
    if request.method == 'GET':
        form = RecipeForm(label_suffix='')
        return render(request, 'recipe/create.html', {'form': form})
    elif request.method == 'POST':
        form = RecipeForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect('homepage')

        return render(request, 'recipe/create.html', {'form': form})
Esempio n. 17
0
def recipe_edit(request, recipe_id):
    """Cтраница редактирования рецепта."""

    recipe = get_object_or_404(Recipe, id=recipe_id)
    form = RecipeForm(
        request.POST or None,
        files=request.FILES or None,
        instance=recipe,
        initial={"request": request},
    )
    data = {}
    if is_negative_weight(request):
        data["ingredient_value_message"] = INGREDIENT_VALUE_ERROR
    elif form.is_valid():
            RecipeIngredient.objects.filter(recipe=recipe).delete()
            form.save()
            return redirect("index")
    data["form"] = form
    data["recipe"] = recipe

    return render(
        request, "recipe/recipe_action.html", data
    )
Esempio n. 18
0
def updaterecipe(request, pk):
    recipe = Recipe.objects.get(id=pk)
    form = RecipeForm(instance=recipe)
    context = {}
    context['form'] = form

    if request.method == 'POST':
        form = RecipeForm(instance=recipe, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('listrecipe')

    return render(request, 'recipeupdate.html', context)
Esempio n. 19
0
def new_recipe(request):
    user = User.objects.get(username=request.user)
    if request.method == 'POST':
        form = RecipeForm(request.POST or None, files=request.FILES or None)
        ingredients = get_ingredients(request)
        if not ingredients:
            form.add_error(None, 'Добавьте ингредиенты')
        elif form.is_valid():
            recipe = form.save(commit=False)
            recipe.author = user
            recipe.save()
            for ing_name, amount in ingredients.items():
                ingredient = get_object_or_404(Ingredients, title=ing_name)
                recipe_ing = RecipeIngredient(
                    recipe=recipe,
                    ingredient=ingredient,
                    amount=amount
                )
                recipe_ing.save()
            form.save_m2m()
            return redirect('index')
    else:
        form = RecipeForm()
    return render(request, 'new_recipe.html', {'form': form})
Esempio n. 20
0
def newrecipes(request):
    newrecipe = RecipeForm()
    if request.method == 'POST':
        newrecipe = RecipeForm(request.POST)
        if newrecipe.is_valid():
            nt = newrecipe.save()
            nt.user = request.user
            nt.save()
            return HttpResponseRedirect('/sharerecipes')
    categories = Category.objects.all().order_by("name")
    return render(request, "newrecipes.html", {
        "newrecipes": newrecipe,
        "categories": categories
    })
Esempio n. 21
0
def createRecipe(request):
    print("inside create recipe")
    template_name = "createrecipe.html"

    context = {}
    context['form'] = RecipeForm()

    if request.method == 'POST':
        form = RecipeForm(request.POST)
        if form.is_valid():
            print("inside is valid")
            form.save()
            # recipe_name = form.cleaned_data.get('recipe_name')# ingredients = form.cleaned_data.get('ingredients')# category = form.cleaned_data.get('category')# obj = Recipe(recipe_name = recipe_name,#              ingredients = ingredients,  #              category    = category)# obj.save()

            return redirect("listrecipe")
        else:
            context['form'] = form
            return render(request, template_name, context)

    return render(request, template_name, context)
Esempio n. 22
0
def edit_recipe(request, recipe_id):
    recipe = get_object_or_404(Recipe, pk=recipe_id)

    if request.method == 'GET':
        form = RecipeForm(label_suffix='', instance=recipe)
        context = {
            'form': form,
            'recipe_id': recipe.id
        }
        return render(request, 'recipe/edit.html', context)

    elif request.method == 'POST':
        form = RecipeForm(request.POST, instance=recipe)

        if form.is_valid():
            form.save()
            return redirect('homepage')

        context = {
            'form': form,
            'recipe_id': recipe.id
        }

        return render(request, 'recipe/edit.html', context)
Esempio n. 23
0
def recipe_new(request):
    """
    Создание рецепта
    """
    author = get_object_or_404(User, username=request.user)
    recipe_form = RecipeForm(request.POST or None, files=request.FILES or None)
    ingredients = get_ingredients_from_js(request)
    if recipe_form.is_valid():
        recipe = recipe_form.save(commit=False)
        recipe.author = author
        recipe.save()
        for title, quantity in ingredients.items():
            ingredient = get_object_or_404(Ingredient, title=title)
            recipe_ingredient = RecipeIngredient(quantity=quantity,
                                                 ingredient=ingredient,
                                                 recipe=recipe)
            recipe_ingredient.save()
        recipe_form.save_m2m()
        return redirect('index')
    return render(request, 'recipe_form.html', {
        'form': recipe_form,
    })
Esempio n. 24
0
def recipe_edit(request, pk):
	"""
	Page for edit a recipe
	"""    
	recipe = get_object_or_404(Recipe, pk = pk)
	if request.user != recipe.author:
		raise Http404
	AmountFormSet = formset_factory(AmountForm, extra = 1)
	StepFormSet = formset_factory(StepForm, extra = 1)
	if request.method == 'POST':
		recipe_form = RecipeForm(request.POST, instance = recipe)
		amount_formset = AmountFormSet(request.POST, prefix='amount')
		step_formset = StepFormSet(request.POST, prefix='step')
		if recipe_form.is_valid() and amount_formset.is_valid() and step_formset.is_valid():
			r = recipe_form.save()
			
			# Process step
			step = 1
			for form in step_formset:
				des = ''
				if 'description' in form.cleaned_data:
					des = form.cleaned_data['description']
				else:
					continue
				s, created = Step.objects.get_or_create(recipe = r, step_num= step, defaults={'description': des})
				s.description = des
				s.step_image = form.cleaned_data['step_image'];
				s.save()
				step = step + 1

			# Process amount
			unactive = get_object_or_404(FoodCategory, pk = 1)
			for form in amount_formset:
				if 'ingredient' in form.cleaned_data:
					f, created = Food.objects.get_or_create(name = form.cleaned_data['ingredient'], defaults={'category': unactive})
					a, created = Amount.objects.get_or_create(ingredient = f, recipe = r, defaults={'amount':form.cleaned_data['amount'], 'must':form.cleaned_data['must']})
					a.amount = form.cleaned_data['amount']
					a.must = form.cleaned_data['must']
					a.save()
				else:
					continue

			return redirect(r)


	else:
		""" Give initial data """
		recipe_form = RecipeForm(instance = recipe)

		amount = recipe.amount_set.all()
		initial_amount = []
		for a in amount:
			initial_amount.append({	'ingredient':a.ingredient,
									'amount': a.amount,
									'must': a.must,
									})

		step = recipe.step_set.all()
		initial_step = []
		for s in step:
			u = ''
			if s.step_image:
				u = s.step_image.url
			initial_step.append({	'description':s.description,
									'step_image':u
									})

		amount_formset = AmountFormSet(initial = initial_amount ,prefix='amount')
		step_formset = StepFormSet(initial = initial_step, prefix='step')
		food_name = Food.objects.all().only('name')

		return render(request, 'recipe/recipe_form.html',{
			'recipe_form': recipe_form,
			'amount_formset': amount_formset,
			'step_formset': step_formset,
			'Courses': RecipeCategory.objects.filter(parent__name='Courses').only('name'),
			'Cuisines': RecipeCategory.objects.filter(parent__name='Cuisines').only('name'),
			'Main_Ingredients': RecipeCategory.objects.filter(parent__name='Main Ingredients').only('name'),
			'Special_Diets': RecipeCategory.objects.filter(parent__name='Special Diets').only('name'),
			'category_list': recipe.category.all().only('name'),
			'food_name_list': food_name,
			})
Esempio n. 25
0
def recipe_edit(request, pk):
    """
	Page for edit a recipe
	"""
    recipe = get_object_or_404(Recipe, pk=pk)
    if request.user != recipe.author:
        raise Http404
    AmountFormSet = formset_factory(AmountForm, extra=1)
    StepFormSet = formset_factory(StepForm, extra=1)
    if request.method == 'POST':
        recipe_form = RecipeForm(request.POST, instance=recipe)
        amount_formset = AmountFormSet(request.POST, prefix='amount')
        step_formset = StepFormSet(request.POST, prefix='step')
        if recipe_form.is_valid() and amount_formset.is_valid(
        ) and step_formset.is_valid():
            r = recipe_form.save()

            # Process step
            step = 1
            for form in step_formset:
                des = ''
                if 'description' in form.cleaned_data:
                    des = form.cleaned_data['description']
                else:
                    continue
                s, created = Step.objects.get_or_create(
                    recipe=r, step_num=step, defaults={'description': des})
                s.description = des
                s.step_image = form.cleaned_data['step_image']
                s.save()
                step = step + 1

            # Process amount
            unactive = get_object_or_404(FoodCategory, pk=1)
            for form in amount_formset:
                if 'ingredient' in form.cleaned_data:
                    f, created = Food.objects.get_or_create(
                        name=form.cleaned_data['ingredient'],
                        defaults={'category': unactive})
                    a, created = Amount.objects.get_or_create(
                        ingredient=f,
                        recipe=r,
                        defaults={
                            'amount': form.cleaned_data['amount'],
                            'must': form.cleaned_data['must']
                        })
                    a.amount = form.cleaned_data['amount']
                    a.must = form.cleaned_data['must']
                    a.save()
                else:
                    continue

            return redirect(r)

    else:
        """ Give initial data """
        recipe_form = RecipeForm(instance=recipe)

        amount = recipe.amount_set.all()
        initial_amount = []
        for a in amount:
            initial_amount.append({
                'ingredient': a.ingredient,
                'amount': a.amount,
                'must': a.must,
            })

        step = recipe.step_set.all()
        initial_step = []
        for s in step:
            u = ''
            if s.step_image:
                u = s.step_image.url
            initial_step.append({
                'description': s.description,
                'step_image': u
            })

        amount_formset = AmountFormSet(initial=initial_amount, prefix='amount')
        step_formset = StepFormSet(initial=initial_step, prefix='step')
        food_name = Food.objects.all().only('name')

        return render(
            request, 'recipe/recipe_form.html', {
                'recipe_form':
                recipe_form,
                'amount_formset':
                amount_formset,
                'step_formset':
                step_formset,
                'Courses':
                RecipeCategory.objects.filter(
                    parent__name='Courses').only('name'),
                'Cuisines':
                RecipeCategory.objects.filter(
                    parent__name='Cuisines').only('name'),
                'Main_Ingredients':
                RecipeCategory.objects.filter(
                    parent__name='Main Ingredients').only('name'),
                'Special_Diets':
                RecipeCategory.objects.filter(
                    parent__name='Special Diets').only('name'),
                'category_list':
                recipe.category.all().only('name'),
                'food_name_list':
                food_name,
            })
Esempio n. 26
0
def recipe_create(request):
    """
	Page for create a new recipe
	"""
    AmountFormSet = formset_factory(AmountForm, extra=3)
    StepFormSet = formset_factory(StepForm, extra=3)
    if request.method == 'POST':
        recipe_form = RecipeForm(request.POST)
        amount_formset = AmountFormSet(request.POST, prefix='amount')
        step_formset = StepFormSet(request.POST, prefix='step')
        if recipe_form.is_valid() and amount_formset.is_valid(
        ) and step_formset.is_valid():
            r = recipe_form.save()
            step = 1
            for form in step_formset:
                des = ''
                if 'description' in form.cleaned_data:
                    des = form.cleaned_data['description']
                else:
                    continue
                s = Step(recipe=r, step_num=step, description=des)
                s.step_image = form.cleaned_data['step_image']
                s.save()
                step = step + 1

            unactive = get_object_or_404(FoodCategory, pk=1)
            for form in amount_formset:
                if 'ingredient' in form.cleaned_data:
                    f, created = Food.objects.get_or_create(
                        name=form.cleaned_data['ingredient'],
                        defaults={'category': unactive})
                    a = Amount(ingredient=f,
                               recipe=r,
                               amount=form.cleaned_data['amount'],
                               must=form.cleaned_data['must'])
                    a.save()
                else:
                    continue

            return redirect(r)

    else:
        recipe_form = RecipeForm(initial={'author': request.user.id})
        amount_formset = AmountFormSet(prefix='amount')
        step_formset = StepFormSet(prefix='step')
        food_name = Food.objects.all().only('name')

        return render(
            request, 'recipe/recipe_form.html', {
                'recipe_form':
                recipe_form,
                'amount_formset':
                amount_formset,
                'step_formset':
                step_formset,
                'Courses':
                RecipeCategory.objects.filter(
                    parent__name='Courses').only('name'),
                'Cuisines':
                RecipeCategory.objects.filter(
                    parent__name='Cuisines').only('name'),
                'Main_Ingredients':
                RecipeCategory.objects.filter(
                    parent__name='Main Ingredients').only('name'),
                'Special_Diets':
                RecipeCategory.objects.filter(
                    parent__name='Special Diets').only('name'),
                'food_name_list':
                food_name,
            })
Esempio n. 27
0
def get_recipe(request):
    '''This function calls the yummly API and retrieves recipe data'''
    client = Client(api_id='3d16b896',
                    api_key='ad2bc866586798e1e659e988442cafb3')
    if request.method == 'POST':
        form = RecipeForm(request.POST) # pylint: disable=E1120
        #print form.errors
        if form.is_valid(): # pylint: disable=E1101
            recipe_name = request.POST.get('q', "")
            allowed_ingredients = request.POST.get('AllowedIngredients', "")
            excluded_ingredients = request.POST.get('ExcludedIngredients', "")
            allowed_cuisine = request.POST.get('allowedCuisine', "")
            allowed_course = request.POST.get('allowedCourse', "")
            options = {
                'q': recipe_name,
                'start': 0,
                'maxResult': 5,
                'requirePicutres': True,
                'allowedIngredient[]': [allowed_ingredients],
                'excludedIngredient[]': [excluded_ingredients],
                'allowedCuisine[]': [allowed_cuisine],
                'allowedCourse[]' : [allowed_course],
                'maxTotalTimeInSeconds': 3600,
                'facetField[]': ['ingredient', 'diet'],
                'flavor.sweet.min': 0,
                'flavor.sweet.max': 0.5,
                'nutrition.FAT.min': 0,
                'nutrition.FAT.max': 15
                }
            results2 = client.search(**options) # pylint: disable=W0142
            for match in results2.matches: #displaying 5 options in the terminal
                print 'Recipe ID:', match.id
                print 'Recipe:', match.recipeName
                print 'Rating:', match.rating
                for i in match.ingredients:
                    print 'Ingredients:', i
            match = results2.matches[0]
            match1 = results2.matches[1]
            recipe = client.recipe(match.id) #1st recipe
            recipe1 = client.recipe(match1.id) #2nd recipe
            print recipe
            response_dict = {}
            response_dict.update({'id': recipe.id})
            response_dict.update({'name': recipe.name})
            response_dict.update({'totalTime': recipe.totalTime})
            response_dict.update({'Ingredients': recipe.ingredientLines})
            response_dict.update({'url':  recipe.attribution.url})
            response_dict.update({'Rating': recipe.rating})
            response_dict.update({'id1': recipe1.id})
            response_dict.update({'name1': recipe1.name})
            response_dict.update({'totalTime1': recipe1.totalTime})
            response_dict.update({'Ingredients1': recipe1.ingredientLines})
            response_dict.update({'url1':  recipe1.attribution.url})
            response_dict.update({'Rating1': recipe1.rating})
            return HttpResponse(json.dumps(response_dict),
                                content_type='application/javascript')
        else:
            return HttpResponse("not valid form")
    else:
        form_recipe = RecipeForm() # pylint: disable=E1120
    ctx = {'form': form_recipe}
    return render_to_response('recipe_form.html',
                              ctx,
                              context_instance=RequestContext(request),
                             )