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})