Skip to content

Commit

Permalink
feat(add meals): add meals to nutrition plan
Browse files Browse the repository at this point in the history
- add endpoint for creating a meal
- create a single form for adding meal items
- redirect to the page for adding meal items immediately after
creating a meal.

[Finishes #166185773]
  • Loading branch information
richien committed Jun 21, 2019
1 parent dcea3fb commit b6cd6b3
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 24 deletions.
34 changes: 34 additions & 0 deletions wger/nutrition/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
MealItem,
Meal,
Ingredient,
NutritionPlan,
)


Expand Down Expand Up @@ -87,3 +88,36 @@ class IngredientSerializer(serializers.ModelSerializer):

class Meta:
model = Ingredient


class MealMealItemSerializer(serializers.ModelSerializer):

class Meta:
model = MealItem

def validate(self, data):
plan_id = self.initial_data.get('plan_id')
time = self.initial_data.get('time')
order = 1

plan = NutritionPlan.objects.get(id=plan_id)

meal = Meal(
order=order,
plan=plan,
time=time
)
meal.save()

data.update(
{
"meal": meal,
"order": order
}
)
return data

def create(self, validated_data):
meal_item = MealItem(**validated_data)
meal_item.save()
return validated_data
15 changes: 15 additions & 0 deletions wger/nutrition/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
from rest_framework.decorators import detail_route
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from wger.nutrition.api.serializers import (
NutritionPlanSerializer,
Expand All @@ -27,6 +30,7 @@
MealItemSerializer,
MealSerializer,
IngredientSerializer,
MealMealItemSerializer
)
from wger.nutrition.forms import UnitChooserForm
from wger.nutrition.models import (
Expand Down Expand Up @@ -275,3 +279,14 @@ def nutritional_values(self, request, pk):
Return an overview of the nutritional plan's values
"""
return Response(MealItem.objects.get(pk=pk).get_nutritional_values())


class MealMealItemView(APIView):

serializer_class = MealMealItemSerializer

def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
3 changes: 2 additions & 1 deletion wger/nutrition/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ class MealItemForm(forms.ModelForm):
required=False,
)
ingredient = forms.ModelChoiceField(
queryset=Ingredient.objects.all(), widget=forms.HiddenInput
queryset=Ingredient.objects.all(),
widget=forms.HiddenInput
)

class Meta:
Expand Down
57 changes: 57 additions & 0 deletions wger/nutrition/templates/meal_item/add.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{% extends "base.html" %}
{% load i18n %}
{% load staticfiles %}
{% load wger_extras %}


{% block title %}{% trans "Add a meal" %}{% endblock %}


{% block header %}
<script type="text/javascript">
$(document).ready(function() {
// Init the autocompleter
wgerInitIngredientAutocompleter();
});
</script>
{% endblock %}


-
-
{% block content %}
<form action="{{ form_action }}"
method="post"
class="form-horizontal">
{% csrf_token %}
{% render_form_errors form %}
<div class="form-group">
{% comment %} <label for="time-field">Time (approx) - Optional</label> {% endcomment %}

<div class="col-md-3"><label for="time-field">Time (approx) - Optional</label></div>
<div class="col-md-9" >
<input type="time" id="time-field" name="time-field"
min="9:00" max="18:00"
class="form-control">
</div>
</div>
<div style="display: None;">{{form.ingredient}}</div>
<div class="form-group {% if field.errors %}has-error{% endif %}" id="form-id_ingredient_searchfield">
<label for="id_ingredient_searchfield" class="col-md-3 control-label">
{% trans "Ingredient name" %}
</label>

<div class="col-md-9">
<input type="text"
id="id_ingredient_searchfield"
name="ingredient_searchfield"
value="{{ingredient_searchfield}}"
class="form-control">
<div id="exercise_name"></div>
</div>
</div>
{% render_form_field form.amount %}
{% render_form_field form.weight_unit %}
{% render_form_submit submit_text %}
</form>
{% endblock %}
4 changes: 2 additions & 2 deletions wger/nutrition/templates/meal_item/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
{% endblock %}




-
-
{% block content %}
<form action="{{ form_action }}"
method="post"
Expand Down
19 changes: 6 additions & 13 deletions wger/nutrition/tests/test_meal.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,15 @@
WorkoutManagerTestCase,
WorkoutManagerEditTestCase,
WorkoutManagerAddTestCase,
get_reverse
)
from wger.nutrition.models import Meal
from wger.nutrition.models import Meal, MealItem
from wger.nutrition.models import NutritionPlan

from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient


class MealRepresentationTestCase(WorkoutManagerTestCase):
"""
Expand All @@ -50,18 +55,6 @@ class EditMealTestCase(WorkoutManagerEditTestCase):
data = {"time": datetime.time(8, 12)}


class AddMealTestCase(WorkoutManagerAddTestCase):
"""
Tests adding a Meal
"""

object_class = Meal
url = reverse("nutrition:meal:add", kwargs={"plan_pk": 4})
data = {"time": datetime.time(9, 2)}
user_success = "test"
user_fail = "admin"


class PlanOverviewTestCase(WorkoutManagerTestCase):
"""
Tests the nutrition plan overview
Expand Down
48 changes: 40 additions & 8 deletions wger/nutrition/views/meal.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
#
# You should have received a copy of the GNU Affero General Public License
import logging
import json
import requests
import os

from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponseForbidden
Expand All @@ -23,8 +26,11 @@

from django.views.generic import CreateView, UpdateView

from wger.nutrition.models import NutritionPlan, Meal
from wger.nutrition.models import NutritionPlan, Meal, MealItem
from wger.utils.generic_views import WgerFormMixin
# from wger.nutrition.views.meal_item import MealItemCreateView
from wger.nutrition.forms import MealItemForm


logger = logging.getLogger(__name__)

Expand All @@ -39,18 +45,40 @@ class MealCreateView(WgerFormMixin, CreateView):
Generic view to add a new meal to a nutrition plan
"""

model = Meal
fields = "__all__"
model = MealItem
title = ugettext_lazy("Add new meal")
owner_object = {"pk": "plan_pk", "class": NutritionPlan}
form_class = MealItemForm
template_name = "meal_item/add.html"

def form_valid(self, form):
plan = get_object_or_404(
NutritionPlan, pk=self.kwargs["plan_pk"], user=self.request.user
time = self.request.POST["time-field"]
if time == '':
time = None
amount = self.request.POST['amount']
ingredient = self.request.POST['ingredient']
weight_unit = self.request.POST['weight_unit']
plan_id = self.kwargs['plan_pk']

url = os.environ.get("MEAL_MEALITEM_URL")
payload = {
"time": time,
"amount": amount,
"ingredient": ingredient,
"weight_unit": weight_unit,
"plan_id": plan_id
}
headers = {"content-type": "application/json"}
requests.post(
url,
data=json.dumps(payload),
headers=headers
)

return HttpResponseRedirect(
reverse("nutrition:plan:view",
kwargs={"id": plan_id})
)
form.instance.plan = plan
form.instance.order = 1
return super(MealCreateView, self).form_valid(form)

def get_success_url(self):
return self.object.plan.get_absolute_url()
Expand All @@ -61,6 +89,10 @@ def get_context_data(self, **kwargs):
context["form_action"] = reverse(
"nutrition:meal:add", kwargs={"plan_pk": self.kwargs["plan_pk"]}
)
context["plan_id"] = self.kwargs["plan_pk"]
context["ingredient_searchfield"] = self.request.POST.get(
"ingredient_searchfield", ""
)

return context

Expand Down
1 change: 1 addition & 0 deletions wger/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@
name="ingredient-search",
),
url(r"^api/v2/", include(router.urls)),
url(r"api/v2/meal-mealitem", nutrition_api_views.MealMealItemView.as_view())
]

#
Expand Down

0 comments on commit b6cd6b3

Please sign in to comment.