Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Calculate the nutritional values on the ingredient page

Roland Geiderdbefc8647af3
diff --git a/wger/nutrition/migrations/0004_rename_amount_gramm.py b/wger/nutrition/migrations/0004_rename_amount_gramm.py
index e98c6ad45..48f941728 100644
--- a/wger/nutrition/migrations/0004_rename_amount_gramm.py
+++ b/wger/nutrition/migrations/0004_rename_amount_gramm.py
@@ -87,7 +87,7 @@ class Migration(SchemaMigration):
},
'nutrition.mealitem': {
'Meta': {'object_name': 'MealItem'},
- 'amount_gramm': ('django.db.models.fields.DecimalField', [], {'max_digits': '6', 'decimal_places': '2'}),
+ 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '6', 'decimal_places': '2'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ingredient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.Ingredient']"}),
'meal': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.Meal']"}),
diff --git a/wger/nutrition/migrations/0005_auto__chg_field_ingredient_sodium__chg_field_ingredient_carbohydrates_.py b/wger/nutrition/migrations/0005_auto__chg_field_ingredient_sodium__chg_field_ingredient_carbohydrates_.py
new file mode 100644
index 000000000..a3d7718ae
--- /dev/null
+++ b/wger/nutrition/migrations/0005_auto__chg_field_ingredient_sodium__chg_field_ingredient_carbohydrates_.py
@@ -0,0 +1,153 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+
+ # Changing field 'Ingredient.sodium'
+ db.alter_column('nutrition_ingredient', 'sodium', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=5, decimal_places=2))
+
+ # Changing field 'Ingredient.carbohydrates'
+ db.alter_column('nutrition_ingredient', 'carbohydrates', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=2))
+
+ # Changing field 'Ingredient.fat'
+ db.alter_column('nutrition_ingredient', 'fat', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=2))
+
+ # Changing field 'Ingredient.carbohydrates_sugar'
+ db.alter_column('nutrition_ingredient', 'carbohydrates_sugar', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=5, decimal_places=2))
+
+ # Changing field 'Ingredient.fat_saturated'
+ db.alter_column('nutrition_ingredient', 'fat_saturated', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=5, decimal_places=2))
+
+ # Changing field 'Ingredient.fibres'
+ db.alter_column('nutrition_ingredient', 'fibres', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=5, decimal_places=2))
+
+ # Changing field 'Ingredient.protein'
+ db.alter_column('nutrition_ingredient', 'protein', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=2))
+
+ def backwards(self, orm):
+
+ # Changing field 'Ingredient.sodium'
+ db.alter_column('nutrition_ingredient', 'sodium', self.gf('django.db.models.fields.FloatField')(null=True))
+
+ # Changing field 'Ingredient.carbohydrates'
+ db.alter_column('nutrition_ingredient', 'carbohydrates', self.gf('django.db.models.fields.FloatField')())
+
+ # Changing field 'Ingredient.fat'
+ db.alter_column('nutrition_ingredient', 'fat', self.gf('django.db.models.fields.FloatField')())
+
+ # Changing field 'Ingredient.carbohydrates_sugar'
+ db.alter_column('nutrition_ingredient', 'carbohydrates_sugar', self.gf('django.db.models.fields.FloatField')(null=True))
+
+ # Changing field 'Ingredient.fat_saturated'
+ db.alter_column('nutrition_ingredient', 'fat_saturated', self.gf('django.db.models.fields.FloatField')(null=True))
+
+ # Changing field 'Ingredient.fibres'
+ db.alter_column('nutrition_ingredient', 'fibres', self.gf('django.db.models.fields.FloatField')(null=True))
+
+ # Changing field 'Ingredient.protein'
+ db.alter_column('nutrition_ingredient', 'protein', self.gf('django.db.models.fields.FloatField')())
+
+ models = {
+ 'auth.group': {
+ 'Meta': {'object_name': 'Group'},
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+ 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+ },
+ 'auth.permission': {
+ 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+ 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+ },
+ 'auth.user': {
+ 'Meta': {'object_name': 'User'},
+ 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+ 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+ 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+ 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+ 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+ },
+ 'contenttypes.contenttype': {
+ 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+ 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+ },
+ 'exercises.language': {
+ 'Meta': {'object_name': 'Language'},
+ 'full_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'short_name': ('django.db.models.fields.CharField', [], {'max_length': '2'})
+ },
+ 'nutrition.ingredient': {
+ 'Meta': {'ordering': "['name']", 'object_name': 'Ingredient'},
+ 'carbohydrates': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),
+ 'carbohydrates_sugar': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}),
+ 'energy': ('django.db.models.fields.IntegerField', [], {}),
+ 'fat': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}),
+ 'fat_saturated': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}),
+ 'fibres': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['exercises.Language']"}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
+ 'protein': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),
+ 'sodium': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'})
+ },
+ 'nutrition.ingredientweightunit': {
+ 'Meta': {'object_name': 'IngredientWeightUnit'},
+ 'amount': ('django.db.models.fields.DecimalField', [], {'default': '1', 'max_digits': '5', 'decimal_places': '2'}),
+ 'gramm': ('django.db.models.fields.IntegerField', [], {}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'ingredient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.Ingredient']"}),
+ 'unit': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.WeightUnit']"})
+ },
+ 'nutrition.meal': {
+ 'Meta': {'ordering': "['time']", 'object_name': 'Meal'},
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'order': ('django.db.models.fields.IntegerField', [], {'max_length': '1', 'blank': 'True'}),
+ 'plan': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.NutritionPlan']"}),
+ 'time': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'})
+ },
+ 'nutrition.mealitem': {
+ 'Meta': {'object_name': 'MealItem'},
+ 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '6', 'decimal_places': '2'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'ingredient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.Ingredient']"}),
+ 'meal': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.Meal']"}),
+ 'order': ('django.db.models.fields.IntegerField', [], {'max_length': '1', 'blank': 'True'}),
+ 'weight_unit': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.IngredientWeightUnit']", 'null': 'True', 'blank': 'True'})
+ },
+ 'nutrition.nutritionplan': {
+ 'Meta': {'ordering': "['-creation_date']", 'object_name': 'NutritionPlan'},
+ 'creation_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+ 'description': ('django.db.models.fields.TextField', [], {'max_length': '2000', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['exercises.Language']"}),
+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
+ },
+ 'nutrition.weightunit': {
+ 'Meta': {'ordering': "['name']", 'object_name': 'WeightUnit'},
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['exercises.Language']"}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})
+ }
+ }
+
+ complete_apps = ['nutrition']
\ No newline at end of file
diff --git a/wger/nutrition/models.py b/wger/nutrition/models.py
index bde8cd365..11870ba7b 100644
--- a/wger/nutrition/models.py
+++ b/wger/nutrition/models.py
@@ -14,7 +14,8 @@
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
-
+import logging
+import decimal
from django.db import models
@@ -30,6 +31,8 @@ from wger.exercises.models import Language
MEALITEM_WEIGHT_GRAM = '1'
MEALITEM_WEIGHT_UNIT = '2'
+logger = logging.getLogger('workout_manager.custom')
+
class NutritionPlan(models.Model):
'''
@@ -74,38 +77,21 @@ class NutritionPlan(models.Model):
'fibres': 0,
'sodium': 0}
for meal in self.meal_set.select_related():
+
+ # Get the calculated values from the meal item and add them
for item in meal.mealitem_set.select_related():
- # Calculate the base weight of the item
- if item.get_unit_type() == MEALITEM_WEIGHT_GRAM:
- item_weight = float(item.amount)
- else:
- item_weight = (float(item.amount) *
- float(item.weight_unit.amount) *
- item.weight_unit.gramm)
-
- nutritional_info['energy'] += item.ingredient.energy * item_weight / 100
- nutritional_info['protein'] += item.ingredient.protein * item_weight / 100
- nutritional_info['carbohydrates'] += item.ingredient.carbohydrates * \
- item_weight / 100
-
- if item.ingredient.carbohydrates_sugar:
- nutritional_info['carbohydrates_sugar'] += \
- item.ingredient.carbohydrates_sugar * \
- item_weight / 100
-
- nutritional_info['fat'] += item.ingredient.fat * item_weight / 100
- if item.ingredient.fat_saturated:
- nutritional_info['fat_saturated'] += item.ingredient.fat_saturated * \
- item_weight / 100
-
- if item.ingredient.fibres:
- nutritional_info['fibres'] += item.ingredient.fibres * \
- item_weight / 100
-
- if item.ingredient.sodium:
- nutritional_info['sodium'] += item.ingredient.sodium * \
- item_weight / 100
+ values = item.get_nutritional_values()
+
+ nutritional_info['energy'] += values['energy']
+ nutritional_info['protein'] += values['protein']
+ nutritional_info['carbohydrates'] += values['carbohydrates']
+ nutritional_info['carbohydrates_sugar'] += values['carbohydrates_sugar']
+ nutritional_info['fat'] += values['fat']
+ nutritional_info['fat_saturated'] += values['fat_saturated']
+ nutritional_info['fibres'] += values['fibres']
+ nutritional_info['sodium'] += values['sodium']
+
return nutritional_info
def get_owner_object(self):
@@ -132,32 +118,45 @@ class Ingredient(models.Model):
energy = models.IntegerField(verbose_name=_('Energy'),
help_text=_('In kcal per 100g'))
- protein = models.FloatField(verbose_name=_('Protein'),
+ protein = models.DecimalField(decimal_places=2,
+ max_digits=5,
+ verbose_name=_('Protein'),
help_text=_('In g per 100g of product'))
- carbohydrates = models.FloatField(verbose_name=_('Carbohydrates'),
+ carbohydrates = models.DecimalField(decimal_places=2,
+ max_digits=5,
+ verbose_name=_('Carbohydrates'),
help_text=_('In g per 100g of product'))
- carbohydrates_sugar = models.FloatField(blank=True,
+ carbohydrates_sugar = models.DecimalField(decimal_places=2,
+ max_digits=5,
+ blank=True,
null=True,
verbose_name=_('Sugar content in carbohydrates'),
help_text=_('In g per 100g of product'))
- fat = models.FloatField(blank=True,
+ fat = models.DecimalField(decimal_places=2,
+ max_digits=5,
+ blank=True,
verbose_name=_('Fat'),
help_text=_('In g per 100g of product'))
- fat_saturated = models.FloatField(blank=True,
+ fat_saturated = models.DecimalField(decimal_places=2,
+ max_digits=5,blank=True,
null=True,
verbose_name=_('Saturated fat content in fats'),
help_text=_('In g per 100g of product'))
- fibres = models.FloatField(blank=True,
+ fibres = models.DecimalField(decimal_places=2,
+ max_digits=5,
+ blank=True,
null=True,
verbose_name=_('Fibres'),
help_text=_('In g per 100g of product'))
- sodium = models.FloatField(blank=True,
+ sodium = models.DecimalField(decimal_places=2,
+ max_digits=5,
+ blank=True,
null=True,
verbose_name=_('Sodium'),
help_text=_('In g per 100g of product'))
@@ -307,3 +306,48 @@ class MealItem(models.Model):
return MEALITEM_WEIGHT_UNIT
else:
return MEALITEM_WEIGHT_GRAM
+
+ def get_nutritional_values(self):
+ '''
+ Sum the nutrional info
+ '''
+ nutritional_info = {'energy': 0,
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'carbohydrates_sugar': 0,
+ 'fat': 0,
+ 'fat_saturated': 0,
+ 'fibres': 0,
+ 'sodium': 0}
+ # Calculate the base weight of the item
+ if self.get_unit_type() == MEALITEM_WEIGHT_GRAM:
+ item_weight = self.amount
+ else:
+ item_weight = (self.amount *
+ self.weight_unit.amount *
+ self.weight_unit.gramm)
+
+ nutritional_info['energy'] += self.ingredient.energy * item_weight / 100
+ nutritional_info['protein'] += self.ingredient.protein * item_weight / 100
+ nutritional_info['carbohydrates'] += self.ingredient.carbohydrates * \
+ item_weight / 100
+
+ if self.ingredient.carbohydrates_sugar:
+ nutritional_info['carbohydrates_sugar'] += \
+ self.ingredient.carbohydrates_sugar * \
+ item_weight / 100
+
+ nutritional_info['fat'] += self.ingredient.fat * item_weight / 100
+ if self.ingredient.fat_saturated:
+ nutritional_info['fat_saturated'] += self.ingredient.fat_saturated * \
+ item_weight / 100
+
+ if self.ingredient.fibres:
+ nutritional_info['fibres'] += self.ingredient.fibres * \
+ item_weight / 100
+
+ if self.ingredient.sodium:
+ nutritional_info['sodium'] += self.ingredient.sodium * \
+ item_weight / 100
+
+ return nutritional_info
\ No newline at end of file
diff --git a/wger/nutrition/templates/ingredient/view.html b/wger/nutrition/templates/ingredient/view.html
index d428e6114..86ce67d4a 100644
--- a/wger/nutrition/templates/ingredient/view.html
+++ b/wger/nutrition/templates/ingredient/view.html
@@ -6,9 +6,45 @@
{% block title %}{{ingredient.name}}{% endblock %}
+{% block header %}
+<script>
+function update_value() {
+ form_data = $('#nutritional-values-form').serializeArray();
+
+ $.post("{% url 'ingredient-get-values' ingredient.id %}", form_data, function(data) {
+ $('#value-energy').html(parseFloat(data['energy']).toFixed(2));
+ $('#value-protein').html(parseFloat(data['protein']).toFixed(2));
+ $('#value-carbohydrates').html(parseFloat(data['carbohydrates']).toFixed(2));
+ $('#value-carbohydrates-sugar').html(parseFloat(data['carbohydrates_sugar']).toFixed(2));
+ $('#value-fat').html(parseFloat(data['fat']).toFixed(2));
+ $('#value-fat-saturated').html(parseFloat(data['fat_saturated']).toFixed(2));
+ $('#value-fibres').html(parseFloat(data['fibres']).toFixed(2));
+ $('#value-sodium').html(parseFloat(data['sodium']).toFixed(2));
+ });
+ }
+
+$(document).ready(function() {
+
+ // Prevent the form from being sent
+ $('#nutritional-values-form').submit(function(e) {
+ e.preventDefault();
+ });
+
+ $('#id_amount').keyup(function(){
+ update_value();
+ });
+
+ $('#id_unit').change(function(){
+ update_value();
+ });
+
+});
+</script>
+{% endblock %}
+
-{% block content %}
+{% block content %}
<div itemscope itemtype="http://schema.org/NutritionInformation">
<meta itemprop="name" content="{{ingredient.name}}" />
@@ -25,21 +61,27 @@
<tbody>
<tr>
<td style="width:80%;">{% trans "Energy" %}</td>
- <td itemprop="calories">{{ingredient.energy}} kcal</td>
+ <td itemprop="calories">
+ <span id="value-energy">{{ingredient.energy}}</span> kcal
+ </td>
</tr>
<tr>
<td>{% trans "Protein" %}</td>
- <td itemprop="proteinContent">{{ingredient.protein}} g</td>
+ <td itemprop="proteinContent">
+ <span id="value-protein">{{ingredient.protein}}</span> g
+ </td>
</tr>
<tr>
<td>{% trans "Carbohydrates" %}</td>
- <td itemprop="carbohydrateContent">{{ingredient.carbohydrates}} g</td>
+ <td itemprop="carbohydrateContent">
+ <span id="value-carbohydrates">{{ingredient.carbohydrates}}</span> g
+ </td>
</tr>
<tr>
<td style="padding-left: 3em;">{% trans "Sugar content in carbohydrates" %}</td>
<td itemprop="sugarContent">
{% if ingredient.carbohydrates_sugar %}
- {{ingredient.carbohydrates_sugar}} g
+ <span id="value-carbohydrates-sugar">{{ingredient.carbohydrates_sugar}}</span> g
{% else %}
{% trans "n.A." %}
{% endif %}
@@ -47,13 +89,15 @@
</tr>
<tr>
<td>{% trans "Fat" %}</td>
- <td itemprop="fatContent">{{ingredient.fat}} g</td>
+ <td itemprop="fatContent">
+ <span id="value-fat">{{ingredient.fat}}</span> g
+ </td>
</tr>
<tr>
<td style="padding-left: 3em;">{% trans "Saturated fat content in fats" %}</td>
<td itemprop="saturatedFatContent">
{% if ingredient.fat_saturated %}
- {{ingredient.fat_saturated}} g
+ <span id="value-fat-saturated">{{ingredient.fat_saturated}}</span> g
{% else %}
{% trans "n.A." %}
{% endif %}
@@ -73,9 +117,9 @@
<tbody>
<tr>
<td style="width:80%;">{% trans "Fibres" %}</td>
- <td itemprop="fiberContent">
+ <td itemprop="fiberContent" id="value-fibres">
{% if ingredient.fibres %}
- {{ingredient.fibres}} g
+ <span id="value-fibres">{{ingredient.fibres}}</span> g
{% else %}
{% trans "n.A." %}
{% endif %}
@@ -83,9 +127,9 @@
</tr>
<tr>
<td>{% trans "Sodium" %}</td>
- <td itemprop="sodiumContent">
+ <td itemprop="sodiumContent" id="value-sodium">
{% if ingredient.sodium %}
- {{ingredient.sodium}} g
+ <span id="value-fibres">{{ingredient.sodium}}</span> g
{% else %}
{% trans "n.A." %}
{% endif %}
@@ -99,6 +143,20 @@
{% block sidebar %}
+
+<h3>{% trans "Quick calculator" %}</h3>
+<form class="ym-form"
+ method="post"
+ action="{% url 'ingredient-get-values' ingredient.id %}"
+ id="nutritional-values-form">
+ {% csrf_token %}
+ <input type="hidden" value="{{ingredient.id}}" name="ingredient"></input>
+
+ <div class="ym-fbox-text {% if form.amount.errors %}ym-error{% endif %}">{{form.amount}}</div>
+
+ <div class="ym-fbox-select {% if form.unit.errors %}ym-error{% endif %}">{{form.unit}}</div>
+</form>
+
{% if perms.exercises %}
<h3>{% trans "Options" %}</h3>
diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.py
index 09219b092..9ae7b3719 100644
--- a/wger/nutrition/urls.py
+++ b/wger/nutrition/urls.py
@@ -76,6 +76,9 @@ urlpatterns = patterns('wger.nutrition.views',
url(r'^ingredient/(?P<pk>\d+)/get-units$',
'ingredient.ajax_get_ingredient_units',
name='ingredient-get-units'),
+ 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 42dbe3f25..dbbc297c5 100644
--- a/wger/nutrition/views/ingredient.py
+++ b/wger/nutrition/views/ingredient.py
@@ -36,7 +36,7 @@ from django.views.generic import CreateView
from django.views.generic import UpdateView
from django.views.generic import ListView
-
+from wger.nutrition.forms import UnitChooserForm
from wger.nutrition.models import NutritionPlan
from wger.nutrition.models import Meal
from wger.nutrition.models import MealItem
@@ -215,6 +215,9 @@ def ingredient_view(request, id, slug=None):
ingredient = get_object_or_404(Ingredient, pk=id)
template_data['ingredient'] = ingredient
+ template_data['form'] = UnitChooserForm(data={'ingredient_id': ingredient.id,
+ 'amount': 100,
+ 'unit': None})
return render_to_response('ingredient/view.html',
template_data,
@@ -329,3 +332,42 @@ def ajax_get_ingredient_units(request, pk):
return HttpResponse(json.dumps(result, cls=helpers.DecimalJsonEncoder),
'application/json')
+
+
+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}
+ 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:
+ logger.debug(form.errors)
+
+ return HttpResponse(json.dumps(result, cls=helpers.DecimalJsonEncoder),
+ 'application/json')