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'] if options['csv']: menu.shopping_csv() else: menu.shopping_list() 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']) tempMenu.save() tempMenu.recipes.set(recipes) if options['csv']: tempMenu.shopping_csv() else: tempMenu.shopping_list() tempMenu.delete()
def create(request): try: body = json.loads(request.body) _email = body.get('email') _password = body.get('password') _isRestaurant = body.get('isRestaurant') or False if _isRestaurant: M = Menu(restaurant_name=_email) M.save() #_restaurant = request.POST.get('restaurant') # other stuff too # create using function or modelname.objects.create(param1=x, param2 = y.....etc) #if _restaurant == 'yes': # newuser = CustomUserManager().create_restaurant_user(_email, _password) #else: # newuser = CustomUserManager().create_user(_email, _password) #return HttpResponse(newuser.get('is_restaurant')) #email('user_email', 0) _salt = get_random_string(length=32) password = hashlib.sha256(_password.encode()).hexdigest() user = Customuser(email=_email, password=password, isRestaurant=_isRestaurant) user.save() return JsonResponse({"success": True}, status=200) except ValueError: return JsonResponse( { "success": False, "message": "Email must be valid or email is already in use" }, status=400)
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))
def cache_menu(restaurant, date): # call networking functions to fetch restaurant data # save that to db menu = get_restaurant_menu(restaurant, date) for dishoption in menu: # print(dishoption) dish = Menu(restaurant_id=restaurant["restaurant_id"], menu_item_en=dishoption["meal_name_en"], menu_item_fi=dishoption["meal_name_fi"], menu_date=date, menu_name=dishoption["menu_name"]) dish.save()
def clean(self): cleaned_data = super(MenuForm, self).clean() name = cleaned_data.get("name") if name: self.menu_cache = Menu(name=name) else: self.menu_cache = Menu() if self.menu_cache is None: self.error_messages = "Le menu n'a put être créée" self.error_code = 403 raise forms.ValidationError("Menu création failed") return cleaned_data
def respondwithmenu(request, restaurant_name): date_now = datetime.datetime.today().date() try: dbmenu = Menu.objects.get(restaurant_id=490051, menu_date=date_now) except Menu.DoesNotExist: menu = get_restaurant_menu() menu_items_en = [] menu_items_fi = [] for dishoption in menu: print(dishoption) menu_items_en.append(dishoption["name_en"]) menu_items_fi.append(dishoption["name_fi"]) print("menu items en") print(menu_items_en) dbmenu = Menu(restaurant_id=490051, menu_items_en=menu_items_en, menu_items_fi=menu_items_fi) #dbmenu = Menu(restaurant_id=490051, menu_items_en="potatismus", menu_items_fi="pottumuusi") #dbmenu.save() print("got menu:") print(dbmenu) # response = HttpResponse(json.dumps(menu), content_type="application/json") response = dbmenu.menu_items_fi return HttpResponse("this should not come back from here any more")
def test_string_representation_if_description_value_and_value_unit_provided( self): menu = Menu(restaurant=Restaurant(name='test restaurant')) size = Size(menu=menu, description='Test size', value='32', value_unit='cm') expected_result = 'Test size (32 cm)' self.assertEqual(str(size), expected_result)
def test_string_representation(self): menu = Menu(restaurant=Restaurant(name='test restaurant')) size = Size(menu=menu, description='Test size', value='32', value_unit='cm') meal = Meal(menu=menu, name='test meal') price = Price(value='24.99', size=size, content_object=meal) expected_result = '24.99' self.assertEqual(str(price), expected_result)
def handle(self, *args, **options): try: menu = Menu(name=options['name'], servings=options['servings']) menu.save() for recipe_name in options['recipes']: menu.recipes.add(Recipe.get_by_name(recipe_name)) except (Recipe.DoesNotExist, Recipe.MultipleObjectsReturned): menu.delete() raise CommandError("No recipe with name '{}'".format(recipe_name)) except Recipe.MultipleObjectsReturned: menu.delete() raise CommandError( "Multiple recipes matched name '{}'".format(recipe_name))
def new_menu(request): if request.user.groups.filter(name="Customer").exists(): messages.warning(request, "Você não pode acessar essa página") return redirect('orders_list') try: restaurant = Restaurant.objects.get(manager=request.user) except Restaurant.DoesNotExist: messages.warning(request, "Você precisa cadastrar um restaurante") return redirect('new_restaurant') categories = Category.objects.filter(restaurant__manager=request.user) menu_form = Menu() categories_menu_formset = inlineformset_factory(Menu, MenuCategory, form=MenuCategoriesForm, extra=len(categories), max_num=len(categories)) if request.method == 'POST': form = MenuForm(request.POST, instance=menu_form, prefix='main') formset = categories_menu_formset(request.POST, instance=menu_form, prefix='product') for formulario in formset: formulario.fields['category'].queryset = Category.objects.filter( restaurant__manager=request.user) try: if form.is_valid() and formset.is_valid(): novo_cardapio = form.save(commit=False) novo_cardapio.restaurant = restaurant novo_cardapio.save() formset.save() messages.success(request, "Novo cardápio cadastrado.") return redirect('menu_list') except Exception as e: messages.warning(request, f'Ocorreu um erro ao atualizar: {e}') else: form = MenuForm(instance=menu_form, prefix='main') formset = categories_menu_formset(instance=menu_form, prefix='product') for formulario in formset: formulario.fields['category'].queryset = Category.objects.filter( restaurant__manager=request.user) # TODO: Aplicar queryset no formset antes. context = {'form': form, 'formset': formset} return render(request, 'menus/new.html', context=context)
def create_view(request): """ Create a new menu A new menu will be generated given a particular date, if for the selected date a menu already exists, it will be canceled and the user will be notified that he cannot add another menu for the same date. """ form = MenuForm() if request.method == 'POST': form = MenuForm(request.POST) if form.is_valid(): menu = Menu(**form.cleaned_data) menu.save() return HttpResponseRedirect(reverse('menus:menu_edit_dishes', args=( menu.uuid, ))) return render(request, 'menus/create.html', context={ 'form': form })
class MenuImporter: """ Imports a data structure as a menu. Recipes will be added as fuzzy match. { name: str, servings: int, recipes: [str] } """ def __init__(self, log=None): self.log = log or get_logger(__file__, "menu_importer.log", logging.WARNING) 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))
def create(request): _restaurant_name = request.POST.get('restaurant_name') M = Menu(restaurant_name=_restaurant_name) M.save() return JsonResponse({"success": True, "id": M.id}, status=200)
def test_string_representation(self): basket = Basket(owner=User.objects.get(username='******')) meal = Meal(menu=Menu(restaurant=Restaurant(name='restaurant')), name='soup') order = Order(basket=basket, meal=meal) self.assertEqual(str(order), 'christopher soup')
def test_string_representation(self): expected_result = 'test restaurant' menu = Menu(restaurant=Restaurant(name=expected_result)) self.assertEqual(str(menu), expected_result)
def test_string_representation(self): menu = Menu(restaurant=Restaurant(name='test restaurant')) ingredient = Ingredient(name='test ingredient') topping = Topping(menu=menu, ingredient=ingredient) expected_result = 'test restaurant | test ingredient' self.assertEqual(str(topping), expected_result)
def test_string_representation(self): menu = Menu(restaurant=Restaurant(name='test restaurant')) meal = Meal(menu=menu, name='test meal') expected_result = 'test restaurant | test meal' self.assertEqual(str(meal), expected_result)
def test_string_representation_returns_default_if_desc_and_value_is_empty( self): menu = Menu(restaurant=Restaurant(name='test restaurant')) size = Size(menu=menu) expected_result = 'Normal size' self.assertEqual(str(size), expected_result)