def create_new_external_recipe(request, import_id): if request.method == "POST": form = ImportRecipeForm(request.POST, space=request.space) if form.is_valid(): new_recipe = get_object_or_404(RecipeImport, pk=import_id, space=request.space) recipe = Recipe() recipe.space = request.space recipe.storage = new_recipe.storage recipe.name = form.cleaned_data['name'] recipe.file_path = form.cleaned_data['file_path'] recipe.file_uid = form.cleaned_data['file_uid'] recipe.created_by = request.user recipe.save() if form.cleaned_data['keywords']: recipe.keywords.set(form.cleaned_data['keywords']) new_recipe.delete() messages.add_message(request, messages.SUCCESS, _('Imported new recipe!')) return redirect('list_recipe_import') else: messages.add_message(request, messages.ERROR, _('There was an error importing this recipe!')) else: new_recipe = get_object_or_404(RecipeImport, pk=import_id, space=request.space) form = ImportRecipeForm( initial={ 'file_path': new_recipe.file_path, 'name': new_recipe.name, 'file_uid': new_recipe.file_uid }, space=request.space ) return render(request, 'forms/edit_import_recipe.html', {'form': form})
def batch_import(request): imports = RecipeImport.objects.all() for new_recipe in imports: recipe = Recipe(name=new_recipe.name, file_path=new_recipe.file_path, storage=new_recipe.storage, file_uid=new_recipe.file_uid, created_by=request.user) recipe.save() new_recipe.delete() return redirect('list_recipe_import')
def test_create(self): before = len(Recipe.query.all()) r = Recipe(name='Meatballs') assert r.name == 'Meatballs' db.session.add(r) db.session.commit() assert len(Recipe.query.all()) == before + 1
def test_meal_string(self): """Format Meal as a string. """ pancakes = Recipe.get(name='Pancakes') meal, created = Meal.objects.get_or_create( kind='breakfast', recipe=pancakes, date=datetime.today()) self.assertEqual(str(meal), 'Breakfast: Pancakes')
def add_note(request): user = request.user recipe_note = request.GET.get('recipe_note') recipe_id = request.GET.get("recipe_id") r = Recipe(pk=recipe_id) #refactor to one line using Note.create() n = Note.objects.create(user_id=user, note_text=recipe_note, recipe_id=r) # n.user_id = user # n.note_text = recipe_note # n.recipe_id = r # n.save() return HttpResponseRedirect("member/recipe" + str(recipe_id))
def handle_uploaded_file(f): if not f.size < 1e6: raise MemoryError('File too big!') mime = Magic(mime=True) if mime.from_buffer(f.read()) != 'text/plain': raise ValueError('Passed file is not a text file.') f.file.seek(0) file = TextIOWrapper(f.file) recipe_file = parse_file(file) output = recipe_file.to_djangodb() # If recipe with same UUID exists, try to update it, else create a new one. if 'uuid' in output and output['uuid']: try: current_version = Recipe.objects.get(pk=output['uuid']) log.info('Replacing currently existing recipe with new one.') for field in current_version.__dict__: if field in output: current_version.__dict__[field] = output[field] current_version.save() return current_version except Recipe.DoesNotExist: pass log.info('Creating new recipe entry for {}'.format(output['name'])) recipe = Recipe(**output) recipe.save() return recipe
def new_recipe(): form = RecipeForm() if form.validate_on_submit(): recipe = Recipe(title=form.title.data, cuisine=form.cuisine.data, description=form.description.data, picture=form.picture.data, requirement=form.requirement.data, ingredients=form.ingredients.data, preparation=form.preparation.data, author=current_user) db.session.add(recipe) db.session.commit() flash('New Recipe Created', 'success') return redirect(url_for('home')) return render_template('new_recipe.html', form=form)
def update_recipe(request): if request.method == 'POST': old_recipe = request.POST.get('old_recipe', '') recipe_name = request.POST.get('name_input', '') recipe_info = request.POST.get('info_input', '') recipe_chef = request.POST.get('chef_input', '') username = request.POST.get('username_input', '') recipe_time = int(request.POST.get('time_input', '')) recipe_equipment = request.POST.get('equipment_input', '') recipe_fat = int(request.POST.get('fat_input', '')) measurement_list = request.POST.getlist('text_measurement') ingredient_list = request.POST.getlist('text_ingredient') recipe_ingredient = "" for i in range(len(measurement_list) - 1): recipe_ingredient += measurement_list[i] + ":" + ingredient_list[i] recipe_ingredient += "||" recipe_ingredient += measurement_list[len(measurement_list) - 1] + ":" + ingredient_list[ len(ingredient_list) - 1] recipe_method = "||".join(request.POST.getlist("text_direction")) recipe = Recipe(recipe_name=recipe_name, recipe_chef=recipe_chef, recipe_info=recipe_info, recipe_time=recipe_time, recipe_equipment=recipe_equipment, recipe_fat=recipe_fat, recipe_ingredient=recipe_ingredient, recipe_method=recipe_method) recipe_image_1 = request.FILES.get('image1', '') recipe_image_2 = request.FILES.get('image2', '') recipe_image_3 = request.FILES.get('image3', '') recipe_image_4 = request.FILES.get('image4', '') if recipe_image_1: recipe.recipe_image_1 = recipe_image_1 if recipe_image_2: recipe.recipe_image_2 = recipe_image_2 if recipe_image_3: recipe.recipe_image_3 = recipe_image_3 if recipe_image_4: recipe.recipe_image_4 = recipe_image_4 if old_recipe: delete_recipe = Recipe.objects.get(recipe_name__exact=old_recipe) if delete_recipe: delete_recipe.delete() delete_author = AuthorUser.objects.get( recipe_name__exact=old_recipe, user_username__exact=username) if delete_author: delete_author.delete() recipe.save() author = AuthorUser(user_username=username, recipe_name=recipe_name) author.save() category_list = request.POST.getlist('check_category') for category in category_list: recipe.category_tags.add(category) time_list = request.POST.getlist('check_time') for time in time_list: recipe.time_tags.add(time) equipment_list = request.POST.getlist('check_equipment') for equipment in equipment_list: recipe.equipment_tags.add(equipment) allergies_list = request.POST.getlist('check_allergies') for allergies in allergies_list: recipe.allergies_tags.add(allergies) return HttpResponseRedirect(reverse("cookbook:profile")) raise Http404
def createRecipe(request): if request.user.is_authenticated: if request.method == 'POST': name = request.POST["name"] recipe_text = request.POST["recipe_text"] nb_people = request.POST["nb_people"] ingredients = request.POST.getlist("ingredients[]") unit = request.POST.getlist("unit[]") qty = request.POST.getlist("qty[]") tags = request.POST.getlist("tags[]") i = 0 while i < len(ingredients): if not Ingredient.objects.filter(name=ingredients[i]).exists(): del ingredients[i] del unit[i] del qty[i] else: i += 1 j = 0 while j < len(tags): if not RecipeTag.objects.filter(name=tags[j]).exists(): del tags[j] else: j += 1 if name and recipe_text and nb_people and ingredients and unit and qty: if len(ingredients) == len(unit) and len(unit) == len(qty): if int(nb_people) > 0: user = User.objects.get( username=request.user.get_username()) recipe = Recipe(user=user, name=name, recipe_text=recipe_text, number_of_people=int(nb_people)) recipe.save() for i in range(len(ingredients)): contains = Contains( ingredient=Ingredient.objects.get( name=ingredients[i]), unit=unit[i], quantity=int(qty[i]), recipe=recipe) contains.save() for i in range(len(tags)): belongs = Belongs( recipeTag=RecipeTag.objects.get(name=tags[i]), recipe=recipe) belongs.save() return JsonResponse({ "success": True, "url": reverse("cookbook:createRecipe") }) else: return JsonResponse({ "success": False, "message": "Nombre de personne invalide" }) else: return JsonResponse({ "success": False, "message": "Une erreur est survenue sur la liste d'ingrédients" }) else: return JsonResponse({ "success": False, "message": "Veuillez remplir les champs obligatoires correctement" }) else: return render(request, 'cookbook/createRecipe.html') else: messages.warning(request, "Veuillez vous connecter") return HttpResponseRedirect(reverse('cookbook:login'))
def handle(self, *args, **options): default_categories = [ 'Pizza', 'Asian', 'Burgers', 'Barbecue', 'Desserts', 'Thai', 'Sushi', 'Others', ] for category in default_categories: try: c = FoodCategory(name=category) c.save() except Exception as e: raise CommandError('Error when trying to seed \n %s' % e.msg) default_ingredients = [ { 'name': 'Mozzarella Cheese', 'article_number': '15O1A0351K', 'unit': 'G', 'amount': 500, 'cost': 12, }, { 'name': 'Flour', 'article_number': 'K1595SDF', 'unit': 'KG', 'amount': 1, 'cost': 3, }, { 'name': 'Tomato', 'article_number': 'G19D1HO', 'unit': 'KG', 'amount': 1, 'cost': 7, }, { 'name': 'Basil', 'article_number': 'OA91UIVD', 'unit': 'G', 'amount': 50, 'cost': 0.4, }, ] for ingredient in default_ingredients: try: i = Ingredient(name=ingredient['name'], article_number=ingredient['article_number'], unit=ingredient['unit'], amount=ingredient['amount'], cost=ingredient['cost']) i.save() except Exception as e: raise CommandError('Error when trying to seed \n %s' % e.msg) default_recipe = { 'name': 'Marguerita', 'image': 'https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fcdn-image.myrecipes.com%2Fsites%2Fdefault%2Ffiles%2Fstyles%2Fmedium_2x%2Fpublic%2Fimage%2Frecipes%2Foh%2F12%2Fmozzarella-and-basil-pizza-oh-x.jpg%3Fitok%3D3jn_M-VX&w=450&c=sc&poi=face&q=85', 'description': 'An easy pizza recipe with unbeatable flavor!', 'instructions': 'This margherita pizza recipe begins with homemade pizza dough. Top with fresh mozzarella and tomatoes, then finish it off with garden-fresh basil.', 'servings': 4, 'difficulty': 1, 'time': 2, 'category': FoodCategory.objects.get(name='Pizza'), } try: r = Recipe( name=default_recipe['name'], image=default_recipe['image'], description=default_recipe['description'], instructions=default_recipe['instructions'], servings=default_recipe['servings'], difficulty=default_recipe['difficulty'], time=default_recipe['time'], category=default_recipe['category'], ) r.save() ingredients = Ingredient.objects.all() for ingredient in ingredients: amount_used = 0 if ingredient.unit == 'KG' or ingredient.unit == 'L': amount_used = random.randint(1, 5) else: amount_used = random.randint(100, 1000) ri = RecipeIngredient(ingredient=ingredient, recipe=r, amount_used=amount_used) ri.save() except Exception as e: raise CommandError('Error when trying to seed \n %s' % e.msg) self.stdout.write( self.style.SUCCESS('Successfully seeded the database'))