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 save(self): user = self.cleaned_data["user"] r = Recipe( title=self.cleaned_data["title"], ingredients_text=self.cleaned_data["ingredients_text"], instructions_text=self.cleaned_data["instructions_text"], user=user, quantity_text=self.cleaned_data["quantity_text"], ) r.approved = user.is_staff r.save() # for each tag, get it and add it to the recipe, creating a new one if # it doesn't exist if self.cleaned_data["tags"]: tags = [ Tag.objects.get_or_create( name_slug=slugify(tag), defaults={"name": tag.strip()} )[0] for tag in self.cleaned_data["tags"].split(",") ] usertags = [ UserTag(recipe=r, user=self.cleaned_data["user"], tag=tag) for tag in tags ] UserTag.objects.bulk_create(usertags) return r
def setUp(self): self.user = User.objects.create(username='******') self.client.force_login(self.user) self.another_user = User.objects.create(username='******') self.users = User.objects.all() tags = [ Tag(title='Завтрак', slug='breakfast'), Tag(title='Обед', slug='lunch'), Tag(title='Ужин', slug='dinner'), ] Tag.objects.bulk_create(tags) self.tags = Tag.objects.all() self.fd, self.path = tempfile.mkstemp(suffix='.jpg') Image.new("RGB", (1, 1), "#000").save(self.path) self.recipe_kwargs = { 'author': self.user, 'image': self.path, 'title': 'Just some title', 'description': 'Just some description', 'cooking_time_minutes': 60 } self.recipe = Recipe.objects.create(**self.recipe_kwargs) recipes = [] for q in range(29): self.recipe_kwargs.update( {'author': self.users[q % len(self.users)]}) recipes.append(Recipe(**self.recipe_kwargs)) Recipe.objects.bulk_create(recipes) for index, recipe in enumerate(Recipe.objects.all()): recipe.tags.set([self.tags[index % len(self.tags)]])
def test_create_recipe(self): """ Can create a recipe.""" recipes_carbonara = { 'name': 'Spaghetti Carbonara', 'duration': 35, 'short_description': 'Carbonara with fresh cream', 'content': """ 1. Put pasta on cooking 2. Thinly slice the onions and made them cook in pan" 3. Put slice of bacon" 4. Prepare the fresh cream, eggs, salt, pepper in a bowl and mix." 5. When pasta is ready integrate them to the cream""", } new_recipe = Recipe(**recipes_carbonara) new_recipe.save() RecipeIngredientRel.objects.create( ingredient=fetch_ingredient('Pasta'), recipe=new_recipe, quantity=350) RecipeIngredientRel.objects.create( ingredient=fetch_ingredient('bacon'), recipe=new_recipe, quantity=25) self.assertEqual(new_recipe.name, 'Spaghetti Carbonara') self.assertEqual(len(new_recipe.ingredients.values()), 2) self.assertEqual(new_recipe.ingredients.values()[0]['name'], 'Pasta')
def process_recipe(self, item, spider): # ------------------------------------------------------ # we will use django framework to save our data, # so there is no need to fetch & save data manually :) # ------------------------------------------------------ recipe = Recipe.objects.filter(origin_id=item.get('origin_id')) if not recipe: logger.debug("--- Create new `recipe` instance: %s" % item.get('title_fa')) # get required fields from item to store recipe instance data = item data['author'] = self.get_author(item.get('author')) # categories is a ManyToManyField and we will save it after we saved the item categories = self.get_categories(item.get('categories')) data.pop('categories', None) new_recipe = Recipe(**data) new_recipe.save() # get the corresponsing list of category objects to update recipe instance logger.debug('*** Recipe Category list:') logger.debug(categories) new_recipe.categories.set(categories) else: logger.error('--- Duplicate: Recipe(%s)' % item.get('title_fa')) logger.error(recipe) return item
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 read_json_file(): with open('all_recipes.json', 'r') as f: all_recipes = json.load(f) for recipe in all_recipes["all_recipes"]: this_recipe = Recipe() try: title = recipe["title"] image = recipe["image"] is_hard = recipe["isHard"] technical_type = recipe["technical_type"] time = recipe["time"] preparation = "" for i in recipe["preparation"]: preparation = preparation + i["name"] recipe_object = Recipe.objects.update_or_create( title=title, image=image, isHard=is_hard, technical_type=technical_type, time=time, text=preparation) name = urlparse(str(recipe_object[0].image)).path.split('/')[-1] content = ContentFile( urllib.request.urlopen(str(recipe_object[0].image)).read()) recipe_object[0].image.save(name, content, save=True) this_recipe = Recipe.objects.get(title=title, isHard=is_hard, technical_type=technical_type, time=time, text=preparation) for i in recipe["ingredients"]: i = i["name"] parse_ingredient_list = parse_ingredient(i) count = parse_ingredient_list[0] measurement_unit = parse_ingredient_list[1] name = parse_ingredient_list[2] try: ingredient_calorie = calculate_ingredient_calories( clean_product_name(name), measurement_unit, clean_ingredient_count(count)) except ValueError: ingredient_calorie = 0 continue Ingredient.objects.update_or_create( count=count, measurementUnit=measurement_unit, name=name, recipe=this_recipe, calorie=ingredient_calorie) except KeyError: this_recipe.clean() continue
def search(request): q = request.GET.get('q', '*') search_results = ( Search(using=client, index='recipes') .filter("term", title=q) .source(exclude=["@timestamp", "@version"]) ) recipes = [Recipe(**r.to_dict()) for r in search_results] return _list_recipes(request, recipes)
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()
def post(self, request): data = json.loads(request.body) new_recipe = Recipe(**data) new_recipe.save() recipe_dict = { 'title': new_recipe.title, 'description': new_recipe.description, 'ingredients': new_recipe.ingredients, 'favourite': new_recipe.favourite } return HttpResponse(content=json.dumps(recipe_dict), status=201)
def setUp(self): self.username = "******" self.password = "******" self.user = User.objects.create_user(username=self.username, password=self.password) self.token, created = Token.objects.get_or_create(user=self.user) self.username2 = "test_user2" self.password2 = "testuserpass123" self.user2 = User.objects.create_user(username=self.username2, password=self.password2) self.token2, created = Token.objects.get_or_create(user=self.user2) self.recipe = { "title": "test_title", "content": "test_content", "ingredients": [{ "name": "test_ingredient1" }, { "name": "test_ingredient2" }, { "name": "test_ingredient3" }], "difficulty": 1 } self.updated_recipe = { "title": "test_title_updated", "content": "test_content_updated", "ingredients": [{ "name": "test_ingredient1_updated" }, { "name": "test_ingredient2_updated" }, { "name": "test_ingredient3_updated" }], "difficulty": 2 } self.current_recipe = Recipe(title=self.recipe["title"], content=self.recipe["content"], author=self.user, difficulty=str(self.recipe["difficulty"])) self.current_recipe.save() for ingredient in self.recipe["ingredients"]: lookup_name = ingredient["name"].lower() lookup_name = lookup_name.replace(" ", "_") ingredient, created = Ingredient.objects.get_or_create( name=ingredient["name"], lookup_name=lookup_name) self.current_recipe.ingredients.add(ingredient)
def mutate(root, info, input=None): ok = True ingredients = [] for ingredient_input in input.ingredients: ingredient = Ingredient.objects.get(pk=ingredient_input.id) if ingredient is None: return CreateRecipe(ok=False, recipe=None) ingredients.append(ingredient) ingredient_instance = Recipe(title=input.title, description=input.description) ingredient_instance.save() ingredient_instance.ingredients.set(ingredients) return CreateRecipe(ok=ok, recipe=ingredient_instance)
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 test_recipe_recipe(self): user = User.objects.create_user(username='******', is_active=True, password='******') recipe = Recipe( title='Pizza', ingredients='Muka, sol, sahar, yaica, kolbasa, tomatnaya pasta i sir.', text='vse smeshat i kinut v pech', owner=User.objects.get(username='******')) recipe.save() our_recipe = Recipe.objects.get(title='Pizza') self.assertEqual(str(recipe), recipe.title) self.assertEqual(our_recipe.title, recipe.title) self.assertEqual(our_recipe.ingredients, recipe.ingredients) self.assertEqual(our_recipe.owner, user) self.assertEqual(our_recipe.text, recipe.text)
def import_recipe(self, data): self.r = Recipe(name=data['name'], source=data['source'], servings=data['servings'], notes=data.get('notes')) self.r.save() self.log.info("Created recipe {}".format(self.r)) for s in data['steps']: step = self.r.steps.create(description=s) self.log.debug(" - Step: {}".format(step)) for i in data['ingredients']: self.import_ingredient(*i) for tagName in data.get('tags', []): tag, _ = RecipeTag.objects.get_or_create(name=tagName) self.r.tags.add(tag)
def create_inithial_data(db_session: Session): try: tags = [ Tag(title="asian"), Tag(title="fast-food") ] db_session.add_all(tags) db_session.commit() users = [ User(username="******", hpass="******", is_active=True), User(username="******", hpass="******", is_active=False) ] db_session.add_all(users) db_session.commit() # db_session.refresh(users) recipes = [ Recipe( title="pancakes", description="classic russian pancakes", likes_count=120, author_id=users[0].id, is_active=True, dish_type=DishTypes.desert ), Recipe( title="pizza", description="Four Cheeses", likes_count=20, author_id=users[0].id, is_active=True, dish_type=DishTypes.second ), Recipe( title="cream soup", description="...", likes_count=0, tags=[tags[1], ], author_id=users[1].id, is_active=True, dish_type=DishTypes.soup ), Recipe( title="Wok + chicken", description="wok for 4 person", likes_count=200, author_id=users[0].id, is_active=False, dish_type=DishTypes.first, tags=[tags[0], ] ) ] db_session.add_all(recipes) db_session.commit() finally: db_session.close()
def mutate(self, info, title, description, cuisine): user = info.context.user or None recipe = Recipe(title=title, description=description, cuisine=cuisine, posted_by=user) recipe.save() return CreateRecipe( id=recipe.id, title=recipe.title, description=recipe.description, cuisine=recipe.cuisine, posted_by=recipe.posted_by, )
def create_recipe(name, category, nb_persons=1, preparation_time=2, total_time=2): """ Creates a new recipe """ recipe = Recipe() recipe.name = name recipe.category = category recipe.nb_persons = nb_persons recipe.preparation_time = preparation_time recipe.total_time = total_time recipe.save() return recipe
def _create_recipe(author, name, tag): products = [ Ingredient.objects.create(name=f'testIng{i}', unit=i) for i in range(2) ] recipe = Recipe(author=author, name=name, description='test test test', slug='testtesttest', image='static/images/testCardImg.png', cook_time=5) recipe.save() recipe.tag.add(tag) for product in products: ingredient = Amount(recipe=recipe, ingredient=product, units=2) ingredient.save() return recipe
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]))
def handle(self, *args, **options): csv_path = options['csv_filename'] if not os.path.exists(csv_path): raise CommandError('invalid csv file path') count_before_add = Recipe.objects.count() with open(csv_path, 'r') as csv_file: reader = csv.DictReader(csv_file) for row in reader: creator = User.objects.get(username='******') category = row['Category'] if category == 'Main Course': category = 'Entree' elif category == 'Beverage' and 'liquor' in row['Ingredients']: category = 'Mixed Drink' try: recipe_type = RecipeType.objects.get(name=category) except RecipeType.DoesNotExist as dne: print('category in csv does not exist in ORM') ingredients = [] for part in re.split(r'\n|,', row['Ingredients']): if len(part.strip().rstrip()) > 0: ingredients.append(part.strip().rstrip().capitalize()) ingredients_json = json.dumps(ingredients) steps = [] for part in re.split(r'\n|\.', row['Description']): if len(part.strip().rstrip()) > 0: steps.append(part.strip().rstrip().capitalize()) steps_json = json.dumps(steps) r = Recipe( creator=creator, name=row['Name'].capitalize(), recipe_type=recipe_type, ingredients_json=ingredients_json, steps_json=steps_json, ) r.save() count_after_add = Recipe.objects.count() print( f'Added {count_after_add-count_before_add} entires to the Django DB.' )
def add_recipes(file_path): xml_file = etree.ElementTree(file=file_path) xml_tag_list = xml_file.getroot() for xml_tag_item in xml_tag_list: for key in xml_tag_item.attrib: if key == 'id': atr_id = xml_tag_item.attrib[key] elif key == 'name': atr_name = xml_tag_item.attrib[key] else: print('Recipe atribut : %s in tag : %s not parsed.' % (key, xml_tag_item.tag)) new_recipe = Recipe(id=atr_id, name=atr_name) for i in xml_tag_item: if i.tag == 'recipe': new_recipe.item = Item.objects.get(pk=i.attrib['id']) new_recipe.level = i.attrib['level'] new_recipe.type = i.attrib['type'] elif i.tag == 'mpCost': new_recipe.mp_cost = i.text elif i.tag == 'successRate': new_recipe.success_rate = i.text elif i.tag == 'production': pass elif i.tag == 'ingredient': pass else: print('Recipe tag: %s not parsed.' % i.tag) new_recipe.save() for i in xml_tag_item: if i.tag == 'production': new_production = RecipeProduction( recipe=new_recipe, item=Item.objects.get(pk=i.attrib['id']), count=i.attrib['count']) new_production.save() elif i.tag == 'ingredient': new_ingredient = RecipeIngredient( recipe=new_recipe, item=Item.objects.get(pk=i.attrib['id']), count=i.attrib['count']) new_ingredient.save()
def create_initial_recipe(apps, schema_editor): if apps and schema_editor: pass stir_fry = Recipe( name="The Hamilton Stir Fry", ingredients=[ "1x Woolworth's packet stir fry", "3x small meat patties", "1/4 salami", "1x Masterfood quick and easy packet sauce (honey mustard, tuscan meatballs, etc)" ], method=[ "Start by cooking burgers and salami in frypan until safe to eat", "Add stir fry and leave for a couple minutes", "Add sauce and leave for extra couple minutes (stir every so often)", "Serve up" ]) stir_fry.save()
def get_or_create_remote_recipe(ap_id): try: recipe = Recipe.objects.get(ap_id=ap_id) except Recipe.DoesNotExist: recipe = dereference(ap_id) recipe = Recipe( ap_id=recipe.id, remote=True, name=recipe.name, # ingredients= TODO get_or_create_ingredient cook_time=int(recipe.duration[2:-1]) if recipe.duration else None, cooking_method=recipe.cookingMethod, category=recipe.recipeCategory, instructions=recipe.content, quantity=recipe.recipeYield.split(" ")[0], quantity_unit=recipe.recipeYield.split(" ")[1:], ) recipe.save() return recipe
def submit_recipe(request): if request.POST: form = UserSubmittedRecipeForm(request.POST) if form.is_valid(): recipe = form.save(commit=False) ingredient_formset = IngredientFormSet(request.POST, instance=recipe) if ingredient_formset.is_valid(): recipe.save() ingredient_formset.save() return HttpResponseRedirect( reverse('recipes:recipes_submit_posted')) else: form = UserSubmittedRecipeForm() ingredient_formset = IngredientFormSet(instance=Recipe()) return render(request, "recipes/submit.html", { "form": form, "ingredient_formset": ingredient_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 create_recipes(categories): # List of recipes recipes = [] # For each category create 2 pages for i in range(0, len(categories)): category = categories[i] # Name the pages according to the links and create a fake url for j in range(0, 2): recipe_number = i * 2 + j + 1 recipe = Recipe(category=category, title="Recipe " + str(recipe_number), url="http://www.recipe" + str(recipe_number) + ".com", views=recipe_number) recipe.save() recipes.append(recipe) return pages
def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): if request.user is not None: recipe = Recipe() recipe.title = form.cleaned_data['title'] recipe.ingredients = form.cleaned_data['ingredients'] recipe.text = form.cleaned_data['text'] recipe.owner = User.objects.get(username=request.user) recipe.is_published = True recipe.pic = form.cleaned_data['pic'] recipe.save() try: form.save() except Exception: pass # profile = Profile.objects.filter(user=User.objects.get(username=request.user)) # profile.update(avatar=form.cleaned_data['avatar']) return super(RecipeCreateView, self).form_valid(form) else: return self.form_invalid(form)
def handle(self, *args, **options): for i in range(100): title_name = generate_title() description_name = generate_description() category_name = generate_category() kitchen_name = generate_kitchen() menu_name = generate_menu() my_date = generate_date() Category.objects.get_or_create(title=category_name) Kitchen.objects.get_or_create(title=kitchen_name) Menu.objects.get_or_create(title=menu_name) recipe = Recipe(title=title_name, description=description_name, category=Category.objects.get(title=category_name), kitchen=Kitchen.objects.get(title=kitchen_name), menu=Menu.objects.get(title=menu_name), date=my_date) recipe.save() self.stdout.write(self.style.SUCCESS('Data imported successfully'))
def post(current_user, self): """ Add a recipe to the database """ data = request.get_json() #numKeys = len(data.keys()) if data: title = data.get('title') ingredients = data.get('ingredients') steps = data.get('steps') status = data.get('status') category = data.get('category') if title and ingredients and steps and status and category: if validate_text(data['title']): if validate_text(data['ingredients']): if validate_text(data['steps']): if data['status'] == 'public' or data['status'] == 'private': category = Category.query.filter_by(cat_name=data['category']).first() if category: recipe_check=Recipe.query.filter_by(title=data['title']).first() if not recipe_check: new_recipe = Recipe(recipe_id=str(uuid.uuid4()), title=data['title'], category=data['category'], ingredients=data['ingredients'], steps=data['steps'], create_date=datetime.now(), created_by=current_user.username, modified_date=datetime.now(), status=data['status']) save(new_recipe) return ({'Message' : 'Recipe Created'}, 201) return ({'Message' : 'Title already exists'}, 400) return ({'Message' : 'Category does not exist'}, 400) return ({'Message' : 'The status should either be public or private'}, 400) return ({'Message' : 'Please enter valid steps'}, 400) return ({'Message' : 'Please enter valid ingredients'}, 400) return ({'Message' : 'Please enter a valid title'}, 400) return ({'Message' : 'Populate all the required fields'}, 400) return ({'Message' : 'No data submitted'}, 400)