Self hosted FLOSS fitness/workout, nutrition and weight tracker
Format the code according to PEP8
Roland Geider6d1ea0d47a59
diff --git a/wger/exercises/admin.py b/wger/exercises/admin.pyindex 9283d63c7..988e0ddd8 100644--- a/wger/exercises/admin.py+++ b/wger/exercises/admin.py@@ -35,4 +35,3 @@ admin.site.register(Exercise, ExerciseAdmin)admin.site.register(ExerciseCategory)admin.site.register(Language)admin.site.register(Muscle)-diff --git a/wger/exercises/models.py b/wger/exercises/models.pyindex 233b9819a..4a778c6aa 100644--- a/wger/exercises/models.py+++ b/wger/exercises/models.py@@ -16,15 +16,16 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.from django.db import models-from django.template.defaultfilters import slugify # django.utils.text.slugify in django 1.5!+from django.template.defaultfilters import slugify # django.utils.text.slugify in django 1.5!from django.utils.translation import ugettext_lazy as _from django.core.urlresolvers import reverseclass Language(models.Model):- """Language of an item (exercise, workout, etc.)- """+ '''+ Language of an item (exercise, workout, etc.)+ '''#e.g. 'de'short_name = models.CharField(max_length=2,@@ -32,17 +33,19 @@ class Language(models.Model):#e.g. 'Deutsch'full_name = models.CharField(max_length=30,- verbose_name=_('Language full name'))+ verbose_name=_('Language full name'))def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return "%s (%s)" % (self.full_name, self.short_name)class Muscle(models.Model):- """Muscle an exercise works out- """+ '''+ Muscle an exercise works out+ '''# Name, in latin, e.g. "Pectoralis major"name = models.CharField(max_length=50,@@ -56,14 +59,16 @@ class Muscle(models.Model):ordering = ["name", ]def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return self.nameclass ExerciseCategory(models.Model):- """Model for an exercise category- """+ '''+ Model for an exercise category+ '''name = models.CharField(max_length=100,verbose_name=_('Name'),)language = models.ForeignKey(Language,@@ -75,19 +80,22 @@ class ExerciseCategory(models.Model):ordering = ["name", ]def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return self.namedef get_owner_object(self):- """+ '''Category has no owner information- """+ '''return False+class Exercise(models.Model):- """Model for an exercise- """+ '''+ Model for an exercise+ '''category = models.ForeignKey(ExerciseCategory,verbose_name=_('Category'))description = models.TextField(max_length=2000,@@ -99,53 +107,55 @@ class Exercise(models.Model):muscles = models.ManyToManyField(Muscle,verbose_name=_('Primary muscles'),)-+muscles_secondary = models.ManyToManyField(Muscle,- verbose_name=_('Secondary muscles'),- related_name='secondary_muscles',- null=True,- blank=True- )+ verbose_name=_('Secondary muscles'),+ related_name='secondary_muscles',+ null=True,+ blank=True+ )# Metaclass to set some other propertiesclass Meta:ordering = ["name", ]def get_absolute_url(self):- """+ '''Returns the canonical URL to view an exercise- """+ '''return reverse('wger.exercises.views.exercise_view', kwargs={'id': self.id,- 'slug': slugify(self.name)})+ 'slug': slugify(self.name)})def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return self.namedef get_owner_object(self):- """+ '''Exercise has no owner information- """+ '''return Falseclass ExerciseComment(models.Model):- """Model for an exercise comment- """+ '''+ Model for an exercise comment+ '''exercise = models.ForeignKey(Exercise, verbose_name=_('Exercise'))comment = models.CharField(max_length=200,verbose_name=_('Comment'),help_text=_('A comment about how to correctly do this exercise.'))def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return self.commentdef get_owner_object(self):- """+ '''Comment has no owner information- """+ '''return False-diff --git a/wger/exercises/tests/categories.py b/wger/exercises/tests/categories.pyindex 399516e30..6a4e9780f 100644--- a/wger/exercises/tests/categories.py+++ b/wger/exercises/tests/categories.py@@ -40,7 +40,7 @@ class ExerciseCategoryTestCase(WorkoutManagerTestCase):# Delete the categorycount_before = ExerciseCategory.objects.count()response = self.client.post(reverse('exercisecategory-delete',- kwargs={'pk': 4}))+ kwargs={'pk': 4}))count_after = ExerciseCategory.objects.count()# There is a redirect@@ -98,8 +98,8 @@ class ExerciseCategoryTestCase(WorkoutManagerTestCase):self.assertEqual(response.status_code, 200)response = self.client.post(reverse('exercisecategory-edit',- kwargs={'pk': 3}),- {'name': 'A different name'})+ kwargs={'pk': 3}),+ {'name': 'A different name'})# There is a redirectself.assertEqual(response.status_code, 302)@@ -119,7 +119,7 @@ class ExerciseCategoryTestCase(WorkoutManagerTestCase):# No nameif not fail:response = self.client.post(reverse('exercisecategory-edit',- kwargs={'pk': 3}),+ kwargs={'pk': 3}),{'name': ''})self.assertTrue(response.context['form'].errors['name'])@@ -163,7 +163,7 @@ class ExerciseCategoryTestCase(WorkoutManagerTestCase):count_before = ExerciseCategory.objects.count()response = self.client.post(reverse('exercisecategory-add'),- {'name': 'A new category'})+ {'name': 'A new category'})count_after = ExerciseCategory.objects.count()# There is a redirectdiff --git a/wger/exercises/tests/exercise.py b/wger/exercises/tests/exercise.pyindex ec3403af5..4f82924f0 100644--- a/wger/exercises/tests/exercise.py+++ b/wger/exercises/tests/exercise.py@@ -1,289 +1,291 @@# 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 Licenseimport json-from django.test import TestCasefrom django.core.urlresolvers import reversefrom wger.exercises.models import Exercise-from wger.exercises.models import ExerciseCategoryfrom wger.manager.tests.testcase import WorkoutManagerTestCaseclass ExerciseIndexTestCase(WorkoutManagerTestCase):-+def test_exercise_index(self):'''Tests the exercise overview page'''-+response = self.client.get(reverse('wger.exercises.views.exercise_overview'))-+# Page existsself.assertEqual(response.status_code, 200)-+# Correct tab is selectedself.assertEqual(response.context['active_tab'], 'exercises')-+# Correct categories are showncategory_1 = response.context['categories'][0]self.assertEqual(category_1.id, 2)self.assertEqual(category_1.name, "Another category")-+category_2 = response.context['categories'][1]self.assertEqual(category_2.id, 3)self.assertEqual(category_2.name, "Yet another category")-+# Correct exercises in the categoriesexercises_1 = category_1.exercise_set.all()exercise_1 = exercises_1[0]exercise_2 = exercises_1[1]self.assertEqual(exercise_1.id, 2)self.assertEqual(exercise_1.name, "A very cool exercise")-+self.assertEqual(exercise_2.id, 1)self.assertEqual(exercise_2.name, "An exercise")--+def test_exercise_detail(self):- """Tests the exercise details page- """-+ '''+ Tests the exercise details page+ '''+response = self.client.get(reverse('wger.exercises.views.exercise_view', kwargs={'id': 1}))self.assertEqual(response.status_code, 200)-+# Correct tab is selectedself.assertEqual(response.context['active_tab'], 'exercises')-+# Exercise loaded correct musclesexercise_1 = response.context['exercise']self.assertEqual(exercise_1.id, 1)-+muscles = exercise_1.muscles.all()muscle_1 = muscles[0]muscle_2 = muscles[1]-+self.assertEqual(muscle_1.id, 1)self.assertEqual(muscle_2.id, 2)-+# Ensure that non-existent exercises throw a 404.response = self.client.get(reverse('wger.exercises.views.exercise_view', kwargs={'id': 42}))self.assertEqual(response.status_code, 404)--++class ExercisesTestCase(WorkoutManagerTestCase):- """Exercise test case"""--+ '''+ Exercise test case+ '''+def add_exercise_user_fail(self):- """Helper function to test adding exercises by users that aren't- authorized- """-+ '''+ Helper function to test adding exercises by users that aren't authorized+ '''+# Add an exercisecount_before = Exercise.objects.count()- response = self.client.post(reverse('exercise-add'),- {'category': 2,- 'name': 'my test exercise',- 'muscles': [1, 2]})+ response = self.client.post(reverse('exercise-add'),+ {'category': 2,+ 'name': 'my test exercise',+ 'muscles': [1, 2]})count_after = Exercise.objects.count()-+# Exercise was not added- self.assertEqual(count_before, count_after)+ self.assertEqual(count_before, count_after)self.assertTrue('login' in response['location'])def test_add_exercise_user_no_rights(self):- """Tests adding an exercise with a user without enough rights to do this"""-+ '''+ Tests adding an exercise with a user without enough rights to do this+ '''+self.user_login('test')self.add_exercise_user_fail()self.user_logout()-+def test_add_exercise_no_user(self):- """Tests adding an exercise with a logged out (anonymous) user"""-+ '''+ Tests adding an exercise with a logged out (anonymous) user+ '''+self.user_logout()self.add_exercise_user_fail()self.user_logout()--+def test_add_exercise_administrator_user(self):- """Tests adding/editing an exercise with a user with enough rights to do this"""-+ '''+ Tests adding/editing an exercise with a user with enough rights to do this+ '''+# Log in as 'admin'self.user_login()-+# Add an exercisecount_before = Exercise.objects.count()- response = self.client.post(reverse('exercise-add'),- {'category': 2,- 'name': 'my test exercise',- 'muscles': [1, 2]})+ response = self.client.post(reverse('exercise-add'),+ {'category': 2,+ 'name': 'my test exercise',+ 'muscles': [1, 2]})count_after = Exercise.objects.count()self.assertEqual(response.status_code, 302)new_location = response['Location']self.assertEqual(count_before + 1, count_after, 'Exercise was not added')-+response = self.client.get(new_location)- exercise_id = response.context['exercise'].id---+ exercise_id = response.context['exercise'].id+# Exercise was saved- response = self.client.get(reverse('wger.exercises.views.exercise_view', kwargs = {'id': exercise_id}))+ response = self.client.get(reverse('wger.exercises.views.exercise_view',+ kwargs={'id': exercise_id}))self.assertEqual(response.status_code, 200)-+# Navigation tabself.assertEqual(response.context['active_tab'], 'exercises')-- exercise_1 = Exercise.objects.get(pk = exercise_id)++ exercise_1 = Exercise.objects.get(pk=exercise_id)self.assertEqual(exercise_1.name, 'my test exercise')-+# Wrong category - adding- response = self.client.post(reverse('exercise-add'),- {'category': 111,- 'name': 'my test exercise',- 'muscles': [1, 2]})+ response = self.client.post(reverse('exercise-add'),+ {'category': 111,+ 'name': 'my test exercise',+ 'muscles': [1, 2]})self.assertTrue(response.context['form'].errors['category'])-+# Wrong category - editing- response = self.client.post(reverse('exercise-edit', kwargs = {'pk': '1'}),- {'category': 111,- 'name': 'my test exercise',- 'muscles': [1, 2]})+ response = self.client.post(reverse('exercise-edit', kwargs={'pk': '1'}),+ {'category': 111,+ 'name': 'my test exercise',+ 'muscles': [1, 2]})self.assertTrue(response.context['form'].errors['category'])--+# No muscles - adding- response = self.client.post(reverse('exercise-add'),- {'category': 1,- 'name': 'my test exercise',- 'muscles': []})+ response = self.client.post(reverse('exercise-add'),+ {'category': 1,+ 'name': 'my test exercise',+ 'muscles': []})self.assertTrue(response.context['form'].errors['muscles'])-+# No muscles - editing- response = self.client.post(reverse('exercise-edit', kwargs = {'pk': '1'}),- {'category': 1,- 'name': 'my test exercise',- 'muscles': []})+ response = self.client.post(reverse('exercise-edit', kwargs={'pk': '1'}),+ {'category': 1,+ 'name': 'my test exercise',+ 'muscles': []})self.assertTrue(response.context['form'].errors['muscles'])--- #print response.context['edit_form'].errors- #print response['location']-self.user_logout()-def delete_exercise(self, fail=True):- """Helper function to test deleting exercises"""-+ '''+ Helper function to test deleting exercises+ '''+# The exercise existsresponse = self.client.get(reverse('wger.exercises.views.exercise_view', kwargs={'id': 3}))self.assertEqual(response.status_code, 200)-+# Delete the exercisecount_before = Exercise.objects.count()-+# GET request, doesn't delete anythingresponse = self.client.get(reverse('exercise-delete', kwargs={'pk': 3}))count_after = Exercise.objects.count()self.assertEqual(count_before, count_after, 'Exercise was deleted')-+# Check the deletionif fail:self.assertEqual(response.status_code, 302)else:self.assertEqual(response.status_code, 200)-+# POST request, does delete the exerciseresponse = self.client.post(reverse('exercise-delete', kwargs={'pk': 3}))count_after = Exercise.objects.count()-+self.assertEqual(response.status_code, 302)-+# Check the deletionif fail:self.assertEqual(count_before, count_after, 'Exercise was deleted')else:self.assertTrue(count_before > count_after, 'Exercise was not deleted')---+def test_delete_exercise_anonymous(self, fail=True):- """Test deleting an exercise by an anonymous user"""-+ '''+ Test deleting an exercise by an anonymous user+ '''+self.delete_exercise()--+def test_delete_exercise_unauthorized(self, fail=True):- """Test deleting an exercise by an unauthorized user"""-+ '''+ Test deleting an exercise by an unauthorized user+ '''+self.user_login('test')self.delete_exercise()self.user_logout()-+def test_delete_exercise_authorized(self):- """Test deleting an exercise by an authorized user"""-+ '''+ Test deleting an exercise by an authorized user+ '''+self.user_login()self.delete_exercise(fail=False)self.user_logout()--+def search_exercise(self, fail=True):'''Helper function to test searching for exercises'''-+# Search for exercises (1 hit, "A very cool exercise")response = self.client.get(reverse('wger.exercises.views.exercise_search') + '?term=cool')self.assertEqual(response.status_code, 200)self.assertEqual(len(response.context['exercises']), 1)self.assertEqual(response.context['exercises'][0].name, 'A very cool exercise')--- kwargs = {'HTTP_X_REQUESTED_WITH' : 'XMLHttpRequest'}-++ kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}+# AJAX-Search for exercises (1 hit, "A very cool exercise")- response = self.client.get(reverse('wger.exercises.views.exercise_search') + '?term=cool', **kwargs)+ response = self.client.get(reverse('wger.exercises.views.exercise_search') ++ '?term=cool', **kwargs)self.assertEqual(response.status_code, 200)result = json.loads(response.content)self.assertEqual(len(result), 1)self.assertEqual(result[0]['value'], 'A very cool exercise')--+def test_search_exercise_anonymous(self):- """Test deleting an exercise by an anonymous user"""-+ '''+ Test deleting an exercise by an anonymous user+ '''+self.search_exercise()--+def test_search_exercise_unauthorized(self):- """Test deleting an exercise by an unauthorized user"""-+ '''+ Test deleting an exercise by an unauthorized user+ '''+self.user_login('test')self.search_exercise()self.user_logout()-+def test_search_exercise_authorized(self):- """Test deleting an exercise by an authorized user"""-+ '''+ Test deleting an exercise by an authorized user+ '''+self.user_login()self.search_exercise(fail=False)self.user_logout()--diff --git a/wger/exercises/tests/exercise_comments.py b/wger/exercises/tests/exercise_comments.pyindex 1dde0ed6a..82f00a468 100644--- a/wger/exercises/tests/exercise_comments.py+++ b/wger/exercises/tests/exercise_comments.py@@ -1,47 +1,47 @@# 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-from django.test import TestCasefrom django.core.urlresolvers import reversefrom wger.exercises.models import Exercise-from wger.exercises.models import ExerciseCategoryfrom wger.manager.tests.testcase import WorkoutManagerTestCaseclass ExercisecommentsTestCase(WorkoutManagerTestCase):-+def exercise_add_comment(self, fail=True):- """Tests the exercise comments (fails because of permissions)"""-+ '''+ Tests the exercise comments (fails because of permissions)+ '''+# Load the exerciseexercise_1 = Exercise.objects.get(pk=1)-+# Comments are loadedcomments = exercise_1.exercisecomment_set.all()comment_1 = comments[0]self.assertEqual(comment_1.id, 1)self.assertEqual(comment_1.comment, "test 123")self.assertEqual(len(comments), 1)-+# Post a commentresponse = self.client.post(reverse('exercisecomment-add', kwargs={'exercise_pk': 1}),{'comment': 'a new cool comment'})comments = exercise_1.exercisecomment_set.all()-+self.assertEqual(response.status_code, 302)if fail:comments = exercise_1.exercisecomment_set.all()@@ -49,58 +49,61 @@ class ExercisecommentsTestCase(WorkoutManagerTestCase):else:self.assertEqual(len(comments), 2)-+# Post an empty comment and check it doesn't get added- response = self.client.post(reverse('exercisecomment-add', kwargs={'exercise_pk': 1}),+ response = self.client.post(reverse('exercisecomment-add', kwargs={'exercise_pk': 1}),{'comment': ''})comments = exercise_1.exercisecomment_set.all()-+if fail:self.assertEqual(len(comments), 1)else:self.assertEqual(response.status_code, 200)self.assertEqual(len(comments), 2)--+def test_exercise_add_comment_no_authorized(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.user_login('test')self.exercise_add_comment(fail=True)self.user_logout()-+def test_exercise_add_comment_not_logged_in(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.exercise_add_comment(fail=True)--+def test_exercise_add_comment_authorized(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.user_login()self.exercise_add_comment(fail=False)--+def exercise_delete_comment(self, fail=True):'''Tests the deletion of exercise comments'''-+# Load the exerciseexercise_1 = Exercise.objects.get(pk=1)-+# Comments are loadedcomments = exercise_1.exercisecomment_set.all()comment_1 = comments[0]self.assertEqual(comment_1.id, 1)self.assertEqual(comment_1.comment, "test 123")self.assertEqual(len(comments), 1)-+# Delete the commentresponse = self.client.post(reverse('exercisecomment-delete', kwargs={'id': 1}))comments = exercise_1.exercisecomment_set.all()-+self.assertEqual(response.status_code, 302)if fail:comments = exercise_1.exercisecomment_set.all()@@ -108,76 +111,85 @@ class ExercisecommentsTestCase(WorkoutManagerTestCase):else:self.assertEqual(len(comments), 0)--+def test_exercise_delete_comment_no_authorized(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.user_login('test')self.exercise_delete_comment(fail=True)self.user_logout()-+def test_exercise_delete_comment_not_logged_in(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.exercise_delete_comment(fail=True)--+def test_exercise_delete_comment_authorized(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.user_login()self.exercise_delete_comment(fail=False)--+def exercise_edit_comment(self, fail=True):- """Tests the exercise comments (fails because of permissions)"""-+ '''+ Tests the exercise comments (fails because of permissions)+ '''+# Load the exerciseexercise_1 = Exercise.objects.get(pk=1)comment_before = 'test 123'comment_after = 'a new cool comment'-+# Comments are loadedcomments = exercise_1.exercisecomment_set.all()comment_1 = comments[0]self.assertEqual(comment_1.id, 1)self.assertEqual(comment_1.comment, comment_before)self.assertEqual(len(comments), 1)-+# Open the edit pageresponse = self.client.get(reverse('exercisecomment-edit', kwargs={'pk': 1}))if fail:self.assertEqual(response.status_code, 302)else:- self.assertEqual(response.status_code, 200)-+ self.assertEqual(response.status_code, 200)+# Edit the commentresponse = self.client.post(reverse('exercisecomment-edit', kwargs={'pk': 1}),{'comment': comment_after})comments = exercise_1.exercisecomment_set.all()comment_1 = comments[0]-+if fail:self.assertEqual(comment_1.comment, comment_before)else:self.assertEqual(comment_1.comment, comment_after)---+def test_exercise_edit_comment_no_authorized(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.user_login('test')self.exercise_edit_comment(fail=True)-+def test_exercise_edit_comment_not_logged_in(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.exercise_edit_comment(fail=True)-+def test_exercise_edit_comment_authorized(self):- """Tests the exercise comments"""-+ '''+ Tests the exercise comments+ '''+self.user_login()self.exercise_edit_comment(fail=False)diff --git a/wger/exercises/views.py b/wger/exercises/views.pyindex e78e54a0d..0e7645e2f 100644--- a/wger/exercises/views.py+++ b/wger/exercises/views.py@@ -31,6 +31,7 @@ from django.contrib.auth.decorators import permission_requiredfrom django.utils.translation import ugettext as _from django.utils.translation import ugettext_lazy+from django.views.generic import ListViewfrom django.views.generic import DeleteViewfrom django.views.generic import CreateViewfrom django.views.generic import UpdateView@@ -116,7 +117,8 @@ def exercisecomment_delete(request, id):exercise_id = comment.exercise.idcomment.delete()- return HttpResponseRedirect(reverse('wger.exercises.views.exercise_view', kwargs={'id': exercise_id}))+ return HttpResponseRedirect(reverse('wger.exercises.views.exercise_view',+ kwargs={'id': exercise_id}))# ************************@@ -137,8 +139,6 @@ def exercise_overview(request):context_instance=RequestContext(request))-from django.views.generic import ListView-class MuscleListView(ListView):'''Overview of all muscles and their exercises@@ -148,6 +148,7 @@ class MuscleListView(ListView):context_object_name = 'muscle_list'template_name = 'muscle_overview.html'+def exercise_view(request, id, slug=None):'''Detail view for an exercise@@ -176,7 +177,6 @@ def exercise_view(request, id, slug=None):else:backgrounds_back.append('images/muscles/secondary/muscle-%s.svg' % muscle.id)-# Append the "main" background, with the silhouette of the human body# This has to happen as the last step, so it is rendered behind the muscles.if backgrounds_front:@@ -233,7 +233,9 @@ class ExercisesEditAddView(YamlFormMixin):# to 'en-us'.class ExerciseForm(ModelForm):language = load_language()- category = ModelChoiceField(queryset=ExerciseCategory.objects.filter(language=language.id))+ category = ModelChoiceField(queryset=ExerciseCategory.objects.filter(+ language=language.id)+ )class Meta:model = Exercisediff --git a/wger/main.py b/wger/main.pyindex b1e4f6301..30c757c2b 100755--- a/wger/main.py+++ b/wger/main.py@@ -164,7 +164,6 @@ def _main(opts, database_path=None):# Set the django environment to the settingssetup_django_environment(settings_path)-# Create Database if necessaryif not database_exists() or opts.syncdb:run_syncdb()diff --git a/wger/manager/admin.py b/wger/manager/admin.pyindex 9d236b7dc..b8ad1430e 100644--- a/wger/manager/admin.py+++ b/wger/manager/admin.py@@ -17,10 +17,6 @@ from wger.manager import models as manager_modelsfrom django.contrib import admin----admin.site.register(manager_models.TrainingSchedule)admin.site.register(manager_models.Set)admin.site.register(manager_models.Day)@@ -28,4 +24,3 @@ admin.site.register(manager_models.WorkoutLog)admin.site.register(manager_models.UserProfile)admin.site.register(manager_models.Setting)-diff --git a/wger/manager/context_processor.py b/wger/manager/context_processor.pyindex e535e5c61..5461ff5f6 100644--- a/wger/manager/context_processor.py+++ b/wger/manager/context_processor.py@@ -20,8 +20,6 @@ from wger.workout_manager import constantsfrom wger.manager.utils import load_language--def processor(request):full_path = request.get_full_path()@@ -38,7 +36,7 @@ def processor(request):# The current path'request_full_path': full_path,-+# Translation links'i18n_path': {'de': '/de' + full_path[3:],'en': '/en' + full_path[3:]},diff --git a/wger/manager/forms.py b/wger/manager/forms.pyindex 8dc2aab9e..4be8c2d94 100644--- a/wger/manager/forms.py+++ b/wger/manager/forms.py@@ -53,7 +53,7 @@ class UserPreferencesForm(ModelForm):class UserEmailForm(ModelForm):email = EmailField(label=_("Email"),help_text=_("Completely optional, but needed to reset your password "- "in case you forget it."),+ "in case you forget it."),required=False)def clean_email(self):@@ -79,6 +79,7 @@ class DemoUserForm(Form):label=_('Confirmation text'),help_text=_('As a security measure, please enter the previous words'),)+class WorkoutForm(ModelForm):class Meta:model = TrainingSchedule@@ -96,18 +97,14 @@ class DayForm(ModelForm):model = Dayexclude = ('training',)- widgets = {- 'day': TranslatedSelectMultiple()- }+ widgets = {'day': TranslatedSelectMultiple()}class SetForm(ModelForm):class Meta:model = Setexclude = ('exerciseday', 'order',)- widgets = {- 'exercises': ExerciseAjaxSelect(),- }+ widgets = {'exercises': ExerciseAjaxSelect(), }# We need to overwrite the init method here because otherwise Django# will outut a default help text, regardless of the widget used@@ -115,7 +112,7 @@ class SetForm(ModelForm):def __init__(self, *args, **kwargs):super(SetForm, self).__init__(*args, **kwargs)self.fields['exercises'].help_text = _('You can search for more than one exercise, '- 'they will be grouped together for a superset.')+ 'they will be grouped together for a superset.')class HelperDateForm(Form):@@ -139,5 +136,5 @@ class WorkoutLogForm(ModelForm):class Meta:model = WorkoutLogexclude = ('user',- 'workout',- 'exercise')+ 'workout',+ 'exercise')diff --git a/wger/manager/models.py b/wger/manager/models.pyindex 39f934ca3..1cabc0f26 100644--- a/wger/manager/models.py+++ b/wger/manager/models.py@@ -35,8 +35,9 @@ logger = logging.getLogger('workout_manager.custom')class TrainingSchedule(models.Model):- """Model for a training schedule- """+ '''+ Model for a training schedule+ '''# Metaclass to set some other propertiesclass Meta:@@ -51,65 +52,71 @@ For example 'Focus on back' or 'Week 1 of program xy'.'''))user = models.ForeignKey(User, verbose_name=_('User'))def get_absolute_url(self):- """+ '''Returns the canonical URL to view a workout- """+ '''return reverse('wger.manager.views.view_workout', kwargs={'id': self.id})def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return str(self.creation_date)def get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return selfclass DaysOfWeek(models.Model):- """Model for the days of the week+ '''+ Model for the days of the weekThis model is needed so that 'Day' can have multiple days of the week selected- """+ '''day_of_week = models.CharField(max_length=9,verbose_name=_('Day of the week'))def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return self.day_of_weekclass Day(models.Model):- """Model for a training day- """+ '''+ Model for a training day+ '''training = models.ForeignKey(TrainingSchedule, verbose_name=_('Training'))description = models.CharField(max_length=100,verbose_name=_('Description'),- help_text=_('Ususally a description about what parts are trained, like "Arms" or "Pull Day"'))+ help_text=_('Ususally a description about what parts are '+ 'trained, like "Arms" or "Pull Day"'))day = models.ManyToManyField(DaysOfWeek,verbose_name=_('Day'))def __unicode__(self):- """+ '''Return a more human-readable representation- """+ '''return "%s for TP %s" % (self.description, unicode(self.training))def get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return self.trainingclass Set(models.Model):- """Model for a set of exercises- """+ '''+ Model for a set of exercises+ '''exerciseday = models.ForeignKey(Day, verbose_name=_('Exercise day'))exercises = models.ManyToManyField(Exercise, verbose_name=_('Exercises'))@@ -124,22 +131,24 @@ class Set(models.Model):ordering = ["order", ]def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return "Set-ID %s" % (self.id)def get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return self.exerciseday.trainingclass Setting(models.Model):- """Settings for an exercise (weight, reps, etc.)- """+ '''+ Settings for an exercise (weight, reps, etc.)+ '''- set = models.ForeignKey(Set, verbose_name = _('Sets'))+ set = models.ForeignKey(Set, verbose_name=_('Sets'))exercise = models.ForeignKey(Exercise, verbose_name=_('Exercises'))reps = models.IntegerField(validators=[MaxValueValidator(40)], verbose_name=_('Repetitions'))order = models.IntegerField(blank=True, verbose_name=_('Repetitions'))@@ -150,21 +159,22 @@ class Setting(models.Model):ordering = ["order", "id"]def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return "settings for exercise %s in set %s" % (self.exercise.id, self.set.id)def get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return self.set.exerciseday.trainingclass WorkoutLog(models.Model):- """+ '''A log entry for an exercise- """+ '''user = models.ForeignKey(User, verbose_name=_('User'))exercise = models.ForeignKey(Exercise, verbose_name=_('Exercise'))@@ -181,17 +191,17 @@ class WorkoutLog(models.Model):ordering = ["date", "reps"]def __unicode__(self):- """+ '''Return a more human-readable representation- """+ '''return "Log entry: %s - %s kg on %s" % (self.reps,self.weight,self.date)def get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return selfdef process_log_entries(self, logs):@@ -225,7 +235,7 @@ class WorkoutLog(models.Model):max_weight[entry.date][entry.reps] = entry.weightif entry.weight > max_weight[entry.date][entry.reps]:- max_weight[entry.date][entry.reps] = entry.weight+ max_weight[entry.date][entry.reps] = entry.weight# Group by repetitionsfor entry in logs:@@ -258,12 +268,14 @@ class UserProfile(models.Model):# Show exercise comments on workout viewshow_comments = models.BooleanField(verbose_name=_('Show exercise comments'),- help_text=_('Check to show exercise comments on the workout view'))+ help_text=_('Check to show exercise comments on the '+ 'workout view'))# Also show ingredients in english while composing a nutritional plan# (obviously this is only meaningful if the user has a language other than english)- show_english_ingredients = models.BooleanField(verbose_name=_('Also use ingredients in English'),- help_text=_('''Check to also show ingredients in English while creating+ show_english_ingredients = models.BooleanField(+ verbose_name=_('Also use ingredients in English'),+ help_text=_('''Check to also show ingredients in English while creatinga nutritional plan. These ingredients are extracted from a list providedby the US Department of Agriculture. It is extremely complete, with around7000 entries, but can be somewhat overwhelming and make the search difficult.'''))diff --git a/wger/manager/pdf.py b/wger/manager/pdf.pyindex 617e1cbba..38b057fe1 100644--- a/wger/manager/pdf.py+++ b/wger/manager/pdf.py@@ -45,7 +45,7 @@ def workout_log(request, id):"""Generates a PDF with the contents of the given workoutSee also- * http://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/+ * http://www.blog.pythonlibrary.org/2010/09/21/reportlab* http://www.reportlab.com/apis/reportlab/dev/platypus.html"""@@ -77,8 +77,7 @@ def workout_log(request, id):style = ParagraphStyle(name='Normal',#fontName='Helvetica-Bold',- fontSize=8,- )+ fontSize=8,)# table data, here we will put the workout infodata = []@@ -120,8 +119,8 @@ def workout_log(request, id):days_of_week = [_(day_of_week.day_of_week) for day_of_week in day.day.select_related()]P = Paragraph('<para align="center">%(days)s: <strong>%(description)s</strong></para>' %- {'days': ', '.join(days_of_week),- 'description': day.description},+ {'days': ', '.join(days_of_week),+ 'description': day.description},styleSheet["Normal"])data.append([P])@@ -182,19 +181,17 @@ def workout_log(request, id):rowheights = [None] * len(data)# Set general table styles- table_style = [- #('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),- #('BOX', (0,0), (-1,-1), 1.25, colors.black),- ('FONT', (0, 0), (-1, -1), 'Helvetica'),- ('FONTSIZE', (0, 0), (-1, -1), 8),- ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),-- # Note: a padding of 3 seems to be the default- ('LEFTPADDING', (0, 0), (-1, -1), 2),- ('RIGHTPADDING', (0, 0), (-1, -1), 0),- ('TOPPADDING', (0, 0), (-1, -1), 3),- ('BOTTOMPADDING', (0, 0), (-1, -1), 2),- ]+ #('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),+ #('BOX', (0,0), (-1,-1), 1.25, colors.black),+ table_style = [('FONT', (0, 0), (-1, -1), 'Helvetica'),+ ('FONTSIZE', (0, 0), (-1, -1), 8),+ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),++ # Note: a padding of 3 seems to be the default+ ('LEFTPADDING', (0, 0), (-1, -1), 2),+ ('RIGHTPADDING', (0, 0), (-1, -1), 0),+ ('TOPPADDING', (0, 0), (-1, -1), 3),+ ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ]# Set specific styles, e.g. background for title cellsfor marker in day_markers:@@ -232,7 +229,6 @@ def workout_log(request, id):table_style.append(('BACKGROUND', (1, j - 1), (-1, j - 1), colors.lavender))counter += 1-# Make the 'impression' span 3 cells and align it to the rightfor marker in group_day_marker:start_marker = group_day_marker[marker]['start']@@ -276,8 +272,8 @@ def workout_log(request, id):# Set the title (if available)if workout.comment:P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %- {'description': workout.comment},- styleSheet["Normal"])+ {'description': workout.comment},+ styleSheet["Normal"])elements.append(P)# Filler@@ -292,22 +288,21 @@ def workout_log(request, id):elements.append(P)# Print date and info+ created = datetime.date.today().strftime("%d.%m.%Y")+ url = reverse('wger.manager.views.view_workout', kwargs={'id': workout.id})P = Paragraph('''<para align="left">%(date)s -<a href="%(url)s">%(url)s</a> -%(created)s%(version)s</para>''' %- {'date' : _("Created on the <b>%s</b>") % datetime.date.today().strftime("%d.%m.%Y"),- 'created' : "wger Workout Manager",- 'version' : get_version(),- 'url' : request.build_absolute_uri(reverse('wger.manager.views.view_workout',- kwargs={'id': workout.id})),- },+ {'date': _("Created on the <b>%s</b>") % created,+ 'created': "wger Workout Manager",+ 'version': get_version(),+ 'url': request.build_absolute_uri(url), },styleSheet["Normal"])elements.append(P)-# write the document and send the response to the browserdoc.build(elements)diff --git a/wger/manager/templatetags/manager_extras.py b/wger/manager/templatetags/manager_extras.pyindex ca2dacc47..e4025ef73 100644--- a/wger/manager/templatetags/manager_extras.py+++ b/wger/manager/templatetags/manager_extras.py@@ -2,47 +2,51 @@ from django import templateregister = template.Library()+@register.filter(name='get_current_settings')def get_current_settings(exercise, set_id):- """Does a filter on the sets+ '''+ Does a filter on the setsWe need to do this here because it's not possible to pass arguments to function in the template,and we are only interested on the settings that belong to the current set- """+ '''return exercise.setting_set.filter(set_id=set_id)+@register.inclusion_tag('tags/render_day.html')def render_day(day):- """Renders a day as it will be displayed in the workout overview- """+ '''+ Renders a day as it will be displayed in the workout overview+ '''return {'day': day,- 'workout': day.training }+ 'workout': day.training}@register.inclusion_tag('tags/pagination.html')def pagination(page, page_range):- """+ '''Renders the necessary links to paginating a long list- """+ '''return {'page': page,- 'page_range': page_range }+ 'page_range': page_range}@register.inclusion_tag('tags/render_weight_log.html')def render_weight_log(log, div_uuid):- """+ '''Renders a weight log series- """+ '''return {'log': log,'div_uuid': div_uuid}@register.inclusion_tag('tags/yaml_form_element.html')-def yaml_form_field(field, css_class = 'ym-fbox-text'):- """+def yaml_form_field(field, css_class='ym-fbox-text'):+ '''Renders a form field in a <tr> with all necessary CSS- """+ '''return {'field': field,'css_class': css_class}@@ -50,8 +54,8 @@ def yaml_form_field(field, css_class = 'ym-fbox-text'):@register.inclusion_tag('tags/cc-by-sa-sidebar.html')def cc_by_sa_sidebar(language):- """+ '''Renders a form field in a <tr> with all necessary CSS- """+ '''return {'language': language}diff --git a/wger/manager/tests/copy_workout.py b/wger/manager/tests/copy_workout.pyindex af11041c6..b0515a9ff 100644--- a/wger/manager/tests/copy_workout.py+++ b/wger/manager/tests/copy_workout.py@@ -1,18 +1,17 @@# 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-from django.test import TestCasefrom django.core.urlresolvers import reversefrom wger.manager.models import TrainingSchedule@@ -20,61 +19,56 @@ from wger.manager.models import TrainingSchedulefrom wger.manager.tests.testcase import WorkoutManagerTestCase-class CopyWorkoutTestCase(WorkoutManagerTestCase):'''Tests copying a workout'''-- def copy_workout(self, logged_in = False):++ def copy_workout(self, logged_in=False):'''Helper function to test copying workouts'''-+# Open the copy workout formresponse = self.client.get(reverse('workout-copy', kwargs={'pk': '3'}))if not logged_in:- self.assertEqual(response.status_code, 302)+ self.assertEqual(response.status_code, 302)else:self.assertEqual(response.status_code, 200)-+# Copy the workoutcount_before = TrainingSchedule.objects.count()response = self.client.post(reverse('workout-copy', kwargs={'pk': '3'}),{'comment': 'A copied workout'})count_after = TrainingSchedule.objects.count()--+if not logged_in:self.assertEqual(count_before, count_after)- else:+ else:self.assertGreater(count_after, count_before)self.assertEqual(count_after, 4)-- self.assertTemplateUsed('workout/view.html')-- # Test accessing the copied workout++ self.assertTemplateUsed('workout/view.html')++ # Test accessing the copied workoutresponse = self.client.get(reverse('wger.manager.views.view_workout', kwargs={'id': 4}))-+if not logged_in:- self.assertEqual(response.status_code, 302)+ self.assertEqual(response.status_code, 302)else:- self.assertEqual(response.status_code, 200)--+ self.assertEqual(response.status_code, 200)+def test_copy_workout_anonymous(self):'''Test copying a workout as anonymous user'''-+self.copy_workout()--+def test_copy_workout_logged_in(self):'''Test copying a workout as a logged in user'''-+self.user_login('test')- self.copy_workout(logged_in = True)-+ self.copy_workout(logged_in=True)diff --git a/wger/manager/tests/demo_user.py b/wger/manager/tests/demo_user.pyindex 06e798b0f..6b6ad7b13 100644--- a/wger/manager/tests/demo_user.py+++ b/wger/manager/tests/demo_user.py@@ -1,18 +1,17 @@# 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-from django.test import TestCasefrom django.core.urlresolvers import reversefrom django.contrib.auth.models import User@@ -20,28 +19,27 @@ from django.contrib.auth.models import Userfrom wger.manager.tests.testcase import WorkoutManagerTestCase-class DemoUserTestCase(WorkoutManagerTestCase):'''Tests creating a demo user'''-+def test_demo_user(self):-+#os.environ['RECAPTCHA_TESTING'] = 'True'# Open the copy workout formresponse = self.client.get(reverse('demo-account'))self.assertEqual(response.status_code, 200)# Submit the form- count_before = User.objects.count()+ count_before = User.objects.count()response = self.client.post(reverse('demo-account'),{'recaptcha_response_field': 'PASSED'})count_after = User.objects.count()-+self.assertEqual(response.status_code, 302)response = self.client.get(reverse('dashboard'))-+# Check that the demo user was correctly createdself.assertEqual(count_before + 1, count_after)self.assertTrue(User.objects.filter(userprofile__is_temporary=1).count(), 1)diff --git a/wger/manager/tests/index.py b/wger/manager/tests/index.pyindex fc180cdd9..bcbade367 100644--- a/wger/manager/tests/index.py+++ b/wger/manager/tests/index.py@@ -58,7 +58,7 @@ class DashboardTestCase(WorkoutManagerTestCase):#self.client.get(reverse('wger.nutrition.views.add'))response = self.client.get(reverse('dashboard'))-+if logged_in:# There is something to send to the templateself.assertEqual(response.status_code, 200)@@ -75,9 +75,8 @@ class DashboardTestCase(WorkoutManagerTestCase):# Now, with weight#self.client.post(reverse('weight-add'),- {'weight': 100,- 'creation_date': '2012-01-01'},- )+ {'weight': 100,+ 'creation_date': '2012-01-01'},)response = self.client.get(reverse('dashboard'))if logged_in:@@ -106,4 +105,3 @@ class DashboardTestCase(WorkoutManagerTestCase):self.user_login('test')self.dashboard(logged_in=True)-diff --git a/wger/manager/tests/testcase.py b/wger/manager/tests/testcase.pyindex 5e1e4847a..ac2c216dc 100644--- a/wger/manager/tests/testcase.py+++ b/wger/manager/tests/testcase.py@@ -22,13 +22,14 @@ from django.test import LiveServerTestCasefrom selenium import webdriverfrom selenium.webdriver.common.keys import Keys+class WorkoutManagerTestCase(TestCase):fixtures = ('tests-user-data','test-exercises','tests-ingredients','days_of_week','tests-workout-data')-+def setUp(self):'''Overwrite some of Django's settings here@@ -65,7 +66,6 @@ class WorkoutManagerLiveServerTestCase(LiveServerTestCase):'tests-days-of-week','tests-workout-data')-def setUp(self):"""Set up out testing browser@@ -77,7 +77,6 @@ class WorkoutManagerLiveServerTestCase(LiveServerTestCase):self.browser = webdriver.Firefox(profile)self.browser.implicitly_wait(3)-def tearDown(self):"""Quit the browserdiff --git a/wger/manager/tests/weight_log.py b/wger/manager/tests/weight_log.pyindex 6afd7fd18..dc3b99788 100644--- a/wger/manager/tests/weight_log.py+++ b/wger/manager/tests/weight_log.py@@ -53,7 +53,6 @@ class WeightLogTestCase(WorkoutManagerTestCase):self.assertTrue(response.status_code in (302, 403))else:self.assertEqual(response.status_code, 200)-# Add new log entriescount_before = WorkoutLog.objects.count()@@ -64,7 +63,7 @@ class WeightLogTestCase(WorkoutManagerTestCase):'form-TOTAL_FORMS': 3,'form-INITIAL_FORMS': 0,'form-MAX-NUM_FORMS': 3- })+ })count_after = WorkoutLog.objects.count()diff --git a/wger/manager/tests/workout.py b/wger/manager/tests/workout.pyindex ebcccf6c8..8ebe896a4 100644--- a/wger/manager/tests/workout.py+++ b/wger/manager/tests/workout.py@@ -1,18 +1,17 @@# 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-from django.test import TestCasefrom django.core.urlresolvers import reversefrom wger.manager.models import TrainingSchedule@@ -20,69 +19,72 @@ from wger.manager.models import TrainingSchedulefrom wger.manager.tests.testcase import WorkoutManagerTestCase-class AddWorkoutTestCase(WorkoutManagerTestCase):- """Tests adding a Workout"""-- def create_workout(self, logged_in = False):- """Helper function to test creating workouts"""-+ '''+ Tests adding a Workout+ '''++ def create_workout(self, logged_in=False):+ '''+ Helper function to test creating workouts+ '''+# Create a workoutcount_before = TrainingSchedule.objects.count()response = self.client.get(reverse('wger.manager.views.add'))count_after = TrainingSchedule.objects.count()-+# There is always a redirect- self.assertEqual(response.status_code, 302)--+ self.assertEqual(response.status_code, 302)+# Test creating workoutif not logged_in:-+self.assertEqual(count_before, count_after)self.assertEqual(count_after, 3)- self.assertTemplateUsed('login.html')-- else:+ self.assertTemplateUsed('login.html')++ else:self.assertGreater(count_after, count_before)- self.assertTemplateUsed('workout/view.html')-- # Test accessing workout+ self.assertTemplateUsed('workout/view.html')++ # Test accessing workoutresponse = self.client.get(reverse('wger.manager.views.view_workout', kwargs={'id': 1}))-+if logged_in:- workout = TrainingSchedule.objects.get(pk = 1)+ workout = TrainingSchedule.objects.get(pk=1)self.assertEqual(response.context['workout'], workout)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 200)else:self.assertEqual(response.status_code, 302)#workout = TrainingSchedule.objects.get(pk = 1)---+def test_create_workout_anonymous(self):'''Test creating a workout as anonymous user'''-+self.user_logout()self.create_workout()--+def test_create_workout_logged_in(self):'''Test creating a workout a logged in user'''-+self.user_login()- self.create_workout(logged_in = True)+ self.create_workout(logged_in=True)self.user_logout()class WorkoutOverviewTestCase(WorkoutManagerTestCase):- """Tests the workout overview"""-- def get_workout_overview(self, logged_in = False):- """Helper function to test the workout overview"""-+ '''+ Tests the workout overview+ '''++ def get_workout_overview(self, logged_in=False):+ '''+ Helper function to test the workout overview+ '''+response = self.client.get(reverse('wger.manager.views.overview'))-+# Page existsif logged_in:self.assertEqual(response.status_code, 200)@@ -90,21 +92,21 @@ class WorkoutOverviewTestCase(WorkoutManagerTestCase):else:self.assertEqual(response.status_code, 302)return-+# There are workouts sent to the templateself.assertTrue(response.context['workouts'])--+def test_dashboard_anonymous(self):- '''Test creating a workout as anonymous user'''+ '''+ Test creating a workout as anonymous user+ '''self.user_logout()self.get_workout_overview()--+def test_dashboard_logged_in(self):- '''Test creating a workout a logged in user'''+ '''+ Test creating a workout a logged in user+ '''self.user_login()- self.get_workout_overview(logged_in = True)+ self.get_workout_overview(logged_in=True)self.user_logout()--diff --git a/wger/manager/utils.py b/wger/manager/utils.pyindex e6b872d83..f92103292 100644--- a/wger/manager/utils.py+++ b/wger/manager/utils.py@@ -64,4 +64,3 @@ def load_ingredient_languages(request):languages = (language.id, 2)return languages-diff --git a/wger/manager/views.py b/wger/manager/views.pyindex 15495dac6..dc654927d 100644--- a/wger/manager/views.py+++ b/wger/manager/views.py@@ -95,9 +95,10 @@ def index(request):@login_requireddef dashboard(request):- """Show the index page, in our case, the last workout and nutritional plan+ '''+ Show the index page, in our case, the last workout and nutritional planand the current weight- """+ '''template_data = {}@@ -117,7 +118,7 @@ def dashboard(request):# Load the last logged weight entry, if one existstry:- weight = WeightEntry.objects.filter(user=request.user).latest('creation_date')+ weight = WeightEntry.objects.filter(user=request.user).latest('creation_date')except ObjectDoesNotExist:weight = Falsetemplate_data['weight'] = weight@@ -153,24 +154,26 @@ def dashboard(request):# User functions# ************************def login(request):- """+ '''Small wrapper around the django login view- """+ '''return django_loginview(request,template_name='user/login.html')def logout(request):- """Logout the user- """+ '''+ Logout the user+ '''django_logout(request)return HttpResponseRedirect(reverse('login'))def registration(request):- """A form to allow for registration of new users- """+ '''+ A form to allow for registration of new users+ '''template_data = {}template_data.update(csrf(request))@@ -244,7 +247,7 @@ def create_demo_user(request):day.day.add(monday)day2 = Day(training=workout,- description=_('Another sample day'))+ description=_('Another sample day'))day2.save()day2.day.add(wednesday)@@ -341,9 +344,10 @@ def create_demo_user(request):# (Body) weight entriesfor i in range(1, 20):+ creation_date = datetime.date.today() - datetime.timedelta(days=i)entry = WeightEntry(user=user,- weight=80 + 0.5*i + random.randint(1, 3),- creation_date=datetime.date.today() - datetime.timedelta(days=i))+ weight=80 + 0.5*i + random.randint(1, 3),+ creation_date=creation_date)entry.save()user = authenticate(username=username, password=password)@@ -361,8 +365,9 @@ def create_demo_user(request):def preferences(request):- """An overview of all user preferences- """+ '''+ An overview of all user preferences+ '''template_data = {}template_data.update(csrf(request))@@ -403,8 +408,9 @@ def preferences(request):@login_requireddef api_user_preferences(request):- """ Allows the user to edit its preferences via AJAX calls- """+ '''+ Allows the user to edit its preferences via AJAX calls+ '''if request.is_ajax():@@ -434,8 +440,9 @@ def api_user_preferences(request):# ************************@login_requireddef overview(request):- """An overview of all the user's workouts- """+ '''+ An overview of all the user's workouts+ '''template_data = {}@@ -449,8 +456,9 @@ def overview(request):@login_requireddef view_workout(request, id):- """Show the workout with the given ID- """+ '''+ Show the workout with the given ID+ '''template_data = {}workout = get_object_or_404(TrainingSchedule, pk=id, user=request.user)@@ -490,9 +498,9 @@ def view_workout(request, id):@login_requireddef copy_workout(request, pk):- """+ '''Makes a copy of a workout- """+ '''workout = get_object_or_404(TrainingSchedule, pk=pk, user=request.user)@@ -543,37 +551,40 @@ def copy_workout(request, pk):setting_copy.set = current_set_copysetting_copy.save()- return HttpResponseRedirect(reverse('wger.manager.views.view_workout', kwargs={'id': workout.id}))+ return HttpResponseRedirect(reverse('wger.manager.views.view_workout',+ kwargs={'id': workout.id}))else:- workout_form = WorkoutCopyForm({'comment':workout.comment})+ workout_form = WorkoutCopyForm({'comment': workout.comment})template_data = {}template_data.update(csrf(request))- template_data['title'] = _('Copy workout')- template_data['form'] = workout_form+ template_data['title'] = _('Copy workout')+ template_data['form'] = workout_formtemplate_data['form_action'] = reverse('workout-copy', kwargs={'pk': workout.id})template_data['form_fields'] = [workout_form['comment']]return render_to_response('form.html',- template_data,- context_instance=RequestContext(request))+ template_data,+ context_instance=RequestContext(request))@login_requireddef add(request):- """Add a new workout and redirect to its page- """+ '''+ Add a new workout and redirect to its page+ '''workout = TrainingSchedule()workout.user = request.userworkout.save()- return HttpResponseRedirect(reverse('wger.manager.views.view_workout', kwargs={'id': workout.id}))+ return HttpResponseRedirect(reverse('wger.manager.views.view_workout',+ kwargs={'id': workout.id}))class WorkoutDeleteView(YamlDeleteMixin, DeleteView):- """+ '''Generic view to delete a workout routine- """+ '''model = TrainingSchedulesuccess_url = reverse_lazy('wger.manager.views.overview')@@ -582,9 +593,9 @@ class WorkoutDeleteView(YamlDeleteMixin, DeleteView):class WorkoutEditView(YamlFormMixin, UpdateView):- """+ '''Generic view to update an existing workout routine- """+ '''model = TrainingScheduleform_class = WorkoutForm@@ -596,9 +607,9 @@ class WorkoutEditView(YamlFormMixin, UpdateView):# Day functions# ************************class DayView(YamlFormMixin):- """+ '''Base generic view for exercise day- """+ '''model = Dayform_class = DayForm@@ -607,8 +618,9 @@ class DayView(YamlFormMixin):return reverse('wger.manager.views.view_workout', kwargs={'id': self.object.training_id})def get_form(self, form_class):- """- Filter the days of the week that are alreeady used by other days"""+ '''+ Filter the days of the week that are alreeady used by other days+ '''# Get the formform = super(DayView, self).get_form(form_class)@@ -633,27 +645,26 @@ class DayView(YamlFormMixin):class DayEditView(DayView, UpdateView):- """+ '''Generic view to update an existing exercise day- """+ '''title = ugettext_lazy('Edit workout day')form_action_urlname = 'day-edit'class DayCreateView(DayView, CreateView):- """+ '''Generic view to add a new exercise day- """+ '''title = ugettext_lazy('Add workout day')owner_object = {'pk': 'workout_pk', 'class': TrainingSchedule}-def form_valid(self, form):- """+ '''Set the workout this day belongs to- """+ '''form.instance.training = TrainingSchedule.objects.get(pk=self.kwargs['workout_pk'])return super(DayCreateView, self).form_valid(form)@@ -667,8 +678,9 @@ class DayCreateView(DayView, CreateView):@login_requireddef delete_day(request, id, day_id):- """Deletes the day with ID day_id belonging to workout with ID id- """+ '''+ Deletes the day with ID day_id belonging to workout with ID id+ '''# Load the dayday = get_object_or_404(Day, pk=day_id)@@ -683,10 +695,11 @@ def delete_day(request, id, day_id):@login_requireddef view_day(request, id):- """Renders a day as shown in the workout overview.+ '''+ Renders a day as shown in the workout overview.This function is to be used with AJAX calls.- """+ '''template_data = {}# Load day and check if its workout belongs to the user@@ -706,8 +719,9 @@ def view_day(request, id):# ************************@login_requireddef edit_set(request, id, day_id, set_id=None):- """ Edits/creates a set- """+ '''+ Edits/creates a set+ '''template_data = {}template_data.update(csrf(request))@@ -755,7 +769,8 @@ def edit_set(request, id, day_id, set_id=None):# The exercises are ManyToMany in DB, so we have to save with this functionset_form.save_m2m()- return HttpResponseRedirect(reverse('wger.manager.views.view_workout', kwargs={'id': id}))+ return HttpResponseRedirect(reverse('wger.manager.views.view_workout',+ kwargs={'id': id}))else:set_form = SetForm(instance=workout_set)template_data['set_form'] = set_form@@ -767,8 +782,9 @@ def edit_set(request, id, day_id, set_id=None):@login_requireddef delete_set(request, id, day_id, set_id):- """ Deletes the given set- """+ '''+ Deletes the given set+ '''# Load the setset_obj = get_object_or_404(Set, pk=set_id)@@ -783,8 +799,9 @@ def delete_set(request, id, day_id, set_id):@login_requireddef api_edit_set(request):- """ Allows to edit the order of the sets via an AJAX call- """+ '''+ Allows to edit the order of the sets via an AJAX call+ '''if request.is_ajax():@@ -875,7 +892,6 @@ def api_edit_set(request):setting_id = int(i.split('-')[-1])setting = get_object_or_404(Setting, pk=setting_id)-# Check if the new value is empty (the user wants the setting deleted)# We don't check more, if the user enters a string, it won't be converted# and nothing will happen@@ -908,8 +924,8 @@ def api_edit_set(request):template_data['exercise'] = exercisereturn render_to_response('setting/ajax_edit.html',- template_data,- context_instance=RequestContext(request))+ template_data,+ context_instance=RequestContext(request))# ************************@@ -969,7 +985,8 @@ def edit_setting(request, id, set_id, exercise_id, setting_id=None):order += 1- return HttpResponseRedirect(reverse('wger.manager.views.view_workout', kwargs={'id': id}))+ return HttpResponseRedirect(reverse('wger.manager.views.view_workout',+ kwargs={'id': id}))else:setting_form = SettingFormSet(queryset=Setting.objects.filter(exercise_id=exercise.id,set_id=set_obj.id))@@ -979,10 +996,12 @@ def edit_setting(request, id, set_id, exercise_id, setting_id=None):template_data,context_instance=RequestContext(request))+@login_requireddef api_edit_setting(request):- """ Allows to edit the order of the setting inside a set via an AJAX call- """+ '''+ Allows to edit the order of the setting inside a set via an AJAX call+ '''if request.is_ajax():if request.GET.get('do') == 'set_order':@@ -1007,8 +1026,9 @@ def api_edit_setting(request):@login_requireddef delete_setting(request, id, set_id, exercise_id):- """Deletes all the settings belonging to set_id and exercise_id- """+ '''+ Deletes all the settings belonging to set_id and exercise_id+ '''# Load the workoutworkout = get_object_or_404(TrainingSchedule, pk=id, user=request.user)@@ -1024,9 +1044,9 @@ def delete_setting(request, id, set_id, exercise_id):# Log functions# ************************class WorkoutLogUpdateView(YamlFormMixin, UpdateView):- """+ '''Generic view to edit an existing workout log weight entry- """+ '''model = WorkoutLogform_class = WorkoutLogFormcustom_js = '''$(document).ready(function () {@@ -1086,11 +1106,11 @@ def workout_log_add(request, pk):# Define the formset here because now we know the value to pass to 'extra'WorkoutLogFormSet = modelformset_factory(WorkoutLog,- form=WorkoutLogForm,- exclude=('user',- 'workout',- 'date'),- extra = total_sets)+ form=WorkoutLogForm,+ exclude=('user',+ 'workout',+ 'date'),+ extra = total_sets)# Process the requestif request.method == 'POST':@@ -1116,9 +1136,9 @@ def workout_log_add(request, pk):instances = formset.save(commit=False)for instance in instances:- instance.user = request.user- instance.workout = day.training- instance.date = log_date+ instance.user = request.user+ instance.workout = day.training+ instance.date = log_dateinstance.save()return HttpResponseRedirect(reverse('workout-log', kwargs={'pk': day.training_id}))@@ -1135,7 +1155,7 @@ def workout_log_add(request, pk):form_id_from = min(exercise_list[exercise]['form_ids'])form_id_to = max(exercise_list[exercise]['form_ids'])- exercise_list[exercise]['forms'] = formset[form_id_from:form_id_to +1]+ exercise_list[exercise]['forms'] = formset[form_id_from:form_id_to + 1]template_data['day'] = daytemplate_data['exercises'] = exercise_list@@ -1191,9 +1211,9 @@ class WorkoutLogDetailView(DetailView):return contextdef dispatch(self, request, *args, **kwargs):- """+ '''Check for ownership- """+ '''workout = TrainingSchedule.objects.get(pk=kwargs['pk'])if workout.user != request.user:@@ -1201,4 +1221,3 @@ class WorkoutLogDetailView(DetailView):# Dispatch normallyreturn super(WorkoutLogDetailView, self).dispatch(request, *args, **kwargs)-diff --git a/wger/nutrition/models.py b/wger/nutrition/models.pyindex e283fdf9e..870b98990 100644--- a/wger/nutrition/models.py+++ b/wger/nutrition/models.py@@ -18,7 +18,7 @@from django.db import models-from django.template.defaultfilters import slugify # django.utils.text.slugify in django 1.5!+from django.template.defaultfilters import slugify # django.utils.text.slugify in django 1.5!from django.core.validators import MaxValueValidatorfrom django.core.urlresolvers import reversefrom django.contrib.auth.models import User@@ -28,8 +28,9 @@ from wger.exercises.models import Languageclass NutritionPlan(models.Model):- """ A nutrition plan- """+ '''+ A nutrition plan+ '''# Metaclass to set some other propertiesclass Meta:@@ -43,17 +44,19 @@ class NutritionPlan(models.Model):description = models.TextField(max_length=2000,blank=True,verbose_name=_('Description'),- help_text=_('A description of the goal of the plan, e.g. "Gain mass" or "Prepare for summer"'))+ help_text=_('A description of the goal of the plan, e.g. '+ '"Gain mass" or "Prepare for summer"'))def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return "Nutrition plan for %s, %s" % (self.user, self.creation_date)def get_absolute_url(self):- """+ '''Returns the canonical URL to view this object- """+ '''return reverse('wger.nutrition.views.view', kwargs={'id': self.id})def get_nutritional_values(self):@@ -73,31 +76,39 @@ class NutritionPlan(models.Model):if item.ingredient and item.amount_gramm:nutritional_info['energy'] += item.ingredient.energy * item.amount_gramm / 100nutritional_info['protein'] += item.ingredient.protein * item.amount_gramm / 100- nutritional_info['carbohydrates'] += item.ingredient.carbohydrates * item.amount_gramm / 100+ nutritional_info['carbohydrates'] += item.ingredient.carbohydrates * \+ item.amount_gramm / 100+if item.ingredient.carbohydrates_sugar:- nutritional_info['carbohydrates_sugar'] += item.ingredient.carbohydrates_sugar * item.amount_gramm / 100+ nutritional_info['carbohydrates_sugar'] += \+ item.ingredient.carbohydrates_sugar * \+ item.amount_gramm / 100nutritional_info['fat'] += item.ingredient.fat * item.amount_gramm / 100if item.ingredient.fat_saturated:- nutritional_info['fat_saturated'] += item.ingredient.fat_saturated * item.amount_gramm / 100+ nutritional_info['fat_saturated'] += item.ingredient.fat_saturated * \+ item.amount_gramm / 100if item.ingredient.fibres:- nutritional_info['fibres'] += item.ingredient.fibres * item.amount_gramm / 100+ nutritional_info['fibres'] += item.ingredient.fibres * \+ item.amount_gramm / 100if item.ingredient.sodium:- nutritional_info['sodium'] += item.ingredient.sodium * item.amount_gramm / 100+ nutritional_info['sodium'] += item.ingredient.sodium * \+ item.amount_gramm / 100return nutritional_infodef get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return selfclass Ingredient(models.Model):- """ An ingredient, with some approximate nutrition values- """+ '''+ An ingredient, with some approximate nutrition values+ '''# Metaclass to set some other propertiesclass Meta:@@ -108,17 +119,14 @@ class Ingredient(models.Model):name = models.CharField(max_length=200,verbose_name=_('Name'),)- energy = models.IntegerField(- verbose_name=_('Energy'),+ energy = models.IntegerField(verbose_name=_('Energy'),help_text=_('In kcal per 100g'))- protein = models.FloatField(- verbose_name=_('Protein'),+ protein = models.FloatField(verbose_name=_('Protein'),help_text=_('In g per 100g of product'))- carbohydrates = models.FloatField(- verbose_name=_('Carbohydrates'),- help_text=_('In g per 100g of product'))+ carbohydrates = models.FloatField(verbose_name=_('Carbohydrates'),+ help_text=_('In g per 100g of product'))carbohydrates_sugar = models.FloatField(blank=True,null=True,@@ -126,8 +134,8 @@ class Ingredient(models.Model):help_text=_('In g per 100g of product'))fat = models.FloatField(blank=True,- verbose_name=_('Fat'),- help_text=_('In g per 100g of product'))+ verbose_name=_('Fat'),+ help_text=_('In g per 100g of product'))fat_saturated = models.FloatField(blank=True,null=True,@@ -145,27 +153,29 @@ class Ingredient(models.Model):help_text=_('In g per 100g of product'))def get_absolute_url(self):- """+ '''Returns the canonical URL to view this object- """+ '''return reverse('wger.nutrition.views.ingredient_view', kwargs={'id': self.id,- 'slug': slugify(self.name)})+ 'slug': slugify(self.name)})def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return "%s" % (self.name, )def get_owner_object(self):- """+ '''Ingredient has no owner information- """+ '''return Falseclass Meal(models.Model):- """ A meal- """+ '''+ A meal+ '''# Metaclass to set some other propertiesclass Meta:@@ -176,20 +186,22 @@ class Meal(models.Model):time = models.TimeField(null=True, blank=True, verbose_name=_('Time (approx)'))def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return "%s Meal" % (self.order,)def get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return self.planclass MealItem(models.Model):- """ An item (component) of a meal- """+ '''+ An item (component) of a meal+ '''meal = models.ForeignKey(Meal, verbose_name=_('Nutrition plan'))order = models.IntegerField(max_length=1, blank=True, verbose_name=_('Order'))@@ -200,13 +212,13 @@ class MealItem(models.Model):ingredient = models.ForeignKey(Ingredient, verbose_name=_('Ingredient'))def __unicode__(self):- """Return a more human-readable representation- """+ '''+ Return a more human-readable representation+ '''return "%sg ingredient %s" % (self.amount_gramm, self.ingredient_id)def get_owner_object(self):- """+ '''Returns the object that has owner information- """+ '''return self.meal.plan-diff --git a/wger/nutrition/tests.py b/wger/nutrition/tests.pydeleted file mode 100644index 66f8cec12..000000000--- a/wger/nutrition/tests.py+++ /dev/null@@ -1,107 +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.core.urlresolvers import reverse--from wger.manager.tests.testcase import WorkoutManagerLiveServerTestCase--logger = logging.getLogger('workout_manager.custom')---#class NutritionTest(WorkoutManagerLiveServerTestCase):-- #def test_create_plan(self):- #"""- #Tests that it's possible to create a complete nutritional plan- #"""-- #self.browser.get(self.live_server_url + reverse('nutrition.views.overview'))- #self.user_login(explicit_login=False)-- ## No plans, there is a warning box- #box = self.browser.find_elements_by_id('nutrition-box-warning')- #self.assertTrue(box)-- ## Clink on the link and enter the weight in the modal dialog- #create_link = self.browser.find_elements_by_id('nutrition-create-new')- #self.assertTrue(create_link)- #create_link[0].click()-- ## No meals, there is a warning box- #box = self.browser.find_elements_by_id('meal-box-warning')[0]- #self.assertTrue(box)-- ## Clink on the link and enter the time in the modal dialog- #create_link = box.find_elements_by_tag_name('a')- #self.assertTrue(create_link)- #create_link[0].click()-- ## Check that there is a modal dialog- #(dialog_title, dialog_content) = self.check_modal_dialog()-- ## Put some number into the time field- #weight_input = dialog_content.find_elements_by_id('id_time')[0]- #self.assertTrue(weight_input)- #weight_input.send_keys('8:00')-- #save_button = dialog_content.find_element_by_id('form-save')- #save_button.click()-- ## Warning box for meals has disappeared- #box = self.browser.find_elements_by_id('meal-box-warning')- #self.assertFalse(box)-- ## There is now 1 warning box for ingredients- #box = self.browser.find_elements_by_class_name('ingredient-box-warning')- #self.assertEqual(len(box), 1)-- ## Click on the link to add a new ingredient- #create_link = box[0].find_elements_by_tag_name('a')[0]- #self.assertTrue(create_link)- #create_link.click()-- ## Check that there is a modal dialog- #(dialog_title, dialog_content) = self.check_modal_dialog()-- ## Set the data- ##id_amount_gramm- #amount_input = dialog_content.find_elements_by_id('id_amount_gramm')[0]- #self.assertTrue(amount_input)- #amount_input.send_keys('150')-- #ingredient_autocomplete = dialog_content.find_elements_by_id('id_ingredient_searchfield')[0]- #self.assertTrue(ingredient_autocomplete)-- ##We want to find "Ingredient, test, 2, organic, raw"- #ingredient_autocomplete.click()- #ingredient_autocomplete.send_keys('raw')- #autocompleter_input = self.browser.find_elements_by_class_name('ui-autocomplete')[0]- #self.assertTrue(amount_input, 'Ingredient autocompleter not found')- ## there is one result- #autocompleter_result = self.browser.find_elements_by_class_name('ui-menu-item')- #self.assertEqual(len(autocompleter_result), 1)- #autocompleter_result[0].click()-- #save_button = dialog_content.find_element_by_id('form-save')- #save_button.click()-- ## Warning box for ingredients has disappeared- #box = self.browser.find_elements_by_class_name('ingredient-box-warning')- #self.assertFalse(box)---#diff --git a/wger/nutrition/views.py b/wger/nutrition/views.pyindex 780e46894..51238331b 100644--- a/wger/nutrition/views.py+++ b/wger/nutrition/views.py@@ -177,7 +177,7 @@ def export_pdf(request, id):"""Generates a PDF with the contents of a nutrition planSee also- * http://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/+ * http://www.blog.pythonlibrary.org/2010/09/21/reportlab* http://www.reportlab.com/apis/reportlab/dev/platypus.html"""@@ -223,13 +223,14 @@ def export_pdf(request, id):if not meal.time:P = Paragraph('<para align="center"><strong>%(meal_nr)s</strong></para>' %- {'meal_nr': i},- styleSheet["Normal"])+ {'meal_nr': i},+ styleSheet["Normal"])else:- P = Paragraph('<para align="center"><strong>%(meal_nr)s - %(meal_time)s</strong></para>' %- {'meal_nr': i,- 'meal_time': meal.time.strftime("%H:%M")},- styleSheet["Normal"])+ P = Paragraph('<para align="center"><strong>%(meal_nr)s - '+ '%(meal_time)s</strong></para>' %+ {'meal_nr': i,+ 'meal_time': meal.time.strftime("%H:%M")},+ styleSheet["Normal"])data.append([P])# Ingredients@@ -241,10 +242,10 @@ def export_pdf(request, id):data.append(["%sg" % item.amount_gramm, P])# Set general table styles- table_style = [- #('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),- #('BOX', (0,0), (-1,-1), 0.25, colors.black)- ]++ #('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),+ #('BOX', (0,0), (-1,-1), 0.25, colors.black)+ table_style = []# Set specific styles, e.g. background for title cellsfor marker in meal_markers:@@ -263,8 +264,8 @@ def export_pdf(request, id):# Set the title (if available)if plan.description:P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %- {'description': plan.description},- styleSheet["Normal"])+ {'description': plan.description},+ styleSheet["Normal"])elements.append(P)# Filler@@ -280,9 +281,10 @@ def export_pdf(request, id):# Print date and infoP = Paragraph('<para align="left">%(date)s - %(created)s v%(version)s</para>' %- {'date': _("Created on the <b>%s</b>") % plan.creation_date.strftime("%d.%m.%Y"),- 'created': "Workout Manager",- 'version': get_version()},+ {'date': _("Created on the <b>%s</b>") %+ plan.creation_date.strftime("%d.%m.%Y"),+ 'created': "Workout Manager",+ 'version': get_version()},styleSheet["Normal"])elements.append(P)diff --git a/wger/weight/helpers.py b/wger/weight/helpers.pyindex 0f9f32a10..bd899edc0 100644--- a/wger/weight/helpers.py+++ b/wger/weight/helpers.py@@ -31,7 +31,7 @@ def parse_weight_csv(request, cleaned_data):dialect = csv.Sniffer().sniff(cleaned_data['csv_input'])except csv.Error:#logger.debug('Error while sniffing CSV format')- dialect='excel'+ dialect = 'excel'# csv.reader expects a file-like object, so use StringIOparsed_csv = csv.reader(StringIO.StringIO(cleaned_data['csv_input']),@@ -43,11 +43,11 @@ def parse_weight_csv(request, cleaned_data):try:parsed_date = datetime.datetime.strptime(row[0], cleaned_data['date_format'])parsed_weight = decimal.Decimal(row[1].replace(',', '.'))-+weight_list.append(WeightEntry(creation_date=parsed_date,weight=parsed_weight,user=request.user))-+except (ValueError, IndexError, decimal.InvalidOperation), e:error_list.append(row)#logger.debug(row)diff --git a/wger/weight/models.py b/wger/weight/models.pyindex 73ec02cff..0cd7d1df2 100644--- a/wger/weight/models.py+++ b/wger/weight/models.py@@ -44,4 +44,3 @@ class WeightEntry(models.Model):Returns the object that has owner information"""return self-diff --git a/wger/weight/tests/__init__.py b/wger/weight/tests/__init__.pyindex a1c4205af..0a60fdc93 100644--- a/wger/weight/tests/__init__.py+++ b/wger/weight/tests/__init__.py@@ -1,2 +1 @@-from wger.weight.tests.entry import *from wger.weight.tests.csv_import import *diff --git a/wger/weight/tests/csv_import.py b/wger/weight/tests/csv_import.pyindex 471b66604..1e5187429 100644--- a/wger/weight/tests/csv_import.py+++ b/wger/weight/tests/csv_import.py@@ -96,4 +96,3 @@ class WeightCsvImportTestCase(WorkoutManagerTestCase):self.user_login('test')self.import_csv(fail=False)-diff --git a/wger/weight/tests/entry.py b/wger/weight/tests/entry.pydeleted file mode 100644index a4194a704..000000000--- a/wger/weight/tests/entry.py+++ /dev/null@@ -1,155 +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.core.urlresolvers import reverse--from wger.manager.tests.testcase import WorkoutManagerLiveServerTestCase--logger = logging.getLogger('workout_manager.custom')---#class WeigtTest(WorkoutManagerLiveServerTestCase):-- #def add_weight_entry(self, weight=80, day_index=0):- #"""- #Helper function that adds a weight entry- #"""-- ## Clink on the link and enter the weight in the modal dialog- #add_entry_link = self.browser.find_elements_by_id('add-weight-entry')- #self.assertTrue(add_entry_link)-- #add_entry_link[0].click()-- #modal_dialog = self.browser.find_elements_by_class_name('ui-dialog')[0]- #self.assertTrue(modal_dialog)-- ## Found the title- #dialog_title = modal_dialog.find_elements_by_id('ui-id-1')- #self.assertTrue(dialog_title)-- ## Found the content- #dialog_content = modal_dialog.find_elements_by_id('ajax-info')[0]- #self.assertTrue(dialog_content)-- ## Put some number into the weight input- #weight_input = modal_dialog.find_elements_by_id('id_weight')[0]- #self.assertTrue(weight_input)- #weight_input.send_keys(weight)-- ## Focus on the date, a date picker should appear, select something- #date_input = modal_dialog.find_elements_by_id('id_creation_date')[0]- #self.assertTrue(date_input)- #date_input.click()- #datepicker_div = self.browser.find_elements_by_id('ui-datepicker-div')[0]- #day = datepicker_div.find_elements_by_tag_name('tbody')[0].find_elements_by_tag_name('a')[day_index]- #day.click()-- #save_button = dialog_content.find_element_by_id('form-save')- #save_button.click()-- #def test_weight_index_empty(self):- #"""- #Tests that the weight overview page has no content if there are no- #weight entries- #"""-- #self.user_login()- #self.browser.get(self.live_server_url + reverse('weight.views.overview'))-- ## No diagram- #svg = self.browser.find_elements_by_tag_name('svg')- #self.assertFalse(svg)-- ## Warning box- #warning_box = self.browser.find_elements_by_id('weight-box-warning')- #self.assertTrue(warning_box)-- #def test_add_weight_entry(self):- #"""- #Tests that it's possible to add a weight entry and that this appears- #in the overview- #"""-- #self.user_login()- #self.browser.get(self.live_server_url + reverse('weight.views.overview'))- #self.add_weight_entry()-- #def test_weight_index_data(self):- #"""- #Tests that after adding weight entries, there is a diagram generated- #"""-- #self.user_login()- #self.browser.get(self.live_server_url + reverse('weight.views.overview'))- #self.add_weight_entry(70, 0)- #self.add_weight_entry(71, 1)- #self.add_weight_entry(76, 2)- #self.add_weight_entry(80, 3)- #self.add_weight_entry(86, 4)- #self.add_weight_entry(81, 5)- #self.add_weight_entry(83, 7)-- ## There is a diagram with 8 data points- #svg_points = self.browser.find_elements_by_tag_name('circle')- #self.assertTrue(len(svg_points), 8)-- ## There is no warning box anymore- #warning_box = self.browser.find_elements_by_id('weight-box-warning')- #self.assertFalse(warning_box)-- ##- ## Edit- ##-- ## Note: it seems selenium can't click on SVG elements- ##svg_points[0].click()- ##modal_dialog = self.browser.find_elements_by_class_name('ui-dialog')[0]- ##weight_entry = self.browser.find_elements_by_id('id_weight')- ##self.assertTrue(weight_entry)- ##self.assertTrue(weight_entry[0].value, 70)-- ##- ## Filter the results- ##- #svg_points_orig = self.browser.find_elements_by_tag_name('circle')-- ## Set the dates- #date_from = self.browser.find_elements_by_id('weight_filter_from')[0]- #date_to = self.browser.find_elements_by_id('weight_filter_to')[0]-- ## Open the datepicker and select the first element for from date- #date_from.click()- #datepicker_div = self.browser.find_elements_by_id('ui-datepicker-div')[0]- #day = datepicker_div.find_elements_by_tag_name('tbody')[0].find_elements_by_tag_name('a')[0]- #day.click()-- ## Open the datepicker and select the 3rd element for to date- #date_to.click()- #datepicker_div = self.browser.find_elements_by_id('ui-datepicker-div')[0]- #day = datepicker_div.find_elements_by_tag_name('tbody')[0].find_elements_by_tag_name('a')[3]- #day.click()-- ## Filter- #refresh_button = self.browser.find_elements_by_id('weight_diagram_refresh')[0]- #refresh_button.click()-- ## There is a diagram less data points- #svg_points = self.browser.find_elements_by_tag_name('circle')- #self.assertTrue(len(svg_points) <= len(svg_points_orig))-#diff --git a/wger/weight/views.py b/wger/weight/views.pyindex bf1d4f0d4..2e0346b60 100644--- a/wger/weight/views.py+++ b/wger/weight/views.py@@ -133,16 +133,20 @@ def overview(request):"""template_data = {}- min_date = WeightEntry.objects.filter(user=request.user).aggregate(Min('creation_date'))['creation_date__min']- max_date = WeightEntry.objects.filter(user=request.user).aggregate(Max('creation_date'))['creation_date__max']+ min_date = WeightEntry.objects.filter(user=request.user).\+ aggregate(Min('creation_date'))['creation_date__min']+ max_date = WeightEntry.objects.filter(user=request.user).\+ aggregate(Max('creation_date'))['creation_date__max']if min_date:- template_data['min_date'] = 'new Date(%(year)s, %(month)s, %(day)s)' % {'year': min_date.year,- 'month': min_date.month,- 'day': min_date.day}+ template_data['min_date'] = 'new Date(%(year)s, %(month)s, %(day)s)' % \+ {'year': min_date.year,+ 'month': min_date.month,+ 'day': min_date.day}if max_date:- template_data['max_date'] = 'new Date(%(year)s, %(month)s, %(day)s)' % {'year': max_date.year,- 'month': max_date.month,- 'day': max_date.day}+ template_data['max_date'] = 'new Date(%(year)s, %(month)s, %(day)s)' % \+ {'year': max_date.year,+ 'month': max_date.month,+ 'day': max_date.day}return render_to_response('weight_overview.html',template_data,context_instance=RequestContext(request))@@ -177,14 +181,13 @@ def get_weight_data(request):return HttpResponse(json.dumps(chart_data), mimetype)-CSV_DATE_FORMAT = (- ('%d.%m.%Y', 'DD.MM.YYYY (30.01.2012)'),- ('%d.%m.%y', 'DD.MM.YY (30.01.12)'),- ('%Y-%m-%d', 'YYYY-MM-DD (2012-01-30)'),- ('%y-%m-%d', 'YY-MM-DD (12-01-30)'),- ('%m/%d/%Y', 'MM/DD/YYYY (01/30/2012)'),- ('%m/%d/%y', 'MM/DD/YY (01/30/12)'),- )+CSV_DATE_FORMAT = (('%d.%m.%Y', 'DD.MM.YYYY (30.01.2012)'),+ ('%d.%m.%y', 'DD.MM.YY (30.01.12)'),+ ('%Y-%m-%d', 'YYYY-MM-DD (2012-01-30)'),+ ('%y-%m-%d', 'YY-MM-DD (12-01-30)'),+ ('%m/%d/%Y', 'MM/DD/YYYY (01/30/2012)'),+ ('%m/%d/%y', 'MM/DD/YY (01/30/12)'),)+class WeightCsvImportForm(Form):'''@@ -209,11 +212,11 @@ class WeightCsvImportFormPreview(FormPreview):'form_action': reverse('weight-import-csv')}def process_preview(self, request, form, context):- context['weight_list'], context['error_list'] = helpers.parse_weight_csv(request, form.cleaned_data)+ context['weight_list'], context['error_list'] = helpers.parse_weight_csv(request,+ form.cleaned_data)return contextdef done(self, request, cleaned_data):weight_list, error_list = helpers.parse_weight_csv(request, cleaned_data)WeightEntry.objects.bulk_create(weight_list)return HttpResponseRedirect(reverse('weight-overview'))-diff --git a/wger/workout_manager/__init__.py b/wger/workout_manager/__init__.pyindex 7e6fb87a1..3100a8162 100644--- a/wger/workout_manager/__init__.py+++ b/wger/workout_manager/__init__.py@@ -7,9 +7,10 @@VERSION = (1, 1, 0, 'alpha', 0)+def get_version(version=None):"""Derives a PEP386-compliant version number from VERSION."""-+if version is None:version = VERSIONassert len(version) == 5@@ -40,7 +41,6 @@ def get_version(version=None):def hg_version():import socketimport os- import sysfrom os.path import realpath, join, dirnametry:from mercurial import ui as hguidiff --git a/wger/workout_manager/constants.py b/wger/workout_manager/constants.pyindex c571f8279..ed2a326d7 100644--- a/wger/workout_manager/constants.py+++ b/wger/workout_manager/constants.py@@ -24,8 +24,7 @@ SOFTWARE_TAB = 'software'USER_TAB = 'user'# Valid date formats-DATE_FORMATS = [- '%d.%m.%Y', # '25.10.2012'+DATE_FORMATS = ['%d.%m.%Y', # '25.10.2012''%d.%m.%y', # '25.10.12''%m/%d/%Y', # '10/25/2012'diff --git a/wger/workout_manager/generic_views.py b/wger/workout_manager/generic_views.pyindex cf24c8839..614c10773 100644--- a/wger/workout_manager/generic_views.py+++ b/wger/workout_manager/generic_views.py@@ -72,7 +72,8 @@ class YamlFormMixin(ModelFormMixin):# opening it on a modal dialog, we need to make sure the POST request# reaches the correct controllerif self.form_action_urlname:- context['form_action'] = reverse(self.form_action_urlname, kwargs={'pk': self.object.id})+ context['form_action'] = reverse(self.form_action_urlname,+ kwargs={'pk': self.object.id})elif self.form_action:context['form_action'] = self.form_action@@ -85,13 +86,13 @@ class YamlFormMixin(ModelFormMixin):return contextdef dispatch(self, request, *args, **kwargs):- """+ '''Custom dispatch method.This basically only checks for ownerships of editable/deletableobjects and return a HttpResponseForbidden response if the useris not the owner.- """+ '''# These seem to be necessary for calling get_objectself.kwargs = kwargs@@ -99,7 +100,8 @@ class YamlFormMixin(ModelFormMixin):# For new objects, we have to manually load the owner objectif self.owner_object:- owner_object = self.owner_object['class'].objects.get(pk = kwargs[self.owner_object['pk']])+ owner_object = self.owner_object['class'].objects.get(+ pk=kwargs[self.owner_object['pk']])else:# On CreateViews we don't have an object, so just ignore ittry:@@ -115,7 +117,6 @@ class YamlFormMixin(ModelFormMixin):return super(YamlFormMixin, self).dispatch(request, *args, **kwargs)-class YamlDeleteMixin(ModelFormMixin):template_name = 'delete.html'@@ -126,7 +127,6 @@ class YamlDeleteMixin(ModelFormMixin):delete_message = ''template_name = 'delete.html'-def get_context_data(self, **kwargs):'''Set necessary template data to correctly render the form@@ -145,11 +145,11 @@ class YamlDeleteMixin(ModelFormMixin):# opening it on a modal dialog, we need to make sure the POST request# reaches the correct controllerif self.form_action_urlname:- context['form_action'] = reverse(self.form_action_urlname, kwargs={'pk': self.object.id})+ context['form_action'] = reverse(self.form_action_urlname,+ kwargs={'pk': self.object.id})elif self.form_action:context['form_action'] = self.form_action-# Set the titlecontext['title'] = self.title@@ -158,15 +158,14 @@ class YamlDeleteMixin(ModelFormMixin):return context-def dispatch(self, request, *args, **kwargs):- """+ '''Custom dispatch method.This basically only checks for ownerships of editable/deletableobjects and return a HttpResponseForbidden response if the useris not the owner.- """+ '''# These seem to be necessary if for calling get_objectself.kwargs = kwargs@@ -179,4 +178,3 @@ class YamlDeleteMixin(ModelFormMixin):# Dispatch normallyreturn super(YamlDeleteMixin, self).dispatch(request, *args, **kwargs)-diff --git a/wger/workout_manager/helpers.py b/wger/workout_manager/helpers.pyindex cc1e147c3..51c0f5bd2 100644--- a/wger/workout_manager/helpers.py+++ b/wger/workout_manager/helpers.py@@ -19,17 +19,18 @@ import jsonfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger+def pagination(object_list,request_page,- paginator_class = Paginator,- objects_per_page = 25,- max_total_pages = 10,- pages_around_current = 5):- """+ paginator_class=Paginator,+ objects_per_page=25,+ max_total_pages=10,+ pages_around_current=5):+ '''Helper function to initialise the pagination.If the list is too long, only pages around the current one are shown.- """+ '''paginator = paginator_class(object_list, objects_per_page)@@ -42,14 +43,13 @@ def pagination(object_list,# If page is out of range (e.g. 9999), deliver last page of results.paginated_page = paginator.page(paginator.num_pages)-# For very long lists (e.g. the English ingredient with more than 8000 items)# we muck around here to remove the pages not inmediately 'around' the current# one, otherwise we end up with a which a useless block with 300 pages.if paginator.num_pages > max_total_pages:start_page = paginated_page.number - pages_around_current- for i in range(paginated_page.number - pages_around_current, paginated_page.number +1):+ for i in range(paginated_page.number - pages_around_current, paginated_page.number + 1):if i > 0:start_page = ibreakdiff --git a/wger/workout_manager/settings.sample.py b/wger/workout_manager/settings.sample.pyindex 31a9600ea..0e781faf8 100644--- a/wger/workout_manager/settings.sample.py+++ b/wger/workout_manager/settings.sample.py@@ -33,12 +33,12 @@ SECRET_KEY = ''# Database settingsDATABASES = {'default': {- 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.- 'NAME': '', # Or path to database file if using sqlite3.- 'USER': '', # Not used with sqlite3.- 'PASSWORD': '', # Not used with sqlite3.- 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.- 'PORT': '', # Set to empty string for default. Not used with sqlite3.+ 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2','mysql', 'sqlite3' or 'oracle'+ 'NAME': '', # Or path to database file if using sqlite3.+ 'USER': '', # Not used with sqlite3.+ 'PASSWORD': '', # Not used with sqlite3.+ 'HOST': '', # Set to empty string for localhost. Not used with sqlite3+ 'PORT': '', # Set to empty string for default. Not used with sqlite3.}}diff --git a/wger/workout_manager/settings_global.py b/wger/workout_manager/settings_global.pyindex 817a9979e..2b1ee03bb 100644--- a/wger/workout_manager/settings_global.py+++ b/wger/workout_manager/settings_global.py@@ -112,7 +112,7 @@ STATICFILES_DIRS = (STATICFILES_FINDERS = ('django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder',-# 'django.contrib.staticfiles.finders.DefaultStorageFinder',+ #'django.contrib.staticfiles.finders.DefaultStorageFinder',)# List of callables that know how to import templates from various sources.@@ -120,7 +120,7 @@ TEMPLATE_LOADERS = ('django_mobile.loader.Loader','django.template.loaders.filesystem.Loader','django.template.loaders.app_directories.Loader',-# 'django.template.loaders.eggs.Loader',+ #'django.template.loaders.eggs.Loader',)MIDDLEWARE_CLASSES = (@@ -215,25 +215,25 @@ LOGGING = {},'handlers': {'null': {- 'level':'DEBUG',- 'class':'django.utils.log.NullHandler',+ 'level': 'DEBUG',+ 'class': 'django.utils.log.NullHandler',},'mail_admins': {'level': 'ERROR','filters': ['require_debug_false'],'class': 'django.utils.log.AdminEmailHandler'},- 'console':{- 'level':'DEBUG',- 'class':'logging.StreamHandler',+ 'console': {+ 'level': 'DEBUG',+ 'class': 'logging.StreamHandler','formatter': 'simple'},},'loggers': {'django': {- 'handlers':['null'],+ 'handlers': ['null'],'propagate': True,- 'level':'INFO',+ 'level': 'INFO',},'django.request': {'handlers': ['mail_admins'],diff --git a/wger/workout_manager/widgets.py b/wger/workout_manager/widgets.pyindex cf87238d8..8f637a527 100644--- a/wger/workout_manager/widgets.py+++ b/wger/workout_manager/widgets.py@@ -1,58 +1,53 @@# -*- 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 Licenseimport uuidfrom itertools import chainfrom django.forms.widgets import SelectMultiple-from django.forms.widgets import Widget-from django.forms.util import flatattfrom django.utils.translation import ugettext as _from django.utils.encoding import force_unicodefrom django.utils.html import escapefrom django.utils.html import conditional_escapefrom django.utils.safestring import mark_safe-from django.utils.datastructures import MultiValueDict-from django.utils.datastructures import MergeDict-class ExerciseAjaxSelect(SelectMultiple):'''Custom widget that allows to select exercises from an autocompleter-- This is basically modified MultipleSelect widget++ This is basically modified MultipleSelect widget'''-+def render(self, name, value, attrs=None, choices=()):- if value is None: value = []+ if value is None:+ value = []final_attrs = self.build_attrs(attrs, name=name)-+output = [u'<div class="ym-fbox-text">']output.append(u'<input type="text" id="exercise-search">')output.append(u'</div>')-+output.append('<div id="exercise-search-log">')options = self.render_options(choices, value)if options:- output.append(options)+ output.append(options)output.append('</div>')-- return mark_safe(u'\n'.join(output))+ return mark_safe(u'\n'.join(output))def render_options(self, choices, selected_choices):# Normalize to strings.@@ -62,30 +57,28 @@ class ExerciseAjaxSelect(SelectMultiple):output.append(self.render_option(selected_choices, option_value, option_label))return u'\n'.join(output)-def render_option(self, selected_choices, option_value, option_label):option_value = force_unicode(option_value)if option_value in selected_choices:-+return u'''- <div id="a%(div_id)s" class="ajax-exercise-select">- <a href="#">- <img src="/static/images/icons/status-off.svg"- width="14"- height="14"- alt="Delete">- </a> %(value)s- <input type="hidden" name="exercises" value="%(id)s">+ <div id="a%(div_id)s" class="ajax-exercise-select">+ <a href="#">+ <img src="/static/images/icons/status-off.svg"+ width="14"+ height="14"+ alt="Delete">+ </a> %(value)s+ <input type="hidden" name="exercises" value="%(id)s"></div>- ''' % { 'value': conditional_escape(force_unicode(option_label)),- 'id': escape(option_value),- 'div_id': uuid.uuid4()- }-+ ''' % {'value': conditional_escape(force_unicode(option_label)),+ 'id': escape(option_value),+ 'div_id': uuid.uuid4()}+else:return ''--++class TranslatedSelectMultiple(SelectMultiple):'''A SelectMultiple widget that translates the options@@ -95,4 +88,3 @@ class TranslatedSelectMultiple(SelectMultiple):return super(TranslatedSelectMultiple, self).render_option(selected_choices,option_value,_(option_label))-