コード例 #1
0
def new_recipe(request):
    form = RecipeForm(request.POST or None, files=request.FILES or None)
    ingredients = get_form_ingredients(request)
    if form.is_valid() and ingredients:
        recipe = form.save(commit=False)
        recipe.author = request.user
        form.save()
        passed_tags = request.POST.getlist('tags')
        for tag_id in passed_tags:
            tag = get_object_or_404(Tag, id=tag_id)
            recipe.tags.add(tag)

        for ing_id, values in ingredients.items():
            title, amount, units = values
            ingredient = Ingredient.objects.get_or_create(
                title=title, dimension=units)[0]
            new_ingredient = IngredientAmount.objects.get_or_create(
                ingredient=ingredient,
                amount=amount)[0]
            recipe.ingredients.add(new_ingredient)
        form.save_m2m()
        return redirect('index')
    if request.method == 'POST' and not ingredients:
        form.add_error(None, 'Обязательное поле.')
    return render(
        request,
        template_name='formRecipe.html',
        context={
            'form': form,
        }
    )
コード例 #2
0
def add_recipe(request):
    """
    tags is dictionary with tag as key and bool as value
    first save recipe for make recipe_id
    then tags and ingredients
    """

    form = RecipeForm(request.POST or None, files=request.FILES or None)
    tag_list = ('breakfast', 'lunch', 'dinner')
    context = {'form': form}

    if request.method == 'POST':
        tags = [tag for tag in tag_list if tag in form.data]
        ingrs_and_amount = parse_ingredients_from_form(form.data)
        if not tags:
            form.add_error(None, 'Нужен хотя бы один тэг')
        if not ingrs_and_amount:
            form.add_error(None, 'Нужен хотя бы один ингредиент. Лучше два.')
        if form.is_valid() and tags and ingrs_and_amount:
            recipe = form.save(commit=False)
            recipe.author = request.user
            recipe.save()
            recipe.tags.add(*tags)
            for ingr in ingrs_and_amount:
                IngredientsInRecipe.objects.create(recipe=recipe, **ingr)

            return redirect('recipe', recipe.id, recipe.slug)

        context['ingredients'] = ingrs_and_amount

    return render(request, 'recipes/recipe_form.html', context)
コード例 #3
0
ファイル: views.py プロジェクト: Fr33vvay/foodgram-project
def new_recipe(request):
    """Создаёт новый рецепт"""
    if request.method == 'POST':
        form = RecipeForm(request.POST or None, files=request.FILES or None)
        ingredients = get_ingredients(request.POST)
        if not ingredients:
            form.add_error(None, 'Добавьте ингредиенты из выпадающего списка')
        if form.is_valid():
            recipe_form_save(form, ingredients, request)
            return redirect('index')
        else:
            return render(request, 'formRecipe.html', {'form': form})
    return render(request, 'formRecipe.html', {'form': RecipeForm()})
コード例 #4
0
def edit_recipe(request, recipe_id=None, the_slug=None):
    """
    Tags is dictionary with tag as key and bool as value.
    Check permission and then make form from recipe, and
    ingredients from query set to append to form.
    If form contains any data, then for correct update,
    must delete old data.
    When update recipe, then update recipe.slug.
    """
    user = request.user
    recipe = get_object_or_404(Recipe, id=recipe_id)
    if not (user.is_staff or user == recipe.author):
        return HttpResponseForbidden

    tag_list = ('breakfast', 'lunch', 'dinner')
    form = RecipeForm(request.POST or None,
                      files=request.FILES or None,
                      instance=recipe)
    instance_ingredients = recipe.ingredients.all()

    if request.method == 'POST':
        tags = [tag for tag in tag_list if tag in form.data]
        ingrs_and_amount = parse_ingredients_from_form(form.data)
        if not tags:
            form.add_error(None, 'Нужен хотя бы один тэг')
        if not ingrs_and_amount:
            form.add_error(None, 'Нужен хотя бы один ингредиент. Лучше два.')
        if form.is_valid() and tags and ingrs_and_amount:
            recipe = form.save(commit=False)
            recipe.update_slug()
            recipe.save()
            recipe.tags.clear()
            recipe.tags.add(*tags)
            for ingr in instance_ingredients:
                ingr.delete()
            for ingr in ingrs_and_amount:
                IngredientsInRecipe.objects.create(recipe=recipe, **ingr)

            return redirect('recipe', recipe.id, recipe.slug)

    context = {
        'form': form,
        'recipe': recipe,
        'ingredients': instance_ingredients
    }
    return render(request, 'recipes/recipe_form.html', context)
コード例 #5
0
def change_recipe(request, recipe_id):
    recipe = get_object_or_404(Recipe, id=recipe_id)
    user = request.user
    author = recipe.author
    if user != author:
        return redirect('recipe_view', recipe_id=recipe_id)
    form = RecipeForm(
        request.POST or None,
        files=request.FILES or None,
        instance=recipe
    )
    ingredients = get_form_ingredients(request)
    if form.is_valid():
        form.save()
        recipe.ingredients.clear()
        for ing_id, values in ingredients.items():
            title, *specifications = values
            if specifications:
                ingredient = Ingredient.objects.get_or_create(
                    title=title, dimension=specifications[1])[0]
                new_ingredient = IngredientAmount.objects.get_or_create(
                    ingredient=ingredient, amount=specifications[0])[0]
            else:
                new_ingredient = IngredientAmount.objects.get_or_create(
                    id=ing_id)[0]
            recipe.ingredients.add(new_ingredient)

        return redirect('recipe_view', recipe_id=recipe_id)

    if request.method == 'POST' and not ingredients:
        form.add_error(None, 'Обязательное поле.')
    recipe_tags = recipe.tags.all()
    ingredients = recipe.ingredients.all()
    return render(request, 'formChangeRecipe.html', {
        'form': form,
        'recipe': recipe,
        'ingredients': ingredients,
        'recipe_tags': recipe_tags
    })