Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add date fields to the ingredient model
Roland Geider396dad29f859
diff --git a/wger/manager/templates/tags/render_weight_log.html b/wger/manager/templates/tags/render_weight_log.htmlindex 609b045dd..9dd6da9dc 100644--- a/wger/manager/templates/tags/render_weight_log.html+++ b/wger/manager/templates/tags/render_weight_log.html@@ -1,9 +1,5 @@{% load i18n %}{% load staticfiles %}--{% block header %}--{% endblock %}<div class="weight-chart-table-toggle" data-toggle-target="table-{{div_uuid}}"><p><a href="#">diff --git a/wger/manager/tests/testcase.py b/wger/manager/tests/testcase.pyindex 2a2a0d3bc..09c1938d5 100644--- a/wger/manager/tests/testcase.py+++ b/wger/manager/tests/testcase.py@@ -35,13 +35,14 @@ class WorkoutManagerTestCase(TestCase):'test-ingredients','test-nutrition-data','test-workout-data')+ current_user = 'anonymous'def setUp(self):'''Overwrite some of Django's settings here'''os.environ['RECAPTCHA_TESTING'] = 'True'- logging.disable(logging.ERROR)+ logging.disable(logging.INFO)def tearDown(self):'''@@ -54,12 +55,14 @@ class WorkoutManagerTestCase(TestCase):Login the user, by default as 'admin''''self.client.login(username=user, password='%(user)s%(user)s' % {'user': user})+ self.current_user = userdef user_logout(self):'''Visit the logout page'''self.client.logout()+ self.current_user = 'anonymous'def compare_fields(self, field, value):current_field_class = field.__class__.__name__@@ -85,6 +88,13 @@ class WorkoutManagerTestCase(TestCase):else:self.assertEqual(field.id, value)+ def post_test_hook(self):+ '''+ Hook to add some more specific tests after the basic add or delete+ operations are finished+ '''+ pass+class WorkoutManagerDeleteTestCase(WorkoutManagerTestCase):'''@@ -136,6 +146,7 @@ class WorkoutManagerDeleteTestCase(WorkoutManagerTestCase):# The page we are redirected to doesn't trigger an errorresponse = self.client.get(response['Location'])self.assertEqual(response.status_code, 200)+ self.post_test_hook()def test_delete_object_anonymous(self):'''@@ -228,6 +239,7 @@ class WorkoutManagerEditTestCase(WorkoutManagerTestCase):# The page we are redirected to doesn't trigger an errorresponse = self.client.get(response['Location'])self.assertEqual(response.status_code, 200)+ self.post_test_hook()def test_edit_object_anonymous(self):'''@@ -324,6 +336,7 @@ class WorkoutManagerAddTestCase(WorkoutManagerTestCase):# The page we are redirected to doesn't trigger an errorresponse = self.client.get(response['Location'])self.assertEqual(response.status_code, 200)+ self.post_test_hook()def test_add_object_anonymous(self):'''diff --git a/wger/nutrition/fixtures/test-ingredients.json b/wger/nutrition/fixtures/test-ingredients.jsonindex 4c949e6b3..c65924bb3 100644--- a/wger/nutrition/fixtures/test-ingredients.json+++ b/wger/nutrition/fixtures/test-ingredients.json@@ -3,6 +3,8 @@"pk": 1,"model": "nutrition.ingredient","fields": {+ "update_date": "2013-02-12",+ "creation_date": "2013-01-01","name": "Test ingredient 1","language": 2,"sodium": "0.549",@@ -19,7 +21,8 @@"pk": 2,"model": "nutrition.ingredient","fields": {- "name": "Ingredient, test, 2, organic, raw",+ "name": "Ingredient, test, 2, organic, raw",+ "creation_date": "2013-01-01","language": 2,"sodium": "0.1","energy": 300,@@ -35,6 +38,8 @@"pk": 3,"model": "nutrition.ingredient","fields": {+ "update_date": "2013-03-22",+ "creation_date": "2013-02-03","name": "Bachelor chow, now with flavour!","language": 2,"sodium": "0.1",@@ -51,6 +56,7 @@"pk": 4,"model": "nutrition.ingredient","fields": {+ "creation_date": "2013-04-05","name": "Slurm","language": 2,"sodium": "0.1",@@ -67,6 +73,7 @@"pk": 5,"model": "nutrition.ingredient","fields": {+ "creation_date": "2013-04-05","name": "Another tasty ingredient","language": 2,"sodium": "2.1",@@ -83,6 +90,7 @@"pk": 6,"model": "nutrition.ingredient","fields": {+ "creation_date": "2013-04-05","name": "Raw ingredient","language": 2,"sodium": "2.1",diff --git a/wger/nutrition/migrations/0006_auto__add_field_ingredient_creation_date__chg_field_ingredient_sodium_.py b/wger/nutrition/migrations/0006_auto__add_field_ingredient_creation_date__chg_field_ingredient_sodium_.pynew file mode 100644index 000000000..ff89b3a81--- /dev/null+++ b/wger/nutrition/migrations/0006_auto__add_field_ingredient_creation_date__chg_field_ingredient_sodium_.py@@ -0,0 +1,171 @@+# -*- 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):+ # Adding field 'Ingredient.creation_date'+ db.add_column('nutrition_ingredient', 'creation_date',+ self.gf('django.db.models.fields.DateField')(auto_now_add=True, default=datetime.date.today, blank=True),+ keep_default=False)++ # Adding field 'Ingredient.update_date'+ db.add_column('nutrition_ingredient', 'update_date',+ self.gf('django.db.models.fields.DateField')(default=datetime.date.today),+ keep_default=False)+++ # Changing field 'Ingredient.sodium'+ db.alter_column('nutrition_ingredient', 'sodium', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=6, decimal_places=3))++ # Changing field 'Ingredient.fat'+ db.alter_column('nutrition_ingredient', 'fat', self.gf('django.db.models.fields.DecimalField')(max_digits=6, decimal_places=3))++ # Changing field 'Ingredient.carbohydrates_sugar'+ db.alter_column('nutrition_ingredient', 'carbohydrates_sugar', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=6, decimal_places=3))++ # Changing field 'Ingredient.fat_saturated'+ db.alter_column('nutrition_ingredient', 'fat_saturated', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=6, decimal_places=3))++ # Changing field 'Ingredient.fibres'+ db.alter_column('nutrition_ingredient', 'fibres', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=6, decimal_places=3))++ # Changing field 'Ingredient.protein'+ db.alter_column('nutrition_ingredient', 'protein', self.gf('django.db.models.fields.DecimalField')(max_digits=6, decimal_places=3))++ # Changing field 'Ingredient.carbohydrates'+ db.alter_column('nutrition_ingredient', 'carbohydrates', self.gf('django.db.models.fields.DecimalField')(max_digits=6, decimal_places=3))++ def backwards(self, orm):+ # Deleting field 'Ingredient.creation_date'+ db.delete_column('nutrition_ingredient', 'creation_date')++ # Deleting field 'Ingredient.update_date'+ db.delete_column('nutrition_ingredient', 'update_date')+++ # 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.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))++ # Changing field 'Ingredient.carbohydrates'+ db.alter_column('nutrition_ingredient', 'carbohydrates', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=2))++ 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': '6', 'decimal_places': '3'}),+ 'carbohydrates_sugar': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '3', 'blank': 'True'}),+ 'creation_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),+ 'energy': ('django.db.models.fields.IntegerField', [], {}),+ 'fat': ('django.db.models.fields.DecimalField', [], {'max_digits': '6', 'decimal_places': '3', 'blank': 'True'}),+ 'fat_saturated': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '3', 'blank': 'True'}),+ 'fibres': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '3', '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': '6', 'decimal_places': '3'}),+ 'sodium': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '3', 'blank': 'True'}),+ 'update_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'})+ },+ '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 filediff --git a/wger/nutrition/models.py b/wger/nutrition/models.pyindex 006c08d9d..c95bf502b 100644--- a/wger/nutrition/models.py+++ b/wger/nutrition/models.py@@ -16,6 +16,7 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.import loggingimport decimal+import datetimefrom django.db import models@@ -109,6 +110,11 @@ class Ingredient(models.Model):ordering = ["name", ]language = models.ForeignKey(Language, verbose_name=_('Language'))+ creation_date = models.DateField(_('Date'), auto_now_add=True)+ update_date = models.DateField(_('Date'),+ default=datetime.date.today,+ blank=True,+ )name = models.CharField(max_length=200,verbose_name=_('Name'),)@@ -167,12 +173,46 @@ class Ingredient(models.Model):return reverse('wger.nutrition.views.ingredient.view',kwargs={'id': self.id, 'slug': slugify(self.name)})+ def compare_with_database(self):+ '''+ Compares the current ingredient with the version saved in the database.++ If the current object has no PK, returns false+ '''+ if not self.pk:+ return False++ ingredient = Ingredient.objects.get(pk=self.pk)+ if self != ingredient:+ return False+ logger.debug('NOT equal')+ #form.instance.update_date = datetime.datetime.today()+ else:+ return True+ logger.debug('equal, not doing anything')+def __unicode__(self):'''Return a more human-readable representation'''return "%s" % (self.name, )+ def __eq__(self, other):+ '''+ Compare ingredients based on their values, not like django on their PKs+ '''++ logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.')+ equal = True+ if isinstance(other, self.__class__):+ for i in self._meta.fields:+ if (hasattr(self, i.name) and hasattr(other, i.name) and+ (getattr(self, i.name, None) != getattr(other, i.name, None))):+ equal = False+ else:+ equal = False+ return equal+def get_owner_object(self):'''Ingredient has no owner informationdiff --git a/wger/nutrition/tests/ingredient.py b/wger/nutrition/tests/ingredient.pyindex dc42d07aa..f2ceaba13 100644--- a/wger/nutrition/tests/ingredient.py+++ b/wger/nutrition/tests/ingredient.py@@ -14,10 +14,12 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.import json+import datetimefrom django.core.urlresolvers import reversefrom wger.nutrition.models import Ingredient+from wger.nutrition.models import Mealfrom wger.workout_manager.constants import NUTRITION_TAB@@ -55,6 +57,14 @@ class EditIngredientTestCase(WorkoutManagerEditTestCase):'protein': 30,'carbohydrates': 10}+ def post_test_hook(self):+ '''+ Test that the update date is correctly set+ '''+ if self.current_user == 'admin':+ ingredient = Ingredient.objects.get(pk=1)+ self.assertEqual(ingredient.update_date, datetime.date.today())+class AddIngredientTestCase(WorkoutManagerAddTestCase):'''@@ -74,6 +84,14 @@ class AddIngredientTestCase(WorkoutManagerAddTestCase):'protein': 30,'carbohydrates': 10}+ def post_test_hook(self):+ '''+ Test that the creation date is correctly set+ '''+ if self.current_user == 'admin':+ ingredient = Ingredient.objects.get(pk=7)+ self.assertEqual(ingredient.creation_date, datetime.date.today())+class IngredientDetailTestCase(WorkoutManagerTestCase):'''@@ -277,3 +295,39 @@ class IngredientValuesTestCase(WorkoutManagerTestCase):self.user_login('test')self.calculate_value()+++class IngredientTestCase(WorkoutManagerTestCase):+ '''+ Tests other ingredient functions+ '''+ def test_compare(self):+ '''+ Tests the custom compare method based on values+ '''+ ingredient1 = Ingredient.objects.get(pk=1)+ ingredient2 = Ingredient.objects.get(pk=1)+ ingredient2.name = 'A different name altogether'+ self.assertFalse(ingredient1 == ingredient2)++ ingredient1 = Ingredient()+ ingredient1.name = 'ingredient name'+ ingredient1.energy = 150+ ingredient1.protein = 30++ ingredient2 = Ingredient()+ ingredient2.name = 'ingredient name'+ ingredient2.energy = 150+ self.assertFalse(ingredient1 == ingredient2)++ ingredient2.protein = 31+ self.assertFalse(ingredient1 == ingredient2)++ ingredient2.protein = None+ self.assertFalse(ingredient1 == ingredient2)++ ingredient2.protein = 30+ self.assertEqual(ingredient1, ingredient2)++ meal = Meal.objects.get(pk=1)+ self.assertFalse(ingredient1 == meal)diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.pyindex 7e99c9b7b..2d85a9166 100644--- a/wger/nutrition/views/ingredient.py+++ b/wger/nutrition/views/ingredient.py@@ -15,6 +15,7 @@# You should have received a copy of the GNU Affero General Public Licenseimport loggingimport json+import datetimefrom django import formsfrom django.template import RequestContext@@ -103,7 +104,7 @@ def view(request, id, slug=None):class IngredientForm(forms.ModelForm):class Meta:model = Ingredient- exclude = ('language',)+ exclude = ('language', 'update_date')class IngredientDeleteView(YamlDeleteMixin, DeleteView):@@ -133,10 +134,18 @@ class IngredientEditView(YamlFormMixin, UpdateView):model = Ingredientform_class = IngredientForm- title = ugettext_lazy('Add a new ingredient')+ title = ugettext_lazy('Edit ingredient')form_action_urlname = 'ingredient-edit'messages = ugettext_lazy('Ingredient successfully updated')+ def form_valid(self, form):+ '''+ Set the date if the ingredient was updated+ '''+ if not form.instance.compare_with_database():+ form.instance.update_date = datetime.datetime.today()+ return super(IngredientEditView, self).form_valid(form)+class IngredientCreateView(YamlFormMixin, CreateView):'''diff --git a/wger/nutrition/views/meal_ingredient.py b/wger/nutrition/views/meal_ingredient.pydeleted file mode 100644index a233bb555..000000000--- a/wger/nutrition/views/meal_ingredient.py+++ /dev/null@@ -1,122 +0,0 @@-# -*- coding: utf-8 -*---# This file is part of Workout Manager.-#-# Workout Manager is free software: you can redistribute it and/or modify-# it under the terms of the GNU Affero General Public License as published by-# the Free Software Foundation, either version 3 of the License, or-# (at your option) any later version.-#-# Workout Manager is distributed in the hope that it will be useful,-# but WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-# GNU General Public License for more details.-#-# You should have received a copy of the GNU Affero General Public License-import logging--from django.template import RequestContext-from django.shortcuts import render_to_response-from django.shortcuts import get_object_or_404-from django.http import HttpResponseRedirect-from django.http import HttpResponseForbidden-from django.core.urlresolvers import reverse-from django.contrib.auth.decorators import login_required--from wger.nutrition.models import NutritionPlan-from wger.nutrition.models import Meal-from wger.nutrition.models import MealItem---logger = logging.getLogger('workout_manager.custom')---# ************************-# Meal ingredient functions-# ************************-@login_required-def delete_meal_item(request, item_id):- '''- Deletes the meal ingredient with the given ID- '''-- # Load the item- item = get_object_or_404(MealItem, pk=item_id)- plan = item.meal.plan-- # Only delete if the user is the owner- if plan.user == request.user:- item.delete()- return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view',- kwargs={'id': plan.id}))- else:- return HttpResponseForbidden()---@login_required-def edit_meal_item(request, id, meal_id, item_id=None):- '''- Form to add a meal to a plan- '''- template_data = {}-- # Load the plan- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)- template_data['plan'] = plan-- # Load the meal- meal = get_object_or_404(Meal, pk=meal_id)- template_data['meal'] = meal-- if meal.plan != plan:- return HttpResponseForbidden()-- # Load the meal item- # If the object is new, we will receice a 'None' (string) as the ID- # from the template, so we check for it (ValueError) and for an actual- # None (TypeError)- try:- int(item_id)- meal_item = get_object_or_404(MealItem, pk=item_id)- template_data['ingredient'] = meal_item.ingredient.id- template_data['ingredient_searchfield'] = meal_item.ingredient.name-- except ValueError, TypeError:- meal_item = MealItem()-- #template_data['meal_item'] = meal_item-- # Check that javascript is activated This is used to hide the drop down list with the- # ingredients and use the autocompleter version instead. This is not only nicer but also much- # faster as the ingredient list from USDA is many thosand entries long.- js_active = request.GET.get('js', False)- template_data['js_active'] = js_active-- # Process request- if request.method == 'POST':- meal_form = MealItemForm(request.POST, instance=meal_item)-- # Pass the ingredient ID back to the template, this is originally set by the JQuery- # autocompleter, in case of errors (max. gramms reached), we need to set the ID manually- # so the user can simply submit again.- template_data['ingredient'] = request.POST.get('ingredient', '')-- template_data['ingredient_searchfield'] = request.POST.get('ingredient_searchfield', '')-- # If the data is valid, save and redirect- if meal_form.is_valid():- meal_item = meal_form.save(commit=False)- meal_item.meal = meal- meal_item.order = 1- meal_item.save()-- return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view',- kwargs={'id': id}))-- else:- meal_form = MealItemForm(instance=meal_item)- template_data['form'] = meal_form-- return render_to_response('edit_meal_item.html',- template_data,- context_instance=RequestContext(request))