Example #1
0
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)
Example #2
0
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)
Example #3
0
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
    })
Example #4
0
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)
Example #5
0
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})
Example #6
0
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})
Example #7
0
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()})
Example #8
0
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,)))
Example #9
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)
Example #10
0
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
    })
Example #11
0
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')
Example #12
0
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')
Example #13
0
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')
Example #14
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,
        }
    )
Example #15
0
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
        })
Example #16
0
 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
         })
Example #17
0
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)
Example #18
0
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)
Example #19
0
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})
Example #20
0
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})
Example #21
0
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)
Example #22
0
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 new_recipe(request):
    tags = Tag.objects.all()
    if request.method != 'POST':
        form = RecipeForm()
        return render(
            request, 'recipes/new_recipe.html', {'form': form, 'tags': tags}
        )
    form = RecipeForm(request.POST or None, files=request.FILES or None)

    if not form.is_valid():
        return render(
            request,
            'recipes/new_recipe.html',
            {'form': form, 'tags': tags}
        )
    with transaction.atomic():
        recipe = form.save(commit=False)
        recipe.user = request.user
        recipe.save()

        parse_recipe(request.POST, recipe)

    return redirect('detail', pk=recipe.id)
Example #24
0
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})
Example #25
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)
Example #26
0
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)
Example #27
0
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)
Example #28
0
def recipe_edit(request, slug):
    recipe = get_object_or_404(Recipe, slug=slug)
    if request.user.username != recipe.author.username:
        return redirect('recipe_detail', slug=slug)
    form = RecipeForm(
        request.POST or None,
        files=request.FILES or None,
        instance=recipe,
    )
    if not form.is_valid():
        context = {
            'form': form,
            'recipe': recipe,
            'recipe_edit': 'recipe_edit'
        }
        return render(
            request,
            'recipes/recipe_create.html',
            context,
        )
    recipe = form.save(commit=False)
    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('recipe_detail', slug=recipe.slug)
Example #29
0
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)
Example #30
0
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)