Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Move ajax_get_ingredient_values method to API

Roland Geider781d405c1cf4
diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.py
index d3833f172..0de304346 100644
--- a/wger/nutrition/api/views.py
+++ b/wger/nutrition/api/views.py
@@ -16,10 +16,12 @@
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
from rest_framework import viewsets
-from rest_framework.decorators import link, api_view
+from rest_framework.decorators import link
+from rest_framework.decorators import api_view
from rest_framework.response import Response
from wger.nutrition.api.serializers import NutritionPlanSerializer
+from wger.nutrition.forms import UnitChooserForm
from wger.nutrition.models import Ingredient
from wger.nutrition.models import Meal
@@ -27,8 +29,8 @@ from wger.nutrition.models import MealItem
from wger.nutrition.models import WeightUnit
from wger.nutrition.models import IngredientWeightUnit
from wger.nutrition.models import NutritionPlan
-from wger.utils.language import load_ingredient_languages
+from wger.utils.language import load_ingredient_languages
from wger.utils.viewsets import WgerOwnerObjectModelViewSet
@@ -54,6 +56,49 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):
'license',
'license_author')
+ @link()
+ def get_values(self, request, pk):
+ '''
+ Calculates the nutritional values for current ingredient and
+ the given amount and unit.
+
+ This function basically just performs a multiplication (in the model), and
+ is a candidate to be moved to pure AJAX calls, however doing it like this
+ keeps the logic nicely hidden and respects the DRY principle.
+ '''
+
+ result = {'energy': 0,
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'carbohydrates_sugar': 0,
+ 'fat': 0,
+ 'fat_saturated': 0,
+ 'fibres': 0,
+ 'sodium': 0,
+ 'errors': []}
+ ingredient = self.get_object()
+
+ form = UnitChooserForm(request.GET)
+
+ if form.is_valid():
+
+ # Create a temporary MealItem object
+ if form.cleaned_data['unit']:
+ unit_id = form.cleaned_data['unit'].id
+ else:
+ unit_id = None
+
+ item = MealItem()
+ item.ingredient = ingredient
+ item.weight_unit_id = unit_id
+ item.amount = form.cleaned_data['amount']
+
+ result = item.get_nutritional_values()
+ else:
+ result['errors'] = form.errors
+
+ return Response(result)
+
@api_view(['GET'])
def search(request):
diff --git a/wger/nutrition/static/js/nutrition.js b/wger/nutrition/static/js/nutrition.js
index 44f2d7cd4..2c76f0891 100644
--- a/wger/nutrition/static/js/nutrition.js
+++ b/wger/nutrition/static/js/nutrition.js
@@ -23,7 +23,7 @@
function update_ingredient_value(url)
{
var form_data = $('#nutritional-values-form').serializeArray();
- $.post(url, form_data, function(data) {
+ $.get(url, form_data, function(data) {
// Show any validation errors
$('#calculator-errors').html('');
diff --git a/wger/nutrition/templates/ingredient/view.html b/wger/nutrition/templates/ingredient/view.html
index c342c7847..dd21a703b 100644
--- a/wger/nutrition/templates/ingredient/view.html
+++ b/wger/nutrition/templates/ingredient/view.html
@@ -8,7 +8,7 @@
{% block header %}
<script>
$(document).ready(function() {
- init_ingredient_detail("{% url 'ingredient-get-values' ingredient.id %}");
+ init_ingredient_detail("{% url 'api-ingredient-get-values' ingredient.id %}");
});
</script>
{% endblock %}
@@ -63,11 +63,10 @@ the search.{% endblocktrans %}
<meta itemprop="name" content="{{ingredient.name}}" />
<form class="form-horizontal"
- method="post"
- action="{% url 'ingredient-get-values' ingredient.id %}"
+ method="GET"
+ action="{% url 'api-ingredient-get-values' ingredient.id %}"
id="nutritional-values-form"
style="background-color: transparent; border-width: 0px; box-shadow: 0px 0px 0px 0px transparent;">
- {% csrf_token %}
<div id="calculator-errors"></div>
<input type="hidden" value="{{ingredient.id}}" name="ingredient">
diff --git a/wger/nutrition/templates/mobile/ingredient/view.html b/wger/nutrition/templates/mobile/ingredient/view.html
index f5b29942a..388de6286 100644
--- a/wger/nutrition/templates/mobile/ingredient/view.html
+++ b/wger/nutrition/templates/mobile/ingredient/view.html
@@ -8,7 +8,7 @@
{% block header %}
<script>
$(document).on('pageinit', function(){
- init_ingredient_detail("{% url 'ingredient-get-values' ingredient.id %}");
+ init_ingredient_detail("{% url 'api-ingredient-get-values' ingredient.id %}");
});
</script>
{% endblock %}
@@ -66,11 +66,10 @@ the search.{% endblocktrans %}
<div itemscope itemtype="http://schema.org/NutritionInformation">
<meta itemprop="name" content="{{ingredient.name}}" />
-<form method="post"
- action="{% url 'ingredient-get-values' ingredient.id %}"
+<form method="GET"
+ action="{% url 'api-ingredient-get-values' ingredient.id %}"
id="nutritional-values-form"
style="background-color: transparent; border-width: 0px; box-shadow: 0px 0px 0px 0px transparent;">
- {% csrf_token %}
<div id="calculator-errors" class="ym-error"></div>
<input type="hidden" value="{{ingredient.id}}" name="ingredient"></input>
diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.py
index ce91b3ed1..79ae9fdaa 100644
--- a/wger/nutrition/tests/test_ingredient.py
+++ b/wger/nutrition/tests/test_ingredient.py
@@ -210,10 +210,10 @@ class IngredientValuesTestCase(WorkoutManagerTestCase):
'''
# Get the nutritional values in 1 gram of product
- response = self.client.post(reverse('ingredient-get-values', kwargs={'pk': 1}),
- {'amount': 1,
- 'ingredient': 1,
- 'unit': ''})
+ response = self.client.get(reverse('api-ingredient-get-values', kwargs={'pk': 1}),
+ {'amount': 1,
+ 'ingredient': 1,
+ 'unit': ''})
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
@@ -228,10 +228,10 @@ class IngredientValuesTestCase(WorkoutManagerTestCase):
u'carbohydrates': u'0.00'})
# Get the nutritional values in 1 unit of product
- response = self.client.post(reverse('ingredient-get-values', kwargs={'pk': 1}),
- {'amount': 1,
- 'ingredient': 1,
- 'unit': 2})
+ response = self.client.get(reverse('api-ingredient-get-values', kwargs={'pk': 1}),
+ {'amount': 1,
+ 'ingredient': 1,
+ 'unit': 2})
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.py
index f87e67b27..f220e9a10 100644
--- a/wger/nutrition/urls.py
+++ b/wger/nutrition/urls.py
@@ -96,9 +96,6 @@ urlpatterns = patterns('wger.nutrition.views',
url(r'^ingredient/(?P<id>\d+)/view/(?P<slug>[-\w]+)/$',
ingredient.view,
name='ingredient-view'),
- url(r'^ingredient/(?P<pk>\d+)/get-nutritional-values$',
- ingredient.ajax_get_ingredient_values,
- name='ingredient-get-values'),
# Ingredient units
url(r'^ingredient/unit/list/$',
diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.py
index 83b45d5ef..38cbfbd1c 100644
--- a/wger/nutrition/views/ingredient.py
+++ b/wger/nutrition/views/ingredient.py
@@ -14,20 +14,16 @@
#
# You should have received a copy of the GNU Affero General Public License
import logging
-import json
from django.shortcuts import render
from django.shortcuts import get_object_or_404
-from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseForbidden
from django.core import mail
-from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.core.cache import cache
from django.contrib.auth.decorators import permission_required
-from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
@@ -37,10 +33,7 @@ from django.views.generic import UpdateView
from django.views.generic import ListView
from wger.nutrition.forms import UnitChooserForm
-from wger.nutrition.models import MealItem
from wger.nutrition.models import Ingredient
-from wger.nutrition.models import IngredientWeightUnit
-from wger.utils import helpers
from wger.utils.generic_views import WgerPermissionMixin
from wger.utils.generic_views import WgerFormMixin
from wger.utils.generic_views import WgerDeleteMixin
@@ -221,43 +214,3 @@ def decline(request, pk):
ingredient.save()
messages.success(request, _('Ingredient was successfully marked as rejected'))
return HttpResponseRedirect(ingredient.get_absolute_url())
-
-
-def ajax_get_ingredient_values(request, pk):
- '''
- Calculates the nutritional values for the given amount and exercise
- '''
-
- result = {'energy': 0,
- 'protein': 0,
- 'carbohydrates': 0,
- 'carbohydrates_sugar': 0,
- 'fat': 0,
- 'fat_saturated': 0,
- 'fibres': 0,
- 'sodium': 0,
- 'errors': []}
- ingredient = get_object_or_404(Ingredient, pk=pk)
-
- if request.method == 'POST':
- form = UnitChooserForm(request.POST)
-
- if form.is_valid():
-
- # Create a temporary MealItem object
- if form.cleaned_data['unit']:
- unit_id = form.cleaned_data['unit'].id
- else:
- unit_id = None
-
- item = MealItem()
- item.ingredient = ingredient
- item.weight_unit_id = unit_id
- item.amount = form.cleaned_data['amount']
-
- result = item.get_nutritional_values()
- else:
- result['errors'] = form.errors
-
- return HttpResponse(json.dumps(result, cls=helpers.DecimalJsonEncoder),
- 'application/json')