def _create_recipe(self, name, foods, cooking_time=0, preparation_time=0): """ Creates a recipe with the given parameters and adds some bogus steps """ recipe = Recipe( name=name, subtitle='Something something', description="A refreshing take on %s. Have fun." % name, cooking_time=cooking_time, preparation_time=preparation_time, approved=True, number_servings=2 ) recipe.save() for index, food in enumerate(foods): recipe.ingredients.add( Ingredient(quantity=1, food=food, order=index, recipe=recipe) ) recipe.steps.add( Step(order=1, text="Step 1 blabla", recipe=recipe), Step(order=2, text="Step 2 blabla", recipe=recipe), Step(order=3, text="Step 3 blabla", recipe=recipe), ) Picture.objects.create( url='http://placehold.it/725x350', content_object=recipe ) recipe.save()
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')
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)
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
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')
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 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 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 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 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 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 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 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)
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 _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
class RecipeImporter: """ Imports a data structure as a recipe: { name: str, source: url, servings: int, notes: str, ingredients: [qty, unit, ingerdient, notes?], steps: [str] } """ def __init__(self, log=None): self.log = log or get_logger(__file__, "recipe_importer.log", logging.WARNING) 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 import_ingredient(self, quantity, unit, name, notes=None): "Parses a string as a RecipeIngredient" ingredient, created = Ingredient.objects.get_or_create(name=name) self.log.info("{} ingredient {}".format( "Created" if created else "Loaded", ingredient)) try: ingUnit = IngredientUnit.lookup(unit) self.log.info("Loaded ingredient unit {}".format(ingUnit)) except IngredientUnit.DoesNotExist: ingUnit = IngredientUnit.objects.create(name=unit, short=unit) self.log.info("Created ingredient unit {}".format(ingUnit)) ri = self.r.ingredients.create(ingredient=ingredient, unit=ingUnit, recipe=self.r, quantity=quantity, notes=notes) self.log.info("Added {}".format(ri))
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 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 get_one_drink_with_extra_ingredients(): recipes = Recipe.get_recipes_by_ingredients([self.vodka_id, self.pineapple_juice_id, self.oj_id, self.rum_id]) self.assertEqual(1, len(recipes)) self.assertEqual(self.screwdriver, recipes[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]))
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 setUp(self): city = City.objects.get(name="Curitiba") recipe = Recipe() recipe.title = "Minha receita" recipe.instructions = "Receita" recipe.save() week = WeeklyRecipes() week.city = city week.start_date = datetime.now() week.end_date = datetime.now() + timedelta(days=7) week.save() week.recipes.add(recipe) week.save() self.week = week
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 handle(self, *args, **options): if not options['menu'] and not options['recipes']: raise CommandError( "Please provide a menu name or a list or recipes.") if options['menu']: if options['recipes']: raise CommandError( "Please provide a menu name or a list of recipes, but not both." ) menu = Menu.objects.get(name__contains=options['menu']) if options['servings']: menu.servings = options['servings'] menu.cooking_view() else: try: recipes = [ Recipe.get_by_name(name, ask_which=True) for name in options['recipes'] ] except (Recipe.DoesNotExist, Recipe.MultipleObjectsReturned) as e: raise CommandError(e) tempMenu = Menu(name="Menu", servings=options['servings'] or 1) tempMenu.save() tempMenu.recipes.set(recipes) tempMenu.cooking_view() tempMenu.delete()
def test_can_delete_recipe(self): self.browser.get(self.live_server_url) recipe = Recipe(title='Tomato Soup', author=self.user_henry.profile) recipe.save() # henry would like to edit a recipe he previously created self.login_user(self.henry_credentials['username'], self.henry_credentials['password']) self.browser.find_element_by_link_text('Tomato Soup').click() # he sees and clicks the edit button on the recipes detail page self.browser.find_element_by_link_text('Remove').click() self.assertFalse(self.is_element_present(self.browser.find_element_by_link_text, 'Tomato Soup')) self.assertEqual(Recipe.objects.count(), 0)
def get_two_drinks(): recipes = Recipe.get_recipes_by_ingredients([self.vodka_id, self.gin_id, self.oj_id]) recipes.sort(key=lambda recipe: recipe.id) expected_recipes = sorted([self.gin_vodka, self.screwdriver], key=lambda recipe: recipe.id) self.assertEqual(2, len(recipes)) self.assertListEqual(expected_recipes, recipes)
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 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 import_menu(self, data): r = [ Recipe.get_by_name(name, ask_which=True) for name in data['recipes'] ] self.m = Menu(name=data['name'], servings=data['servings']) self.m.save() self.m.recipes.set(r) self.log.info("Created menu {}".format(self.m))
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')
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 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 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_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 dispatch(self, *args, **kwargs): if 'recipe_id' in self.kwargs: try: self.instance = Recipe.objects.select_related().prefetch_related('uses__unit').get(pk=self.kwargs['recipe_id']) except Recipe.DoesNotExist: raise Http404 if (not self.request.user == self.instance.author_id) and not self.request.user.is_staff: raise PermissionDenied else: self.instance = Recipe() return SessionWizardView.dispatch(self, *args, **kwargs)
def test_redirects_after_save(self): user = User() user.name = 'ben' user.save() recipe = Recipe() recipe.title = 'cacio e pepe' recipe.url_name = 'cacio-e-pepe' recipe.ingredients = 'kosher salt\n6 oz. pasta \n3 Tbsp. unsalted butter\n 1 tsp. freshly cracked black pepper' recipe.directions = 'bring water to a boil\ncook pasta\nadd butter and pepper' recipe.servings = '4' recipe.user = user recipe.save() response = self.client.post('/users/%s/recipe/%s/edit' % (user.name, recipe.url_name), data={'title': 'Cacio e Pepe'}) self.assertRedirects(response, '/users/%s/recipe/%s' % (user.name, recipe.url_name))
def get_drinks_with_all_ingredients(): recipes = Recipe.get_recipes_by_ingredients([self.coconut_cream_id, self.pineapple_juice_id, self.gin_id, self.oj_id, self.vodka_id, self.rum_id, self.white_rum_id]) recipes.sort(key=lambda recipe: recipe.id) expected_recipes = sorted([self.gin_vodka, self.screwdriver, self.pina_colada], key=lambda recipe: recipe.id) self.assertEqual(3, len(recipes)) self.assertListEqual(expected_recipes, recipes)
def test_save_a_post_request_for_an_existing_recipe(self): user = User() user.name = 'ben' user.save() recipe = Recipe() recipe.title = 'cacio e pepe' recipe.url_name = 'cacio-e-pepe' recipe.ingredients = 'kosher salt\n6 oz. pasta \n3 Tbsp. unsalted butter\n 1 tsp. freshly cracked black pepper' recipe.directions = 'bring water to a boil\ncook pasta\nadd butter and pepper' recipe.servings = '4' recipe.user = user recipe.save() self.client.post('/users/%s/recipe/%s/edit' % (user.name, recipe.url_name), data={'title': 'Cacio e Pepe'}) edited_recipe = Recipe.objects.first() self.assertEqual(edited_recipe.title, 'Cacio e Pepe')
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 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 setUp(self): recipe = Recipe() recipe.title = "Minha receita" recipe.instructions = "Receita" recipe.save() self.recipe = recipe
def handle(self, *args, **options): r = Recipe(name=' '.join(options['name']), description='description') r.save() r.add_date = datetime.date.today() - datetime.timedelta(days=2) r.save() self.stdout.write(r.slug)
class EditRecipeWizard(SessionWizardView): FORMS = [('basic_info', EditRecipeBasicInfoForm), ('ingredients', EditRecipeIngredientsForm), ('instructions', EditRecipeInstructionsForm)] TEMPLATES = {'basic_info': 'recipes/edit_recipe_basic_info.html', 'ingredients': 'recipes/edit_recipe_ingredients.html', 'instructions': 'recipes/edit_recipe_instructions.html'} file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'tmp_recipe_imgs')) instance = None def get_form_instance(self, step): return self.instance def get_form(self, step=None, data=None, files=None): """ We need to overwrite this, because otherwise 'instance' is not passed to the FormContainer """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm) or issubclass(self.form_list[step], FormContainer): # If the form is based on ModelForm, add instance if available # and not previously set. kwargs.setdefault('instance', self.get_form_instance(step)) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet) or issubclass(self.form_list[step], FormContainer): # If the form is based on ModelFormSet, add queryset if available # and not previous set. kwargs.setdefault('queryset', self.get_form_instance(step)) return self.form_list[step](**kwargs) def form_is_valid(self, step=None): if step is None: step = self.steps.current form = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if not form.is_bound: # The form did not receive any new data. It can only be valid if an instance was present return self.instance is not None and self.instance.id is not None # The form received new data, check the validity of the new data return form.is_valid() def is_valid(self): return all(self.form_is_valid(step) for step in self.steps.all) def get_template_names(self): return self.TEMPLATES[self.steps.current] def get_context_data(self, form, **kwargs): context = SessionWizardView.get_context_data(self, form, **kwargs) # Check if we are adding a new or editing an existing recipe if 'recipe_id' in self.kwargs: context['new_recipe'] = False else: context['new_recipe'] = True for step in self.steps.all: context['%s_form_valid' % step] = self.form_is_valid(step) return context # Make sure login is required for every view in this class @method_decorator(login_required) def dispatch(self, *args, **kwargs): if 'recipe_id' in self.kwargs: try: self.instance = Recipe.objects.select_related().prefetch_related('uses__unit').get(pk=self.kwargs['recipe_id']) except Recipe.DoesNotExist: raise Http404 if (not self.request.user == self.instance.author_id) and not self.request.user.is_staff: raise PermissionDenied else: self.instance = Recipe() return SessionWizardView.dispatch(self, *args, **kwargs) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful and the next step was requested) or the done view (if no more steps are available or the entire wizard was submitted) """ # Look for a wizard_goto_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_goto_step = self.request.POST.get('wizard_goto_step', None) wizard_finish = self.request.POST.get('wizard_finish', None) if wizard_goto_step and wizard_goto_step in self.get_form_list(): self.storage.current_step = wizard_goto_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) form.is_valid() return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError('ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) if wizard_finish: # User tried to submit the entire form if self.is_valid(): return self.render_done(form, **kwargs) else: for step in self.steps.all: if not self.form_is_valid(step): self.storage.current_step = step form = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) form.is_valid() return self.render(form) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ This method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next data = self.storage.get_step_data(next_step) files = self.storage.get_step_files(next_step) new_form = self.get_form(next_step, data=data, files=files) if data or files: new_form.is_valid() # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if form_obj.is_bound or self.instance is None or self.instance.id is None: # only add the form if it changes the instances attributes if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def done(self, form_list, **kwargs): if not self.instance.author: self.instance.author = self.request.user # recipe has not been saved yet self.instance.save() # Check if the ingredients form is present for form in form_list: if hasattr(form, 'forms') and 'ingredients' in form.forms: ing_form = form.forms['ingredients'] if ing_form.has_changed(): # Check for unknown ingredients if ing_form.unknown_ingredients: request_string = '' for ingredient_info in ing_form.unknown_ingredients: request_string += 'Naam ingredient: %s\nGevraagde eenheid: %s\n\n' % (ingredient_info['name'], ingredient_info['unit']) try: ingredient = Ingredient.objects.with_name(ingredient_info['name']) # If this works, the ingredient exists, but isn't accepted except Ingredient.DoesNotExist: # An ingredient with the given name does not exist, so we need to add it ingredient = Ingredient(name=ingredient_info['name'], category=Ingredient.DRINKS, base_footprint=0) ingredient.save() if not ingredient.can_use_unit(ingredient_info['unit']): ingredients.models.CanUseUnit(ingredient=ingredient, unit=ingredient_info['unit'], conversion_factor=0).save() if not UnknownIngredient.objects.filter(name=ingredient_info['name'], requested_by=self.request.user, real_ingredient=ingredient, for_recipe=self.instance).exists(): UnknownIngredient(name=ingredient_info['name'], requested_by=self.request.user, real_ingredient=ingredient, for_recipe=self.instance).save() # revalidate the ingredient forms for form in ing_form: # Allow unaccepted ingredients this time around form.fields['ingredient'].unaccepted_ingredients_allowed = True form.full_clean() # Send mail send_mail('Aanvraag voor Ingredienten', render_to_string('emails/request_ingredients_email.txt', {'user': self.request.user, 'request_string': request_string}), self.request.user.email, ['*****@*****.**'], fail_silently=True) ing_form.save() # And save the recipe again to update the footprint recipe = Recipe.objects.select_related().prefetch_related('uses__unit').get(pk=self.instance.pk) recipe.save() messages.add_message(self.request, messages.INFO, 'Je nieuwe recept werd met succes toegevoegd!') return redirect('/recipes/%d/' % self.instance.id)
def get_one_drink(): recipes = Recipe.get_recipes_by_ingredients([self.pineapple_juice_id, self.white_rum_id, self.coconut_cream_id]) self.assertEqual(1, len(recipes)) self.assertEqual(self.pina_colada, recipes[0])
def __init__(self, recipe: Recipe, team:Team): self.recipe = recipe self.can_perform = recipe.can_perform(team) (self.needs, self.creates, self.consumes) = recipe.ingredients()
desserts = Category(name="Desserts", description="Les desserts...") desserts.save() plats = Category(name="Plats", description="Les plats...") plats.save() entrees = Category(name="Entrées", description="Les entrées...") entrees.save() ### # Recipes ### recipe = Recipe(title="Cake Olives-Jambon", author=admin, preparation_time="20min", portion="5-6") save_file(recipe.picture, 'test/cake jambon olives.jpg') recipe.ingredients = u"""- vin blanc sec: 15cL - huile d'olive: 15cL - oeufs: 4 - gruyère rapé: 100g - farine: 250g - levure: 1 paquet - sel: 1 c. à café - dés de jambon: 200g - olives vertes: 200g""" recipe.content = u"""- Dans un saladier, travailler le vin, l'huile et les oeufs cassés un par un. - Ajouter la farine, le gruyère rapé, la levure et sel. Terminer par le jambon et les olives coupées en 2. - Faire cuire dans un moule à cake beurré et fariné.""" recipe.category = plats
def create_recipe(request): errors = [] new_ingredient={} new_direction='' if 'new_recipe' not in request.session: # If this user has not already tried to create a recipe, one is created when they visit the site. recipe = Recipe() recipe.save() new_recipe = recipe.id request.session['new_recipe'] = new_recipe # The 'new_recipe' cookie is the ID of the saved recipe, should be reset when the recipe is saved or erased. ingredients=[] directions=[] recipe_name = 'Recipe Name' errors.append('New Recipe %s created with ID %s' %(recipe_name, new_recipe)) new_ingredient={'amount':'Amount', 'unit':'Unit', 'ingredient':'Ingredient'} new_direction='' else: # Otherwise, the old recipe is pulled, and the ingredients and directions are parsed into temporary lists. new_recipe = request.session['new_recipe'] recipe = Recipe(id=new_recipe) errors.append('old recipe #%s loaded' % new_recipe) for k,v in request.POST.iteritems(): errors.append('%s = %s' %(k,v)) for k,v in request.GET.iteritems(): errors.append('%s = %s' %(k,v)) # Check to see if form is filled out correctly, and then update recipe if request.method == 'POST': if 'finish' in request.POST: if 'recipe_name' in request.POST: recipe_name = request.POST['recipe_name'] if not recipe_name or recipe_name == 'Recipe Name': errors.append("Come on man, you forgot the recipe name.") else: recipe.recipe_name = recipe_name recipe.save() if 'ingredient' in request.POST: if 'ingredient_amount' in request.POST: ingredient_amount = request.POST['ingredient_amount'] if not ingredient_amount or ingredient_amount == 'Amount': errors.append('Dude you forgot an amount!') new_ingredient['amount'] = 'Amount' amount = False else: new_ingredient['amount'] = request.POST['ingredient_amount'] amount = True if 'ingredient_unit' in request.POST: ingredient_unit = request.POST['ingredient_unit'] if not ingredient_unit or ingredient_unit == 'Unit': errors.append('Where are the units?!') new_ingredient['unit'] = 'Unit' unit = False else: new_ingredient['unit'] = request.POST['ingredient_unit'] unit = True if 'ingredient_type' in request.POST: ingredient_type = request.POST['ingredient_type'] if not ingredient_type or ingredient_type == 'Ingredient': errors.append("Yo what's the ingredient dummy?") new_ingredient['ingredient'] = 'Ingredient' ingredient = False else: new_ingredient['ingredient'] = request.POST['ingredient_type'] ingredient = True if ingredient and unit and amount: recipe.ingredients.item_name, recipe.ingredients.unit, recipe.ingredients.amount = \ new_ingredient['ingredient'], new_ingredient['unit'], new_ingredient['amount'] recipe.save() # If there are no errors, add the ingredients and/or directions if not errors: pass # Update the form recipe_name = recipe.recipe_name errors.append('recipe_name set to %s' % recipe_name) ingredient_list = recipe.ingredients.all() direction_list = recipe.directions.all() ingredients = [ingredient.__unicode__ for ingredient in ingredient_list] directions = [direction.step for direction in direction_list] step_number = len(directions) + 1 errors.append(ingredient_list) return render(request, 'create_recipe.html', {'recipe_name': recipe_name, 'errors' : errors, 'ingredients': ingredients, 'new_ingredient': new_ingredient, 'directions': directions, 'new_direction':new_direction, 'step_number': step_number})
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
def all_ingredients(): from .models import Ingredient from recipes.models import Recipe return Ingredient.all_objects() + Recipe.all_objects()