Esempio n. 1
0
def editRecipeIngredients(request, recipe):
    """
    Saves the current RecipeIngredients objects for the current recipe.
    """
    recipeIngredients = Recipeingredients.objects.filter(recipe=recipe)

    quantity_str = "quantity"
    ingredient_str = "ingredient"
    
    for x in recipeIngredients:
        i= request.POST.get(ingredient_str + str(x.id)).strip()
        quantity = request.POST.get(quantity_str + str(x.id)).strip()
        if  quantity and i:
            existingIngredient = Ingredient.objects.filter(name=i)
            if not len(existingIngredient) == 0:
                for ingredient in existingIngredient:
                    x.ingredient = ingredient
                    x.quantity = quantity
            else:
                ingredient = Ingredient()
                ingredient.name = i
                ingredient.save()
                x.ingredient = ingredient
                x.quantity = quantity
            x.save()
Esempio n. 2
0
def setRecipeIngredients(request, recipe):
    """
    Saves the current ingredients and quantity for Recipe.
    """
    quantity_str = "quantity"
    ingredient_str = "ingredient"
    
    for x in range(1, 12):
        try:
            i= request.POST.get(ingredient_str + str(x))
            quantity = request.POST.get(quantity_str + str(x))
        
            if  quantity and i:
                ri = Recipeingredients()
                existingIngredient = None
                existingIngredient = Ingredient.objects.filter(name=i)
                if not len(existingIngredient) == 0 :
                    for ingredient in existingIngredient:
                        ri.ingredient = ingredient
                        ri.recipe = recipe
                        ri.quantity = quantity
                        ri.save()
                        
                else:
                    ingredient = Ingredient()
                    ingredient.name = i
                    ingredient.save()
                    ri.ingredient = ingredient
                    ri.recipe = recipe
                    ri.quantity = quantity
                    ri.save()
        except:
            return
Esempio n. 3
0
class RecipeModelTest(TestCase):
    def setUp(self):
        self.lasanha = Recipe(title='lasanha', description='placeholder')
        self.macarrao = Recipe(title='macarrao', description='placeholder')
        self.batata = Ingredient(name='batata')
        self.molho = Ingredient(name='molho')

    def test_recipe_is_saved(self):
        self.lasanha.save()
        self.macarrao.save()
        self.assertEqual('lasanha', Recipe.objects.all()[0].title)

    def test_update_ingredients_method(self):
        self.lasanha.save()
        self.batata.save()
        self.molho.save()
        Measure.objects.create(recipe=self.lasanha,
                               ingredient=self.batata,
                               measure='duas')
        new_ingredients = {'batata': 'uma', 'molho': 'um'}
        new_ingredients2 = {'cenoura': 'uma'}
        self.lasanha.update_ingredients(new_ingredients)
        self.assertEqual(self.lasanha.measure_set.all().count(), 2)
        self.assertEqual(
            self.lasanha.measure_set.get(ingredient=self.batata).measure,
            'uma')
        self.assertEqual(
            self.lasanha.measure_set.get(ingredient=Ingredient.objects.get(
                name='molho')).measure, 'um')
        self.lasanha.update_ingredients(new_ingredients2)
        self.assertEqual(self.lasanha.ingredients.count(), 1)
        self.assertEqual(
            self.lasanha.measure_set.get(ingredient=Ingredient.objects.get(
                name='cenoura')).measure, 'uma')
Esempio n. 4
0
class MeasureRelationTest(TestCase):
    def setUp(self):
        self.lasanha = Recipe(title='lasanha', description='placeholder')
        self.batata = Ingredient(name='batata')

    def test_create_association(self):
        self.lasanha.save()
        self.batata.save()
        Measure(ingredient=self.batata, recipe=self.lasanha,
                measure='1 kilo').save()
        batata_lasanha = Measure.objects.get(ingredient=self.batata,
                                             recipe=self.lasanha)
        self.assertEqual(self.lasanha.ingredients.all()[0].name, 'batata')
        self.assertEqual(batata_lasanha.measure, '1 kilo')

    
    def test_no_double_ingredients(self):
        self.batata.save()
        self.lasanha.save()
        Measure.objects.create(ingredient=self.batata, recipe=self.lasanha, measure='uma')
        try:
            Measure.objects.create(ingredient=self.batata,
                                   recipe=self.lasanha, measure='duas')
        except ValidationError:
            pass
        self.assertEqual(self.lasanha.measure_set.all().count(), 1)
Esempio n. 5
0
class IngredientModelTest(TestCase):
    def setUp(self):
        self.batata = Ingredient(name='batata')
        self.cenoura = Ingredient(name='cenoura')

    def test_ingredient_is_saved(self):
        self.batata.save()
        self.assertEqual(Ingredient.objects.all()[0].name, 'batata')
Esempio n. 6
0
 def setUp(self):
     self.user = User.objects.create(username='******', password='******')
     self.lasanha = Recipe(title='lasanha',
                           description='placeholder',
                           author=self.user)
     self.macarrao = Recipe(title='macarrao',
                            description='placeholder',
                            author=self.user)
     self.batata = Ingredient(name='batata')
     self.molho = Ingredient(name='molho')
 def handle_ingredient(self, recipe, name, amount, ingredientid, grams):
     self.stdout.write(u"\t - ingredient: %s | %s" % (amount, name))
     # Look for food
     ingredient = Ingredient.objects.search(name)
     if not ingredient:
         if self.create_foods:
             ingredient = Ingredient()
             ingredient.NDB_No = self.ingredient_NDB_No_generator()
             ingredient.Shrt_Desc = name
             ingredient.Long_Desc = name
             ingredient.save()
         else:
             raise Exception("Ingredient failed!")
     ing_amount = IngredientWithAmount(Recipe=recipe, Ingredient=ingredient)
     ing_amount.HumanReadable = u"%s %s" % (amount, name)
     ing_amount.GramsEquiv = grams
     # Quantity and Units
     items = amount.split()
     try:
         ing_amount.Quantity = float(
             sum(Fraction(part) for part in items[0].split()))
         if len(items) == 1:
             ing_amount.Units = u"unit"
         else:
             ing_amount.Units = items[-1]
         self.stdout.write(u"\t   + ingredient: %s" %
                           (ingredient.Shrt_Desc))
         self.stdout.write(u"\t   + quantity: %s" % (ing_amount.Quantity))
         self.stdout.write(u"\t   + units: %s" % (ing_amount.Units))
         ing_amount.save()
     except Exception as e:
         self.stderr.write(str(e))
         ingredient.delete()
         raise Exception("Quanty and units not parseable: %r" % amount)
Esempio n. 8
0
class MeasureRelationTest(TestCase):
    def setUp(self):
        self.lasanha = Recipe(title='lasanha', description='placeholder')
        self.batata = Ingredient(name='batata')

    def test_create_association(self):
        self.lasanha.save()
        self.batata.save()
        Measure(ingredient=self.batata, recipe=self.lasanha,
                measure='1 kilo').save()
        batata_lasanha = Measure.objects.get(ingredient=self.batata,
                                             recipe=self.lasanha)
        self.assertEqual(self.lasanha.ingredients.all()[0].name, 'batata')
        self.assertEqual(batata_lasanha.measure, '1 kilo')
Esempio n. 9
0
def _create_recipe(author, name, tag):
    products = [
        Product.objects.create(title=f'testIng{i}', unit=i) for i in range(2)
    ]
    recipe = Recipe(author=author,
                    name=name,
                    description='test test test',
                    cook_time=5)
    recipe.save()
    recipe.tags.add(tag)
    for product in products:
        ingredient = Ingredient(recipe=recipe, ingredient=product, amount=2)
        ingredient.save()
    return recipe
 def handle_ingredient(self, recipe, name, amount, ingredientid, grams):
     self.stdout.write(u"\t - ingredient: %s | %s" % (amount, name))
     # Look for food
     ingredient = Ingredient.objects.search(name)
     if not ingredient:
         if self.create_foods:
             ingredient = Ingredient()
             ingredient.NDB_No = self.ingredient_NDB_No_generator();
             ingredient.Shrt_Desc = name
             ingredient.Long_Desc = name
             ingredient.save()
         else:
             raise Exception("Ingredient failed!")
     ing_amount = IngredientWithAmount(Recipe=recipe, Ingredient=ingredient)
     ing_amount.HumanReadable = u"%s %s" % (amount, name)
     ing_amount.GramsEquiv = grams
     # Quantity and Units
     items = amount.split()
     try:
         ing_amount.Quantity = float(sum(Fraction(part) for part in items[0].split()))
         if len(items) == 1:
             ing_amount.Units = u"unit"
         else:
             ing_amount.Units = items[-1]
         self.stdout.write(u"\t   + ingredient: %s" % (ingredient.Shrt_Desc))
         self.stdout.write(u"\t   + quantity: %s" % (ing_amount.Quantity))
         self.stdout.write(u"\t   + units: %s" % (ing_amount.Units))
         ing_amount.save()
     except Exception as e:
         self.stderr.write(str(e))
         ingredient.delete()
         raise Exception("Quanty and units not parseable: %r" % amount)
Esempio n. 11
0
def create_ingredient(label, order, recipe):
    ingredient = Ingredient()
    ingredient.label = label
    ingredient.order = order
    ingredient.recipe = recipe
    ingredient.save()
    return ingredient
Esempio n. 12
0
class MeasureRelationTest(TestCase):
    def setUp(self):
        self.user = User.objects.create(username='******', password='******')
        self.lasanha = Recipe(title='lasanha',
                              description='placeholder',
                              author=self.user)
        self.batata = Ingredient(name='batata')

    @mock.patch('recipes.models.Recipe.indexing', new=mock_indexing)
    def test_create_association(self):
        self.lasanha.save()
        self.batata.save()
        Measure(ingredient=self.batata, recipe=self.lasanha,
                measure='1 kilo').save()
        batata_lasanha = Measure.objects.get(ingredient=self.batata,
                                             recipe=self.lasanha)
        self.assertEqual(self.lasanha.ingredients.all()[0].name, 'batata')
        self.assertEqual(batata_lasanha.measure, '1 kilo')
Esempio n. 13
0
def get_ingredients_from_form(ingredients, recipe):
    """Получает ингредиенты рецепта из формы и возвращает их списком."""
    ingredients_for_save = []
    for ingredient in ingredients:
        product = Product.objects.get(title=ingredient['title'])
        ingredients_for_save.append(
            Ingredient(recipe=recipe,
                       ingredient=product,
                       amount=ingredient['amount']))
    return ingredients_for_save
Esempio n. 14
0
    def handle(self, *args, **options):
        with open('ingredients.json', 'r', encoding='utf-8') as fh:
            data = json.load(fh)

        for i in data:
            dimension = i['dimension']
            title = i['title']

            if not Ingredient.objects.filter(title=title).exists():
                print(f'Добавляю {title}')
                if dimension in [
                        'по вкусу', 'стакан', 'кусок', 'горсть', 'банка',
                        'тушка', 'пакет'
                ]:
                    dimension = 'г'
                ingredient = Ingredient(title=title, dimension=dimension)
                ingredient.save()

        return '--Ингредиенты добавлены--'
Esempio n. 15
0
    def get_ingredients(self, dry_run=True):
        with connections['newsstand'].cursor() as cursor:
            if not dry_run:
                cursor.execute(
                    'SELECT item, skillline, reagent, quantity, spell FROM newsstand.tblDBCItemReagents'
                )
                columns = [col[0] for col in cursor.description]

                for row in fetchsome(cursor):
                    ingredient = dict(zip(columns, row))

                    try:
                        crafted_item = Item.objects.get(
                            blizzard_id=ingredient['item'])
                        recipe_spell = Recipe.objects.get(
                            blizzard_id=ingredient['spell'])
                    except Item.DoesNotExist:
                        self.stdout.write('Item {} not found'.format(
                            ingredient['spell']))
                        continue
                    except Recipe.DoesNotExist:
                        self.stdout.write('Recipe {} not found'.format(
                            ingredient['spell']))
                        continue

                    try:
                        ingredient_reagent = Item.objects.get(
                            blizzard_id=ingredient['reagent'])
                    except Item.DoesNotExist:
                        self.stdout.write('Reagent {} not found'.format(
                            ingredient['spell']))
                        continue

                    if Ingredient.objects.filter(reagent=ingredient_reagent,
                                                 spell=recipe_spell).exists():
                        continue
                    else:
                        new_ingredient = Ingredient()
                        new_ingredient.item = crafted_item
                        new_ingredient.skillline = ingredient['skillline']
                        new_ingredient.reagent = ingredient_reagent
                        new_ingredient.quantity = ingredient['quantity']
                        new_ingredient.spell = recipe_spell

                        new_ingredient.save()
            else:
                self.stdout.write("Skipping Ingredients")
Esempio n. 16
0
    def add_recipe(self, d):
        r = Recipe(recipe_name=d['title'].encode('utf-8'),
                   directions=d['directions'].encode('utf-8'),
                   serving_size=int(d['serving_size'].encode('utf-8')))
        r.save()

        for i in d['ingredients']:
            Ingredient(recipe=r,
                       ingredient_name=i[0].encode('utf-8'),
                       quantity=float(i[1].encode('utf-8')),
                       units=i[2].encode('utf-8')).save()
Esempio n. 17
0
    def create(self, validated_data):
        categories = validated_data.pop('category')
        ingredients = validated_data.pop('ingredients')
        updated_instance = super(RecipeSerializer, self).create(validated_data)

        for ingredient in ingredients:
            updated_instance.ingredients.append(Ingredient(**ingredient))
        for category in categories:
            updated_instance.category.append(Category(**category))

        updated_instance.save()
        return updated_instance
Esempio n. 18
0
def submit_recipe(request):
    if request.user.is_authenticated:
        d = dict(request.POST.iterlists())
        r = Recipe(recipe_name=d['recipe_name'][0],
                   directions=d['directions'][0],
                   serving_size=int(d['serving_size'][0]))
        r.save()
        print(d)
        if 'ingredient' in d:
            for i in range(len(d['ingredient'])):
                Ingredient(recipe=r,
                           ingredient_name=d['ingredient'][i],
                           units=d['units'][i],
                           quantity=float(d['quantity'][i])).save()

    return HttpResponseRedirect(reverse('recipes:detail', args=[r.id]))
Esempio n. 19
0
 def handle(self, *args, **options):
     if Ingredient.objects.exists():
         print('Aromas data already loaded...exiting.')
         print(ALREDY_LOADED_ERROR_MESSAGE)
         return
     print("Creating Ingredients data")
     for row in DictReader(open('./ingredient_by_id.csv', encoding="utf-8"),
                           delimiter=','):
         ingredient = Ingredient()
         ingredient.entity_id = row['entity_id']
         ingredient.entity_alias_readable = row['entity_alias_readable']
         ingredient.save()
     print("Ingredients data successfully created")
Esempio n. 20
0
def submit_edit(request, recipe_id):
    if request.user.is_authenticated and check_if_steward(request.user):
        recipe = get_object_or_404(Recipe, pk=recipe_id)
        for ingredient in recipe.ingredient_set.all():
            ingredient.delete()
        d = dict(request.POST.iterlists())

        recipe.serving_size = d['serving_size'][0]
        recipe.recipe_name = d['recipe_name'][0]
        recipe.directions = d['directions'][0]
        recipe.save()

        if 'ingredient' in d:
            for i in range(len(d['ingredient'])):
                Ingredient(recipe=recipe,
                           ingredient_name=d['ingredient'][i],
                           units=d['units'][i],
                           quantity=float(d['quantity'][i])).save()

    return HttpResponseRedirect(reverse('recipes:detail', args=[recipe_id]))
Esempio n. 21
0
        def add_ingredients(self, recipe_id):
            ingredients = []

            j = 0
            sections = self.dom.select('.ingredients__section')
            for i, section in enumerate(sections):
                group = section.select('.headline__xsmall__bold')
                if len(group) > 1:
                    raise ImportException('Found too many group headlines')
                if len(group) == 1:
                    group = group[0].string.strip()
                    if group[-1] == ':':
                        group = group[:-1]
                else:
                    group = ''

                items = section.select('[itemprop="recipeIngredient"]')
                for item in items:
                    contents = item.contents
                    while isinstance(contents[0], NavigableString):
                        contents.pop(0)

                    quantity = contents.pop(0).string.strip()

                    rest = [tag.string or ''
                            for tag in contents]  # get strings
                    rest = [text.strip() for text in rest
                            if text.strip()]  # remove empty strings
                    name = ' '.join(rest)
                    j += 1

                    ingredient = Ingredient(quantity=quantity,
                                            name=name,
                                            group=group,
                                            order_item=j,
                                            recipe_id=recipe_id)
                    ingredients.append(ingredient)

            Ingredient.objects.bulk_create(ingredients)
    def test_ingredients(self):
        preset = [
            {
                'title': 'Just an ingredient',
                'dimension': 'g'
            },
            {
                'title': 'Just another ingredient',
                'dimension': 'l'
            },
            {
                'title': 'Whatever ingredient',
                'dimension': 'pc'
            },
        ]
        ingredients = []

        for item in preset:
            ingredients.append(
                Ingredient(title=item['title'], dimension=item['dimension']))

        Ingredient.objects.bulk_create(ingredients)
        response = self.client.get(reverse('api:ingredients-list'))

        with self.subTest():
            self.assertEqual(response.json(), preset)

        queries = {
            '': preset,
            'word': [],
            'ju': preset[:2],
            'ver': preset[2:],
            'ingredient': preset,
        }
        for query, fetch in queries.items():
            with self.subTest():
                response = self.client.get(
                    reverse('api:ingredients-list') + f'?query={query}')
                self.assertEqual(response.json(), fetch)
Esempio n. 23
0
def upload_ingedients(csv_file='ingredients.csv'):
    '''Заливаем данные из файла ingredients.csv в Таблицу Ingredient
       Делим строку по символу ','. Присваиваем сзначения полям таблицы
       name и units соответственно.Если после запятой пустая строка - ставим 'г'.Можете поменять это поведение.
       Загружаем все данные в одном запросе методом bulk_create.
    '''
    old_data = Ingredient.objects.all()
    old_data.delete()
    data = csv.reader(open(csv_file, encoding='utf-8'), delimiter=',')
    try:
        obj_list = [
            Ingredient(
                id=id,
                name=row[0],
                measurement_unit='г' if row[1] == '' else row[1],
            ) for id, row in enumerate(data)
        ]
    except (IndexError):
        return 'IndexError'

    Ingredient.objects.bulk_create(obj_list)

    return 'ok'
Esempio n. 24
0
 def mutate(root, info, name, notes, category_id):
     category = IngredientCategory.objects.get(id=category_id)
     igi = Ingredient(name=name, notes=notes, category=category)
     ok = True
     igi.save()
     return CreateIngredient(ingredient=igi, ok=ok)
Esempio n. 25
0
 def test_inserting_into_db(self):
     """it should insert into the database"""
     ingredient = Ingredient(name='test', amount=1)
     ingredient.save()
     assert Ingredient.objects.filter(name='test').count() == 1
    def handle_recipe(self, data, url):
        if Recipe.objects.filter(URL=url).exists():
            self.stdout.write(u"\t   already in database")
            return 1, False

        recipe = Recipe(Title=data[u"name"], URL=url)
        self.stdout.write(u"\t - author: %s" % data.get(u"author", None))
        recipe.Author = data.get(u"author", None)
        self.stdout.write(u"\t - image: %s" % data.get(u"image", None))
        recipe.Image = data.get(u"image", None)
        self.stdout.write(u"\t - ratingValue: %s" %
                          data.get(u"ratingValue", None))
        recipe.Rating = data.get(u"ratingValue", None)
        self.stdout.write(u"\t - description: %s" %
                          data.get(u"description", '')[:60])
        recipe.Description = data.get(u"description", None)

        # Produces
        self.stdout.write(u"\t - Produces: %s" % data[u"name"])
        ingredient = Ingredient.objects.search(data[u"name"])
        if not ingredient:
            if self.create_foods:
                ingredient = Ingredient()
                ingredient.NDB_No = self.ingredient_NDB_No_generator()
                ingredient.Shrt_Desc = data[u"name"]
                ingredient.Long_Desc = data[u"name"]
                ingredient.save()
            else:
                return None, False
        recipe.Produces = ingredient

        # Yields
        self.stdout.write(u"\t - yields: %s" % data.get(u"yields", None))
        yields = data.get(u"yields", None)
        if yields:
            items = [it for it in yields.split() if it.isdigit()]
            if items:
                recipe.Yields = items[0]
            self.stdout.write(u"\t   + yields: %s -> %s" %
                              (yields, recipe.Yields))

        # PrepTime and CookTime
        def minutes(value_str):
            if value_str:
                t = parse_duration(value_str)
                return int(t.seconds / 60.)
            return None

        self.stdout.write(u"\t - prepTime: %s" %
                          minutes(data.get(u"prepTime", None)))
        self.stdout.write(u"\t - cookTime: %s" %
                          minutes(data.get(u"cookTime", None)))
        recipe.PrepTime = minutes(data.get(u"prepTime", None))
        recipe.CookTime = minutes(data.get(u"cookTime", None))

        recipe.save()

        # Ingredients
        try:
            for name, amount, ingredientid, grams in zip(
                    data[u"ingredients-name"], data[u"ingredients-amount"],
                    data["ingredients-data-ingredientid"],
                    data[u"ingredients-data-grams"]):
                self.handle_ingredient(recipe, name, amount, ingredientid,
                                       grams)
        except Exception as e:
            self.stderr.write(str(e))
            recipe.delete(
            )  # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos
            return None, False

        #Directions
        try:
            i = 1
            self.stdout.write(u"\t - directions:")
            for direction in data.get(u"directions"):
                d = Direction(Recipe=recipe, StepNumber=i)
                d.Description = direction
                d.save()
                self.stdout.write(u"\t   + %s" % d)
                i += 1
        except Exception as e:
            self.stderr.write(str(e))
            recipe.delete(
            )  # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos
            return None, False

        return recipe, True
Esempio n. 27
0
 def handle(self, *args, **options):
     i = Ingredient(name=' '.join(options['name']), type=options['type'])
     i.full_clean()
     i.save()
     self.stdout.write(str(i.pk))
Esempio n. 28
0
 def setUp(self):
     self.batata = Ingredient(name='batata')
     self.cenoura = Ingredient(name='cenoura')
Esempio n. 29
0
from django.contrib.auth import get_user_model
from recipes.models import Recipe, Comment, Like, Ingredient, Complaint
from django.utils import timezone
from datetime import datetime, date, time

UserModel = get_user_model()

for i in range(100):
    k = str(i)

    

    recipe = Recipe(title = 'title'+k ,text = 'text' + k, preview ='preview' + k)
    recipe.author = UserModel.objects.get(pk = 1)
    recipe.save()

    ingredient = Ingredient (ingredient_name = 'ingredient' + k)
    ingredient.dish = Recipe.objects.get(pk = i+1)
    ingredient.save()

    comment = Comment(creator=)

    def handle_recipe(self, data, url):
        if Recipe.objects.filter(URL=url).exists():
            self.stdout.write(u"\t   already in database")
            return 1, False 

        recipe = Recipe(Title=data[u"name"], URL=url)
        self.stdout.write(u"\t - author: %s" % data.get(u"author", None))
        recipe.Author = data.get(u"author", None)
        self.stdout.write(u"\t - image: %s" % data.get(u"image", None))
        recipe.Image = data.get(u"image", None)
        self.stdout.write(u"\t - ratingValue: %s" % data.get(u"ratingValue", None))
        recipe.Rating = data.get(u"ratingValue", None)
        self.stdout.write(u"\t - description: %s" % data.get(u"description", '')[:60])
        recipe.Description = data.get(u"description", None)


        # Produces
        self.stdout.write(u"\t - Produces: %s" % data[u"name"])
        ingredient = Ingredient.objects.search(data[u"name"])
        if not ingredient:
            if self.create_foods:
                ingredient = Ingredient()
                ingredient.NDB_No = self.ingredient_NDB_No_generator();
                ingredient.Shrt_Desc = data[u"name"]
                ingredient.Long_Desc = data[u"name"]
                ingredient.save()
            else:
                return None, False
        recipe.Produces = ingredient

        # Yields
        self.stdout.write(u"\t - yields: %s" % data.get(u"yields", None))
        yields = data.get(u"yields", None)
        if yields:
            items = [it for it in yields.split() if it.isdigit()]
            if items:
                recipe.Yields = items[0]
            self.stdout.write(u"\t   + yields: %s -> %s" % (yields, recipe.Yields))

        # PrepTime and CookTime
        def minutes(value_str):
            if value_str:
                t = parse_duration(value_str)
                return int(t.seconds/60.)
            return None
        self.stdout.write(u"\t - prepTime: %s" % minutes(data.get(u"prepTime", None)))
        self.stdout.write(u"\t - cookTime: %s" % minutes(data.get(u"cookTime", None)))
        recipe.PrepTime = minutes(data.get(u"prepTime", None))
        recipe.CookTime = minutes(data.get(u"cookTime", None))

        recipe.save()

        # Ingredients
        try:
            for name, amount, ingredientid, grams in zip(data[u"ingredients-name"], data[u"ingredients-amount"], data["ingredients-data-ingredientid"], data[u"ingredients-data-grams"]):
                self.handle_ingredient(recipe, name, amount, ingredientid, grams)
        except Exception as e:
            self.stderr.write(str(e))
            recipe.delete() # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos
            return None, False

        #Directions
        try:
            i = 1
            self.stdout.write(u"\t - directions:")
            for direction in data.get(u"directions"):
                d = Direction(Recipe=recipe, StepNumber=i)
                d.Description = direction
                d.save()
                self.stdout.write(u"\t   + %s" % d)
                i += 1
        except Exception as e:
            self.stderr.write(str(e))
            recipe.delete() # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos
            return None, False

        return recipe, True
Esempio n. 31
0
 def setUp(self):
     self.lasanha = Recipe(title='lasanha', description='placeholder')
     self.macarrao = Recipe(title='macarrao', description='placeholder')
     self.batata = Ingredient(name='batata')
     self.molho = Ingredient(name='molho')
Esempio n. 32
0
import os
from collections import defaultdict

import django

os.environ['DJANGO_SETTINGS_MODULE'] = 'foodgram.settings'
django.setup()

from recipes.models import Tag, Ingredient

if __name__ == '__main__':
    classes = globals().keys()

    path = os.path.dirname(__file__)
    path = os.path.join(path, 'front', 'static', 'ingredients.json')
    with open(path, 'rb') as file:
        data = json.load(file)
        # Словарь для избежания дублей
        ingredients = defaultdict()
        for ingredient in data:
            key = tuple([value for value in ingredient.values()])
            ingredients[key] = Ingredient(**ingredient)

    Ingredient.objects.bulk_create(ingredients.values())

    Tag(title='Завтрак', color='orange').save()
    Tag(title='Обед', color='green').save()
    Tag(title='Ужин', color='purple').save()

    print('Данные загружены')
Esempio n. 33
0
 def post(self, request, pk):
     f = get_object_or_404(Recipe, id=pk)
     ingredient = Ingredient(name = request.POST['ingredient'], measurement=request.POST['measurement'], owner=request.user, recipe=f)
     ingredient.save()
     return redirect(reverse('recipes:recipe_update', args=[pk]))
import csv
from recipes.models import Ingredient, Tag

with open('./recipes/ingredients.csv', newline='', encoding='utf-8') as File:
    reader = csv.reader(File)
    for row in reader:
        ingred = Ingredient(title=row[0], dimension=row[1])
        ingred.save()
#test

tags = ['B', 'L', 'D']
for tag in tags:
    new_tag = Tag(tag_name=tag)
    new_tag.save()