Advertisement
Guest User

Untitled

a guest
Mar 19th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.70 KB | None | 0 0
  1. from .forms import RecipeIngredientForm, RecipeForm, CalorieForm, ServingsForm, CommentForm, SpecificCalorieForm
  2. from .models import Recipe, Ingredient, RecipeIngredient, Unit, RecipeOwner, IngredientUnitToCal, UserHistory, RecipeComment
  3. from django.contrib.auth import login
  4. from django.http import HttpResponseRedirect
  5. from django.shortcuts import render, redirect, get_object_or_404
  6. from django.contrib.auth import authenticate
  7. from django.contrib.auth import login as auth_login
  8. from django.contrib.auth.forms import UserCreationForm
  9. from django.contrib.auth.models import User
  10. from django.forms import formset_factory
  11. from django.forms import BaseFormSet
  12. import datetime
  13.  
  14. class BaseArticleFormSet(BaseFormSet):
  15. def add_fields(self, form, index):
  16. super(BaseArticleFormSet, self).add_fields(form, index)
  17. form.fields["my_field"] = forms.CharField()
  18.  
  19. # Create your views here.
  20. def home(request):
  21. return render(request, 'cook_app/home.html', {})
  22. #get_recipe_structure is a help method that takes in the ammount of serving and the key of a recipe and then returns all the information needed to create a template for a recipe
  23. def get_recipe_structure(recipe_pk, servings):
  24. #gets the recipe based on the id
  25. recipe = Recipe.objects.get(id=recipe_pk)
  26. #sets name to the title so that we can easily send it back
  27. name = recipe.title
  28. #gets the owner of the recipe
  29. owner = RecipeOwner.objects.get(recipe__id=recipe_pk).owner.username
  30. ingredient_structure = []
  31. #gets all of the ingredients for the recipe
  32. recipe_ingredients = RecipeIngredient.objects.filter(recipe__id=recipe_pk)
  33.  
  34. ingredient_tuples = []
  35. for recipe_ingredient in recipe_ingredients:
  36. #gets the IngredientUnitToCal object based on the ingredient and unit keys
  37. converter = IngredientUnitToCal.objects.get(ingredient=recipe_ingredient.ingredient, unit=recipe_ingredient.unit)
  38. #puts the ingredient into the touple we will use later, where recipe_Ingredient and the IngredientUnitToCal are the touple
  39. ingredient_tuples.append((recipe_ingredient,converter))
  40. #intializes values
  41. cal = 0
  42. cal_per_serving = 0
  43. #loops over the tuples
  44. for ingredient_tuple in ingredient_tuples:
  45. #takes out each part of the touple
  46. recipe_ingredient = ingredient_tuple[0]
  47. ingred_unit_cal = ingredient_tuple[1]
  48. #assert ingredient name and unit to variables
  49. ingredient_name = recipe_ingredient.ingredient.name
  50. ingredient_unit = recipe_ingredient.unit.unit
  51. #checks if we have intialized the amount of calories the unit has
  52. if(ingred_unit_cal.ingredient_unit_to_calories != None):
  53. #if we have we mutiply servings with the calorie ammount so it can be sent
  54. ingredient_calories = ingred_unit_cal.ingredient_unit_to_calories*servings
  55. else:
  56. #else we send nothing
  57. ingredient_calories = None
  58. #we calculate how many ingredients we need
  59. ingredient_amount = recipe_ingredient.quantity_per_serving*servings
  60. # we save all the values we need
  61. ingredient = {"name":ingredient_name,"amount":ingredient_amount,"unit":ingredient_unit,"calories":ingredient_calories}
  62. #and append it to the structure
  63. ingredient_structure.append(ingredient)
  64. #aslong as we have a value add it to the sum
  65. if(ingredient_calories != None):
  66. #sum without servings
  67. cal += ingredient_calories/servings
  68. #sum with servings
  69. cal_per_serving += ingredient_calories
  70.  
  71. recipe = {"name":name,"owner":owner,"servings":servings,"ingredients":ingredient_structure,"calories":cal,"calories_per_serving":cal_per_serving}
  72. return recipe
  73.  
  74. def create_user(request):
  75. if request.method == "POST":
  76. form = UserCreationForm(request.POST)
  77. if form.is_valid():
  78. username = form.cleaned_data["username"]
  79. password = form.cleaned_data["password1"]
  80. new_user = User.objects.create_user(username=username, password=password)
  81. new_user = authenticate(username=username, password=password)
  82. if new_user:
  83. auth_login(request, new_user)
  84. return redirect('home')
  85. else:
  86. form = UserCreationForm()
  87.  
  88. return render(request, 'cook_app/create_user.html', {'form': form})
  89.  
  90. #dynamic_form_view is where we add more ingredients dynamically
  91. def dynamic_form_view(request):
  92. IngredientFormSet = formset_factory(RecipeIngredientForm)
  93. #if we send a post
  94. if request.method == "POST":
  95. recipe_form = RecipeForm(request.POST,prefix="recipe")
  96. ingredient_formset = IngredientFormSet(request.POST,prefix="ingredients")
  97. if recipe_form.is_valid():
  98. # create recipe
  99. recipe_name = recipe_form.cleaned_data["recipe_name"]
  100. recipe, created = Recipe.objects.get_or_create(title=recipe_name)
  101. recipe.save()
  102. # create recipe owner
  103. user = request.user
  104. description = recipe_form.cleaned_data["description"]
  105. recipe_owner = RecipeOwner(description=description, owner=user, recipe=recipe)
  106. recipe_owner.save()
  107. # save number of servings
  108. servings = recipe_form.cleaned_data["servings"]
  109. if ingredient_formset.is_valid():
  110. for form in ingredient_formset:
  111. # create and save the ingredient
  112. ingredient_name = form.cleaned_data["ingredient_name"]
  113. ingredient, created = Ingredient.objects.get_or_create(name=ingredient_name)
  114. ingredient.save()
  115. # create and save the unit
  116. unit = form.cleaned_data["unit"]
  117. # get or create unit-cal info on these
  118. unit_cal, created = IngredientUnitToCal.objects.get_or_create(ingredient = ingredient, unit=unit)
  119. unit_cal.save()
  120. # get or create recipe ingredient
  121. quantity_per_serving = form.cleaned_data["amount"]/servings
  122. recipeIngredient = RecipeIngredient(ingredient=ingredient, recipe=recipe, unit=unit, quantity_per_serving=quantity_per_serving)
  123. recipeIngredient.save()
  124. return redirect('home')
  125. else:
  126. recipe_form = RecipeForm(prefix="recipe")
  127. ingredient_formset = IngredientFormSet(prefix="ingredients")
  128. return render(request, 'cook_app/dynamic_form.html', {'recipe_form' : recipe_form , 'ingredient_formset': ingredient_formset})
  129. #shows all the recipes
  130. def recipes_view(request):
  131. #gets all the recipes
  132. recipes = Recipe.objects.all()
  133. #sends them to html
  134. return render(request, 'cook_app/recipes.html', {'recipes' : recipes})
  135. #this is when we click on a recipe from the recipe list
  136. def recipe_details(request, pk):
  137. servings=1
  138. #post means that we have changed the ammount of servings
  139. if request.method == "POST":
  140. serving_form = ServingsForm(request.POST)
  141. if serving_form.is_valid():
  142. #you should not be able to have servings be less than 0 so if it is we set it to 1, otherwise we let it be what you wanted it to be
  143. if(serving_form.cleaned_data['servings'] <= 0):
  144. servings = 1
  145. else:
  146. servings=serving_form.cleaned_data['servings']
  147. comment_form = CommentForm(request.POST)
  148. #if we have sent in a correct comment
  149. if comment_form.is_valid():
  150. #set the correct values and saves it to the database
  151. title = comment_form.cleaned_data["title"]
  152. comment = comment_form.cleaned_data["comment"]
  153. user = request.user
  154. recipe = Recipe.objects.get(id=pk)
  155. date = datetime.datetime.now()
  156. comment_object = RecipeComment(title=title, comment=comment, recipe=recipe, author=user, published_date=date)
  157. comment_object.save()
  158. else:
  159. print("it's not valid!")
  160. #gets the structure of the template based on servings
  161. recipe_structure = get_recipe_structure(pk, servings)
  162. #gets the commentform
  163. comment_form = CommentForm()
  164. #sets the serving forms servings to what you chose or otherwise 1
  165. serving_form = ServingsForm(initial={'servings': servings})
  166. #gets all the comments ordered by their publish date
  167. comments = RecipeComment.objects.filter(recipe__title=recipe_structure["name"]).order_by("published_date")
  168. return render(request, 'cook_app/recipe_details.html', {"pk":pk,"comments":comments,'comment_form':comment_form,'serving_form':serving_form,"recipe_structure":recipe_structure})
  169. #this is used to get all the recipes that the user has saved
  170. def history_view(request):
  171. #creates a list of all the UserHistory objects that have the same user as the current user
  172. history = UserHistory.objects.filter(owner=request.user)
  173. #sends that list to the renderer
  174. return render(request, 'cook_app/history.html', {"history":history})
  175.  
  176. #this is used to get a list of all Ingredients which units have yet to be defined
  177. def ingredient_list(request):
  178. #gets all the ingredeients that have to calorie count
  179. ingredients = IngredientUnitToCal.objects.filter(ingredient_unit_to_calories=None)
  180. return render(request, 'cook_app/ingredient_list.html', {'ingredients' : ingredients})
  181.  
  182. #add_specific_ingredient is where you set the calorie count of an ingredient without a calorie count
  183. def add_specific_ingredient(request,pk):
  184. #get the ingredientUnitToCal based on the pk sent in the url
  185. ingredient_unit = get_object_or_404(IngredientUnitToCal, pk=pk)
  186. #set the ingredient name unit and ingredient so we can send it
  187. ingredient_name = ingredient_unit.ingredient.name
  188. unit = ingredient_unit.unit.unit
  189. ingredient = (ingredient_name,unit)
  190. #if you post it means you have given a calorie count and we should save it to the database
  191. if request.method == "POST":
  192. form = SpecificCalorieForm(request.POST)
  193. if form.is_valid():
  194. kcal = form.cleaned_data['calories']
  195. ingredient_unit.initialized = True
  196. ingredient_unit.ingredient_unit_to_calories = kcal
  197. ingredient_unit.save()
  198. return redirect('ingredient_list')
  199. else:
  200. form = SpecificCalorieForm(initial={'ingredient_name':ingredient_name,'unit':unit})
  201. return render(request, 'cook_app/add_specific_ingredient.html', {"form":form, "ingredient":ingredient})
  202.  
  203. #this is used to create a new ingredient that is not (yet) used in a recipe
  204. def add_ingredient(request):
  205. #gets the ammount of uninitialized ingredients
  206. unlogged_ingredients = IngredientUnitToCal.objects.filter(initialized=False).count()
  207. saved = False
  208. if request.method == "POST":
  209. saved = True
  210. #if it is valid we create a new ingredient
  211. form = CalorieForm(request.POST)
  212. if form.is_valid():
  213. kcal = form.cleaned_data['calories']
  214. unit = form.cleaned_data['unit']
  215. ingredient_name = form.cleaned_data['ingredient_name']
  216. ingredient, created = Ingredient.objects.get_or_create(name=ingredient_name)
  217. ingredient_unit, created = IngredientUnitToCal.objects.get_or_create(ingredient = ingredient, unit=unit)
  218. ingredient_unit.initialized = True
  219. ingredient_unit.ingredient_unit_to_calories = kcal
  220. ingredient_unit.save()
  221. form = CalorieForm()
  222. else:
  223. form = CalorieForm()
  224. return render(request, 'cook_app/add_ingredient.html', {"form":form, "saved":saved, "unlogged_ingredients":unlogged_ingredients})
  225.  
  226. #this view is used to save a recipe so that you can view it later
  227. def save(request, servings, recipe):
  228. #gets the date and current user
  229. date = datetime.datetime.now()
  230. user = request.user
  231. #gets the recipe from the title
  232. recipe = get_object_or_404(Recipe,title=recipe)
  233. #creates the history object
  234. history, created = UserHistory.objects.get_or_create(
  235. created_date=date,
  236. servings=servings,
  237. owner = user,
  238. recipe=recipe)
  239. history.save()
  240. return redirect('home')
  241.  
  242. #this view is used to see one of your history objects
  243. def history_details(request, pk):
  244. history = get_object_or_404(UserHistory, pk=pk)
  245. recipe_structure = get_recipe_structure(history.recipe.pk, history.servings)
  246. created_date = history.created_date
  247. recipe_structure["created_date"] = created_date
  248. return render(request, 'cook_app/history_details.html', {"recipe_structure":recipe_structure})
  249.  
  250.  
  251. #resets the database by deleting all things from the database and then populates the database
  252. def reset_database(request):
  253. #deletes all the objects
  254. Unit.objects.all().delete()
  255. Recipe.objects.all().delete()
  256. RecipeOwner.objects.all().delete()
  257. RecipeIngredient.objects.all().delete()
  258. IngredientUnitToCal.objects.all().delete()
  259. Ingredient.objects.all().delete()
  260. #populates the database
  261. units = ["dl","g","pieces","l","teaspoon","pinch","tablespoon","cup"]
  262.  
  263. for unit in units:
  264. unit_model = Unit(unit=unit)
  265. unit_model.save()
  266.  
  267. ingredients = [
  268. {"name":"milk","unit":"dl","cal":42},
  269. {"name":"butter","unit":"g","cal":190},
  270. {"name":"flour","unit":"dl","cal":30},
  271. {"name":"sugar","unit":"tablespoon","cal":30},
  272. {"name":"egg","unit":"pieces","cal":78},
  273. {"name":"void shard","unit":"pinch","cal":None}
  274. ]
  275.  
  276. for ingredient in ingredients:
  277. ingredient_model = Ingredient(name=ingredient["name"])
  278. ingredient_model.save()
  279. unit = ingredient["unit"]
  280. unit_model = Unit.objects.get(unit=unit)
  281. converter = IngredientUnitToCal(
  282. ingredient=ingredient_model,
  283. unit=unit_model,
  284. ingredient_unit_to_calories=ingredient["cal"]
  285. )
  286. converter.save()
  287.  
  288. recipe = Recipe(title="Wonderful Cookie")
  289. recipe.save()
  290. for i in range(0,3):
  291. ingredient = ingredients[i]
  292. ingredient_model = Ingredient.objects.get(name=ingredient["name"])
  293. unit = Unit.objects.get(unit=ingredient["unit"])
  294. amount = i*7+5
  295. recipe_ingredient = RecipeIngredient(
  296. quantity_per_serving=amount,
  297. recipe=recipe,
  298. ingredient=ingredient_model,
  299. unit=unit
  300. )
  301. recipe_ingredient.save()
  302.  
  303. owner = RecipeOwner(
  304. description="A wonderful cookie, for the entire family",
  305. recipe = recipe,
  306. owner = request.user
  307. )
  308. owner.save()
  309.  
  310. recipe = Recipe(title="Magnificent Cake")
  311. recipe.save()
  312. for i in range(3,6):
  313. ingredient = ingredients[i]
  314. ingredient_model = Ingredient.objects.get(name=ingredient["name"])
  315. unit = Unit.objects.get(unit=ingredient["unit"])
  316. amount = i*6+8
  317. recipe_ingredient = RecipeIngredient(
  318. quantity_per_serving=amount,
  319. recipe=recipe,
  320. ingredient=ingredient_model,
  321. unit=unit
  322. )
  323. recipe_ingredient.save()
  324.  
  325. owner = RecipeOwner(
  326. description="If patrick has read my comments this won't be here",
  327. recipe = recipe,
  328. owner = request.user
  329. )
  330. owner.save()
  331. return redirect('home')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement