Self hosted FLOSS fitness/workout, nutrition and weight tracker
Make the weight units usable in the meal item edit page
Roland Geider6bf965825d1d
diff --git a/wger/manager/static/js/workout-manager.js b/wger/manager/static/js/workout-manager.jsindex 52838a111..90b0992da 100644--- a/wger/manager/static/js/workout-manager.js+++ b/wger/manager/static/js/workout-manager.js@@ -373,6 +373,16 @@ function init_ingredient_autocompleter()// After clicking on a result set the value of the hidden field$('#id_ingredient').val(ui.item.id);$('#exercise_name').html(ui.item.label);++ // See if the ingredient has any units and set the values for the forms+ $.get('/' + get_current_language() + '/nutrition/ingredient/' + ui.item.id + '/get-units',+ function(data){+ $.each(data, function(index, value) {+ $('#id_unit').append(new Option(value.name, value.id));+ $('#id_weight_unit').append(new Option(value.name, value.id));+ //console.log(index + ': ' + value.name);+ });+ });}});}diff --git a/wger/nutrition/migrations/0002_auto__add_ingredientweightunit__add_weightunit__add_field_mealitem_wei.py b/wger/nutrition/migrations/0002_auto__add_ingredientweightunit__add_weightunit__add_field_mealitem_wei.pyindex 6f8d766f2..b9ac9a731 100644--- a/wger/nutrition/migrations/0002_auto__add_ingredientweightunit__add_weightunit__add_field_mealitem_wei.py+++ b/wger/nutrition/migrations/0002_auto__add_ingredientweightunit__add_weightunit__add_field_mealitem_wei.py@@ -14,7 +14,7 @@ class Migration(SchemaMigration):('ingredient', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['nutrition.Ingredient'])),('unit', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['nutrition.WeightUnit'])),('gramm', self.gf('django.db.models.fields.IntegerField')()),- ('amount', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=2)),+ ('amount', self.gf('django.db.models.fields.DecimalField')(default=1, max_digits=5, decimal_places=2)),))db.send_create_signal('nutrition', ['IngredientWeightUnit'])@@ -28,12 +28,7 @@ class Migration(SchemaMigration):# Adding field 'MealItem.weight_unit'db.add_column('nutrition_mealitem', 'weight_unit',- self.gf('django.db.models.fields.related.ForeignKey')(to=orm['nutrition.IngredientWeightUnit'], null=True),- keep_default=False)-- # Adding field 'MealItem.weight_type'- db.add_column('nutrition_mealitem', 'weight_type',- self.gf('django.db.models.fields.CharField')(default='1', max_length=2),+ self.gf('django.db.models.fields.related.ForeignKey')(to=orm['nutrition.IngredientWeightUnit'], null=True, blank=True),keep_default=False)@@ -47,9 +42,6 @@ class Migration(SchemaMigration):# Deleting field 'MealItem.weight_unit'db.delete_column('nutrition_mealitem', 'weight_unit_id')- # Deleting field 'MealItem.weight_type'- db.delete_column('nutrition_mealitem', 'weight_type')-models = {'auth.group': {@@ -110,7 +102,7 @@ class Migration(SchemaMigration):},'nutrition.ingredientweightunit': {'Meta': {'object_name': 'IngredientWeightUnit'},- 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),+ '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']"}),@@ -130,8 +122,7 @@ class Migration(SchemaMigration):'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_type': ('django.db.models.fields.CharField', [], {'default': "'1'", 'max_length': '2'}),- 'weight_unit': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['nutrition.IngredientWeightUnit']", 'null': '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'},@@ -142,7 +133,7 @@ class Migration(SchemaMigration):'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})},'nutrition.weightunit': {- 'Meta': {'object_name': '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'})diff --git a/wger/nutrition/models.py b/wger/nutrition/models.pyindex c88e9f6c1..598cae798 100644--- a/wger/nutrition/models.py+++ b/wger/nutrition/models.py@@ -27,6 +27,10 @@ from django.utils.translation import ugettext_lazy as _from wger.exercises.models import Language+MEALITEM_WEIGHT_GRAM = '1'+MEALITEM_WEIGHT_UNIT = '2'++class NutritionPlan(models.Model):'''A nutrition plan@@ -73,7 +77,7 @@ class NutritionPlan(models.Model):for item in meal.mealitem_set.select_related():# Calculate the base weight of the item- if item.weight_type == MEALITEM_WEIGHT_GRAM:+ if item.get_unit_type() == MEALITEM_WEIGHT_GRAM:item_weight = item.amount_grammelse:item_weight = (item.amount_gramm *@@ -262,15 +266,6 @@ class Meal(models.Model):return self.plan-MEALITEM_WEIGHT_GRAM = '1'-MEALITEM_WEIGHT_UNIT = '2'--MEALITEM_WEIGHT_TYPES = (- (MEALITEM_WEIGHT_GRAM, _('Weight in grams')),- (MEALITEM_WEIGHT_UNIT, _('Weight in units')),-)--class MealItem(models.Model):'''An item (component) of a meal@@ -280,16 +275,15 @@ class MealItem(models.Model):ingredient = models.ForeignKey(Ingredient, verbose_name=_('Ingredient'))weight_unit = models.ForeignKey(IngredientWeightUnit,verbose_name=_('Weight unit'),- null=True)+ null=True,+ blank=True,+ )order = models.IntegerField(max_length=1, blank=True, verbose_name=_('Order'))amount_gramm = models.IntegerField(max_length=4,blank=True,validators=[MaxValueValidator(1000)],verbose_name=_('Amount in gramms'))- weight_type = models.CharField(max_length=2,- choices=MEALITEM_WEIGHT_TYPES,- default=MEALITEM_WEIGHT_GRAM)def __unicode__(self):'''@@ -302,3 +296,15 @@ class MealItem(models.Model):Returns the object that has owner information'''return self.meal.plan++ def get_unit_type(self):+ '''+ Returns the type of unit used:+ - a value in grams+ - a 'human' unit like 'a cup' or 'a slice'+ '''++ if self.weight_unit:+ return MEALITEM_WEIGHT_UNIT+ else:+ return MEALITEM_WEIGHT_GRAMdiff --git a/wger/nutrition/templates/edit_meal_item.html b/wger/nutrition/templates/edit_meal_item.htmlindex 990a2ef65..a8a94ada8 100644--- a/wger/nutrition/templates/edit_meal_item.html+++ b/wger/nutrition/templates/edit_meal_item.html@@ -52,7 +52,6 @@ $(document).ready(function() {{% yaml_form_field form.amount_gramm %}{% yaml_form_field form.weight_unit "ym-fbox-select" %}- {% yaml_form_field form.weight_type "ym-fbox-select"%}<tr><td colspan="2"><input type="submit" value="{% trans 'Save' %}" id="form-save">diff --git a/wger/nutrition/templates/view_nutrition_plan.html b/wger/nutrition/templates/view_nutrition_plan.htmlindex da2b7fb47..034de7404 100644--- a/wger/nutrition/templates/view_nutrition_plan.html+++ b/wger/nutrition/templates/view_nutrition_plan.html@@ -93,9 +93,7 @@ $(document).ready(function() {<ul>{% for item in meal.mealitem_set.select_related %}<li>- {{ item.amount_gramm }}- {% if item.weight_type == MEALITEM_WEIGHT_GRAM %}- g+ {{ item.amount_gramm }}{% if item.get_unit_type == MEALITEM_WEIGHT_GRAM %}g{% else %}{{ item.weight_unit.unit.name }}{% endif %}diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex c61300b27..09219b092 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -73,6 +73,9 @@ urlpatterns = patterns('wger.nutrition.views',url(r'^ingredient/search/$','ingredient.ingredient_search',name='ingredient-search'),+ url(r'^ingredient/(?P<pk>\d+)/get-units$',+ 'ingredient.ajax_get_ingredient_units',+ name='ingredient-get-units'),# Ingredient unitsurl(r'^ingredient/unit/list/$',diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.pyindex 9a877e461..448c4d1bf 100644--- a/wger/nutrition/views/ingredient.py+++ b/wger/nutrition/views/ingredient.py@@ -16,6 +16,7 @@import loggingimport json+from django import formsfrom django.template import RequestContextfrom django.shortcuts import render_to_responsefrom django.shortcuts import get_object_or_404@@ -26,7 +27,6 @@ from django.core.context_processors import csrffrom django.core.urlresolvers import reversefrom django.core.urlresolvers import reverse_lazyfrom django.contrib.auth.decorators import login_required-from django.forms import ModelFormfrom django.utils.translation import ugettext as _from django.utils.translation import ugettext_lazy@@ -43,6 +43,8 @@ from wger.nutrition.models import MealItemfrom wger.nutrition.models import Ingredientfrom wger.nutrition.models import WeightUnitfrom wger.nutrition.models import IngredientWeightUnit+from wger.nutrition.models import MEALITEM_WEIGHT_GRAM+from wger.nutrition.models import MEALITEM_WEIGHT_UNITfrom reportlab.lib.styles import getSampleStyleSheetfrom reportlab.lib.pagesizes import A4, cm@@ -57,17 +59,31 @@ from wger.workout_manager.generic_views import YamlFormMixinfrom wger.workout_manager.generic_views import YamlDeleteMixinfrom wger.workout_manager import helpers-logger = logging.getLogger('workout_manager.custom')# ************************# Meal ingredient functions# ************************-class MealItemForm(ModelForm):+class MealItemForm(forms.ModelForm):+ weight_unit = forms.ModelChoiceField(queryset=IngredientWeightUnit.objects.none(),+ empty_label="g",+ required=False)+class Meta:model = MealItem- exclude = ('meal', 'order')+ exclude = ('meal', 'order', )++ def __init__(self, *args, **kwargs):+ super(MealItemForm, self).__init__(*args, **kwargs)+ try:+ ingredient_id = args[0]['ingredient']+ except IndexError:+ ingredient_id = None++ if ingredient_id:+ self.fields['weight_unit'].queryset = \+ IngredientWeightUnit.objects.filter(ingredient_id=ingredient_id)@login_required@@ -197,7 +213,7 @@ def ingredient_view(request, id, slug=None):context_instance=RequestContext(request))-class IngredientForm(ModelForm):+class IngredientForm(forms.ModelForm):class Meta:model = Ingredientexclude = ('language',)@@ -287,3 +303,17 @@ def ingredient_search(request):return render_to_response('ingredient_search.html',template_data,context_instance=RequestContext(request))+++def ajax_get_ingredient_units(request, pk):+ '''+ Fetches the available ingredient units+ '''++ units = IngredientWeightUnit.objects.filter(ingredient_id=pk)+ result = []+ for unit in units:+ result.append({'id': unit.id, 'name': unit.unit.name, 'amount': unit.amount})++ return HttpResponse(json.dumps(result, cls=helpers.DecimalJsonEncoder),+ 'application/json')