def update(request, recipe): IngredientFormSet = inlineformset_factory(Recipe, Ingredient, extra=0, form=IngredientForm) RecipeStepFormSet = inlineformset_factory(Recipe, RecipeStep, extra=0, form=RecipeStepForm) recipe = get_object_or_404(Recipe, pk=recipe) if request.method == 'POST': recipe_form = RecipeForm(request.POST, request.FILES, prefix='recipe', instance=recipe) ingredient_formset = IngredientFormSet(request.POST, prefix='ingredients', instance=recipe) recipe_step_formset = RecipeStepFormSet(request.POST, prefix='recipe_steps', instance=recipe) if recipe_form.is_valid() and ingredient_formset.is_valid() and \ recipe_step_formset.is_valid(): recipe_form.save() ingredient_formset.save() recipe_step_formset.save() return HttpResponseRedirect(reverse('home')) else: recipe_form = RecipeForm(instance=recipe, prefix='recipe') ingredient_formset = IngredientFormSet(instance=recipe, prefix='ingredients') recipe_step_formset = RecipeStepFormSet(instance=recipe, prefix='recipe_steps') return render(request, 'add.html', { 'form_action': reverse('recipe-update', args=[recipe.id]), 'recipe_form': recipe_form, 'ingredient_formset': ingredient_formset, 'recipe_step_formset': recipe_step_formset, })
def recipe_edit(request, recipe_id, slug): recipe = get_object_or_404(Recipe, id=recipe_id) # ing = recipe.ingredients.all() # вытащить ингрединеты и передать их а отдельную переменную и распечать ее в шаблоне # ing = Ingredient.objects.filter(recipe=recipe).all() if not request.user.is_superuser: if request.user != recipe.author: return redirect('recipe_view_slug', recipe_id=recipe.id, slug=recipe.slug) form = RecipeForm(request.POST or None, files=request.FILES or None, instance=recipe) if form.is_valid(): try: recipe = edit_recipe(request, form, instance=recipe) except forms.ValidationError as e: return render( request, 'formRecipe.html', { 'form': form, # 'ing': ing, 'errortext': str(e) }) return redirect('recipe_view_slug', recipe_id=recipe.id, slug=recipe.slug) return render( request, 'formRecipe.html', { 'form': form, 'recipe': recipe, # 'ing': ing })
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, } )
def add(request): '''Adds a Recipe This view follows the create/update pattern for CRUD forms. A GET request returns an empty recipe form, ingredient formset, and recipe_step formset. A valid post creates the recipe object, builds the step and ingredient objects from their respective formsets, and adds the foreign keys references to the recipe. If the forms are not all valid, the function returns attached references to all the forms/formsets. Finally, a GET request with a valid recipe pk will return an attached form/formset for updating the recipe. Args: request: the standard django.http.HttpRequest for all views Returns: django.http.HttpResponse with a context containing a recipe_form, ingredient_formset and recipe_step_formset, or a redirect to the list of recipes Raises: django.http.Http404: recipe_id was given, but not a valid Recipe object ''' IngredientFormSet = inlineformset_factory(Recipe,Ingredient,extra=1, form=IngredientForm) RecipeStepFormSet = inlineformset_factory(Recipe,RecipeStep,extra=1, form=RecipeStepForm) if request.method == 'POST': recipe_form = RecipeForm(request.POST, request.FILES, prefix='recipe') ingredient_formset = IngredientFormSet(request.POST, prefix='ingredients') recipe_step_formset = RecipeStepFormSet(request.POST, prefix='recipe_steps') if recipe_form.is_valid() and ingredient_formset.is_valid()\ and recipe_step_formset.is_valid(): recipe_id = recipe_form.save(commit=False) recipe_id.added_by = request.user recipe_id.save() ingredients = ingredient_formset.save(commit=False) for ingredient in ingredients: ingredient.recipe = recipe_id ingredient.save() recipe_steps = recipe_step_formset.save(commit=False) for recipe_step in recipe_steps: recipe_step.recipe = recipe_id recipe_step.save() return HttpResponseRedirect(reverse('home')) else: recipe_form = RecipeForm(prefix='recipe') ingredient_formset = IngredientFormSet(prefix='ingredients') recipe_step_formset = RecipeStepFormSet(prefix='recipe_steps') return render(request, 'add.html', { 'form_action': reverse('recipe-new'), 'recipe_form' : recipe_form, 'ingredient_formset' : ingredient_formset, 'recipe_step_formset' : recipe_step_formset, })
def create(request): if request.method == 'GET': recipe_form = RecipeForm() context = { 'recipe_form': recipe_form, } return render(request, 'create.html', context) else: recipe_form = RecipeForm(request.POST) if recipe_form.is_valid(): title = recipe_form.cleaned_data['title'] image_url = recipe_form.cleaned_data['image_url'] description = recipe_form.cleaned_data['description'] ingredients = recipe_form.cleaned_data['ingredients'] time = recipe_form.cleaned_data['time'] recipe = Recipe( title=title, image_url=image_url, description=description, ingredients=ingredients, time=time, ) recipe.save() return redirect('homepage') context = { 'recipe_form': recipe_form, } return render(request, 'create.html', context)
def test_form_validation_for_blank_items(self): form = RecipeForm(data={'title': ''}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors['title'], ['This field is required.'] )
def add_or_update_recipe(request): current_recipe = None if request.method == 'POST' and not 'recipe_id' in request.POST: recipe_form = RecipeForm(request.POST) if recipe_form.is_valid(): # getting recipe object from form recipe_obj = recipe_form.save(commit=False) recipe_obj.user = request.user recipe_obj.save() # save many to many fields recipe_form.save_m2m() return redirect('recipes:recipe-manage', recipe_slug=recipe_obj.slug) else: recipe_id = request.POST.get('recipe_id', '') # check if user wants to update or create if recipe_id == "": recipe_form = RecipeForm() else: current_recipe = Recipe.objects.get(id=recipe_id) recipe_form = RecipeForm(instance=current_recipe) return render(request, 'recipes/user/add_recipe.html', { 'recipe_form': recipe_form, 'recipe': current_recipe })
def add(request): if request.method == 'POST': form = RecipeForm(user=request.user, data=request.POST) if form.is_valid(): recipe=form.save() return HttpResponseRedirect(recipe.get_absolute_url()) else: form = RecipeForm() return render(request, 'recipes/form.html', {'form': form, 'add': True})
def recipe_edit_view(request, recipe_id): """Страница редактирования рецепта.""" recipe = get_object_or_404(Recipe, id=recipe_id) if request.user != recipe.author: return redirect('recipe_view', recipe_id=recipe_id) if request.method == 'POST': form = RecipeForm(request.POST or None, files=request.FILES or None, instance=recipe) if form.is_valid(): recipe.ingredients.remove() recipe.recipe_amount.all().delete() recipe = form.save(commit=False) recipe.author = request.user ingredients = form.cleaned_data['ingredients'] form.cleaned_data['ingredients'] = [] form.save() Ingredient.objects.bulk_create( get_ingredients_from_form(ingredients, recipe)) return redirect('recipe_view', recipe_id=recipe_id) form = RecipeForm(instance=recipe) context = { 'recipe_id': recipe_id, 'page_title': 'Редактирование рецепта', 'button': 'Сохранить', 'form': form, 'recipe': recipe } return render(request, 'recipes/formRecipe.html', context)
def recipe_new(request): form = RecipeForm(request.POST or None, files=request.FILES or None) if form.is_valid(): form.instance.author = request.user recipe = form.save() return redirect('recipe_view_slug', recipe_id=recipe.id, slug=recipe.slug) return render(request, 'recipes/formRecipe.html', {'form': form})
def recipe_add(request): if request.method == "POST": form = RecipeForm(request.POST) if form.is_valid(): ingredient = Ingredient(name=form.cleaned_data["ingredient"]) ingredient.save() recipegroup = RecipeGroup(main_ingredient=ingredient) recipegroup.save() return HttpResponseRedirect(reverse("recipe_info", args=(recipegroup.id,))) else: form = RecipeForm() return render_to_response("recipes/recipe_add.html", {"form": form}, context_instance=RequestContext(request))
def add_post(request): context = RequestContext(request) if request.method == 'POST': form = RecipeForm(request.POST, request.FILES) if form.is_valid(): check = form.save(commit=True) return redirect('recipes.views.post', post_url=check.name.replace(' ', '_')) else: print form.errors else: form = RecipeForm() return render_to_response('recipes/add_post.html', {'form': form}, context)
def recipe_new(request): form = RecipeForm(request.POST or None, files=request.FILES or None) if form.is_valid(): recipe = save_recipe(request, form) return redirect('recipe_view_slug', recipe_id=recipe.id, slug=recipe.slug) context = {'form': form} return render(request, 'recipes/form_recipe.html', context)
def recipe_create(request): captcha_public_key=settings.RECAPTCHA_PUBLIC_KEY form=RecipeForm(request.POST or None) if form.is_valid(): recipe=form.save(commit=False) recipe.approved=False recipe.slug=slugify(recipe.title) recipe.save() return redirect('recipes-submitted') return render_to_response('recipes/recipe_create.html', locals(), context_instance=RequestContext(request))
def edit(request, recipe_id): recipe = get_object_or_404(Recipe, pk=recipe_id) if recipe.author != request.user and not request.user.is_staff: return HttpResponseForbidden() if request.method == 'POST': form = RecipeForm(instance=recipe, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(recipe.get_absolute_url()) else: form = RecipeForm(instance=recipe) return render(request, 'recipes/form.html', {'form': form, 'add': False, 'object': recipe})
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)
def recipe_create(request): captcha_public_key = settings.RECAPTCHA_PUBLIC_KEY form = RecipeForm(request.POST or None) if form.is_valid(): recipe = form.save(commit=False) recipe.approved = False recipe.slug = slugify(recipe.title) recipe.save() return redirect('recipes-submitted') return render_to_response('recipes/recipe_create.html', locals(), context_instance=RequestContext(request))
def ListView(request): ''' Lists food query results ''' if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): data = form.cleaned_data name = data["name"] foods = get_food_recipe(name) return render(request, 'recipes/list.html', {'food_list': foods}) form = RecipeForm() return HttpResponseRedirect(reverse('recipes:index', args=(form,)))
def addrecipe(request): if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): data = form.cleaned_data r = Recipe() r.name = data['name'] r.servings = data['servings'] r.ingredients = data['ingredients'] r.instructions = data['instructions'] r.save() return redirect(recipe_list) else: form = RecipeForm() return render(request, 'addrecipe.html', {'form': form})
def recipe_new(request): form = RecipeForm(request.POST or None, files=request.FILES or None) if form.is_valid(): try: recipe = save_recipe(request, form) except forms.ValidationError as e: return render(request, 'formRecipe.html', { 'form': form, 'errortext': str(e) }) return redirect('recipe_view_slug', recipe_id=recipe.id, slug=recipe.slug) return render(request, 'formRecipe.html', {'form': form})
def recipe_form_data(self, title, description, source_url, img_url): return RecipeForm( data={ 'title': title, 'description': description, 'source_url': source_url, 'img_url': img_url })
def create(request): form = RecipeForm(request.POST or None) if form.is_valid(): recipe = form.save(commit=False) recipe.creator = request.user recipe.start_date = None recipe.save() request.user.message_set.create(message='Your recipe was added') if 'next' in request.POST: next = request.POST['next'] else: next = reverse('recipe_latest') return HttpResponseRedirect(next) return render_to_response( 'recipes/create.html', {'form':form}, context_instance = RequestContext(request) )
def edit(request): """Create a form that can be used to add a new recipe. Save data submitted through the form to the database as a new recipe. """ if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): data = form.cleaned_data r = Recipe() r.name = data['name'] r.servings = data['servings'] r.ingredients = data['ingredients'] r.instructions = data['instructions'] r.save() return redirect(recipe_list) else: form = RecipeForm() return render(request, 'edit.html', { 'form': form})
def makeRecipe(request): #if(not request.user.is_authenticated()): # messages.error(request, 'You must be logged in to make a recipe.') # return redirect('login') form = RecipeForm(request.POST, request.FILES) if form.is_valid(): form.save() form = RecipeForm() return render(request, 'recipes/makeRecipe.html', {'form': form})
def recipe_edit(request, recipe_id): """Изменяет рецепт""" recipe = get_object_or_404(Recipe, id=recipe_id) ing = Amount.objects.filter(recipe=recipe_id) form = RecipeForm(request.POST or None, files=request.FILES or None, instance=recipe) context = {'form': form, 'recipe': recipe, 'ingredients': ing} if recipe.author == request.user: if request.method == 'POST': ingredients = get_ingredients(request.POST) if form.is_valid(): ing.delete() recipe_form_save(form, ingredients, request) return redirect('recipe_view', recipe_id) return render(request, 'formChangeRecipe.html', context) else: return redirect('recipe_view', recipe_id)
def add_recipe(request): if request.method == "POST": form = RecipeForm(request.POST, request.FILES) if form.is_valid(): new_recipe = form.save(commit=False) new_recipe.user = request.user formset = IngredientFormSet(request.POST, instance=new_recipe) if formset.is_valid(): new_recipe.save() formset.save() print "hi" return redirect('recipes.views.recipe', slug=new_recipe.slug) else: form = RecipeForm() formset = IngredientFormSet(instance=Recipe()) return render(request, "recipes/add_recipe.html", {"form": form, "formset": formset})
def addrecipe(request): """Create a form that can be used to add a new recipe. Save data submitted through the form to the database as a new recipe. """ if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): data = form.cleaned_data r = Recipe() r.name = data['name'] r.servings = data['servings'] r.description = data['description'] r.ingredients = data['ingredients'] r.instructions = data['instructions'] r.save() return redirect(recipe_list) else: form = RecipeForm() return render(request, 'addrecipe.html', {'form': form})
def recipe_edit(request, recipe_id, slug): recipe = get_object_or_404(Recipe, id=recipe_id) if not request.user.is_superuser: if request.user != recipe.author: return redirect('recipe_view_slug', recipe_id=recipe.id, slug=recipe.slug) form = RecipeForm(request.POST or None, files=request.FILES or None, instance=recipe) if form.is_valid(): edit_recipe(request, form, instance=recipe) return redirect('recipe_view_slug', recipe_id=recipe.id, slug=recipe.slug) context = {'form': form, 'recipe': recipe} return render(request, 'recipes/form_recipe.html', context)
def edit(request, pk): recipe = Recipe.objects.get(pk=pk) if request.method == 'GET': context = { 'recipe': recipe, } return render(request, 'edit.html', context) else: recipe_form = RecipeForm(request.POST) if recipe_form.is_valid(): recipe.title = recipe_form.cleaned_data['title'] recipe.image_url = recipe_form.cleaned_data['image_url'] recipe.description = recipe_form.cleaned_data['description'] recipe.ingredients = recipe_form.cleaned_data['ingredients'] recipe.time = recipe_form.cleaned_data['time'] recipe.save() return redirect('homepage') context = { 'recipe_form': recipe_form, } return render(request, 'create.html', context)
def new_recipe(request): form = RecipeForm(request.POST or None, files=request.FILES or None) ingredients = get_ingredients(request) if not form.is_valid(): return render( request, 'formRecipe.html', { 'form': form, 'is_new': True, 'page_title': 'Создание рецепта' }, ) recipe = form.save(commit=False) recipe.user = request.user recipe.save() RecipeIngredient.objects.filter(recipe=recipe).delete() objs = [] for title, count in ingredients.items(): ingredient = get_object_or_404(Ingredient, title=title) objs.append( RecipeIngredient(recipe=recipe, ingredient=ingredient, count=count)) RecipeIngredient.objects.bulk_create(objs) form.save_m2m() return redirect('index')
def recipe_edit(request, id): purchases_counter = ShoppingList.objects.filter(user=request.user).count() recipe_base = get_object_or_404(Recipe, pk=id) form = RecipeForm(request.POST or None, files=request.FILES or None, instance=recipe_base) ingredients = get_ingredients(request) if not form.is_valid(): return render( request, 'EditRecipe.html', { 'form': form, 'is_new': True, 'recipe': recipe_base, 'page_title': 'Редактирование рецепта', 'purchases_counter': purchases_counter }, ) recipe = form.save(commit=False) recipe.user = request.user recipe.save() RecipeIngredient.objects.filter(recipe=recipe).delete() objs = [] for title, count in ingredients.items(): ingredient = get_object_or_404(Ingredient, title=title) objs.append( RecipeIngredient(recipe=recipe, ingredient=ingredient, count=count)) RecipeIngredient.objects.bulk_create(objs) form.save_m2m() return redirect('index')
def edit_recipe(request, slug): recipe = get_object_or_404(Recipe, slug=slug) ingredients = RecipeIngredient.objects.filter(recipe=recipe) my_shopping_list = ShoppingList.objects.filter(user=request.user) if request.method == 'POST': RecipeIngredient.objects.filter(recipe=recipe).delete() recipe_form = RecipeForm( request.POST, request.FILES, username=request.user, instance=recipe, ) if recipe_form.is_valid(): recipe_form.save() return redirect('index') else: form = RecipeForm(username=request.user, instance=recipe) context = { 'form': form, 'recipe': recipe, 'ingredients': ingredients, 'shopping_list_ids': my_shopping_list, } return render(request, 'edit_recipe.html', context)
def recipe_create(request): form = RecipeForm(request.POST or None, files=request.FILES or None) if not form.is_valid(): context = { 'form': form, 'is_new': True, } return render(request, 'recipes/recipe_create.html', context) recipe = form.save(commit=False) recipe.author = request.user RecipeIngredient.objects.filter(recipe=recipe).delete() objs = [] ingredients = get_ingredients(request) if ingredients: for title, count in ingredients.items(): ingredient = get_object_or_404(Ingredient, title=title) objs.append( RecipeIngredient(recipe=recipe, ingredient=ingredient, count=count)) else: context = { 'form': form, 'error': 'error', } return render(request, 'recipes/recipe_create.html', context) recipe.save() RecipeIngredient.objects.bulk_create(objs) form.save_m2m() return redirect('index')
def add(request): IngredientFormSet = inlineformset_factory(Recipe, Ingredient, extra=1, form=IngredientForm) RecipeStepFormSet = inlineformset_factory(Recipe, RecipeStep, extra=1, form=RecipeStepForm) if request.method == 'POST': recipe_form = RecipeForm(request.POST, request.FILES, prefix='recipe') ingredient_formset = IngredientFormSet(request.POST, prefix='ingredients') recipe_step_formset = RecipeStepFormSet(request.POST, prefix='recipe_steps') if recipe_form.is_valid() and ingredient_formset.is_valid() \ and recipe_step_formset.is_valid(): recipe_id = recipe_form.save(commit=False) recipe_id.added_by = request.user recipe_id.save() ingredients = ingredient_formset.save(commit=False) for ingredient in ingredients: ingredient.recipe = recipe_id ingredient.save() recipe_steps = recipe_step_formset.save(commit=False) for recipe_step in recipe_steps: recipe_step.recipe = recipe_id recipe_step.save() return HttpResponseRedirect(reverse('home')) else: recipe_form = RecipeForm(prefix='recipe') ingredient_formset = IngredientFormSet(prefix='ingredients') recipe_step_formset = RecipeStepFormSet(prefix='recipe_steps') return render(request, 'add.html', { 'form_action': reverse('recipe-new'), 'recipe_form': recipe_form, 'ingredient_formset': ingredient_formset, 'recipe_step_formset': recipe_step_formset, })
def add(request): if request.method == 'POST': form = RecipeForm(user=request.user, data=request.POST) if form.is_valid(): recipe = form.save() return HttpResponseRedirect(recipe.get_absolute_url()) else: form = RecipeForm() return render(request, 'recipes/form.html', {'form': form, 'add': True})
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)
def edit_recipe(request, pk): recipe = get_object_or_404(Recipe, id=pk) author = recipe.user if request.user != author: return redirect('detail', pk) form = RecipeForm( request.POST or None, files=request.FILES or None, instance=recipe ) tags = Tag.objects.all() if not form.is_valid(): return render( request, 'recipes/edit_recipe.html', {'form': form, 'recipe': recipe, 'tags': tags, 'edit_mode': True} ) with transaction.atomic(): form.save() RecipeIngredient.objects.filter(recipe=recipe).delete() parse_recipe(request.POST, recipe) return redirect('detail', pk=recipe.id)
def recipe_update(request, recipe_id): try: recipe = Recipe.objects.get(id=recipe_id) except Recipe.DoesNotExist: raise Http404("Recipe does not exist") form = RecipeForm(request.POST, instance=recipe) if form.is_valid(): obj = form.save(commit=False) obj.save() form.save_m2m() return redirect('recipes:recipe-manage', recipe_slug=recipe.slug)
def edit(request, recipe_id): recipe = get_object_or_404(Recipe, pk=recipe_id) if recipe.author != request.user and not request.user.is_staff: return HttpResponseForbidden() if request.method == 'POST': form = RecipeForm(instance=recipe, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(recipe.get_absolute_url()) else: form = RecipeForm(instance=recipe) return render(request, 'recipes/form.html', { 'form': form, 'add': False, 'object': recipe })
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()})
def new_recipe_view(request): """Создание нового рецепта.""" form = RecipeForm(request.POST or None, files=request.FILES or None) if form.is_valid(): recipe = form.save(commit=False) recipe.author = request.user ingredients = form.cleaned_data['ingredients'] form.cleaned_data['ingredients'] = [] form.save() Ingredient.objects.bulk_create( get_ingredients_from_form(ingredients, recipe)) return redirect('index_view') context = { 'page_title': 'Создание рецепта', 'button': 'Создать рецепт', 'form': form, } return render(request, 'recipes/formRecipe.html', context)
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 })
def create_recipe(request): if request.method == 'POST': recipe_form = RecipeForm(request.POST, request.FILES, username=request.user) if recipe_form.is_valid(): recipe_form.save() return redirect('index') else: form = RecipeForm(username=request.user) user = request.user shopping_list_ids = (ShoppingList.objects.filter(user=user).values_list( 'recipe', flat=True)) context = { 'form': form, 'shopping_list_ids': shopping_list_ids, } return render(request, 'create_recipe.html', context=context)
def test_form_renders_recipe_text_input(self): form = RecipeForm() self.assertIn('placeholder="Enter the title of the recipe"', form.as_p()) self.assertIn('class="form-control"', form.as_p())