Self hosted FLOSS fitness/workout, nutrition and weight tracker
Format code according to PEP8, remove unused imports
Roland Geider24a388cdbbec
diff --git a/exercises/admin.py b/exercises/admin.pyindex 84e6ee5c9..6e582e2c6 100644--- a/exercises/admin.py+++ b/exercises/admin.py@@ -1,15 +1,15 @@# 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 Licensefrom exercises.models import Language@@ -19,13 +19,16 @@ from exercises.models import ExerciseCategoryfrom exercises.models import Musclefrom django.contrib import admin-class ExerciseCommentInline(admin.TabularInline): #admin.StackedInline+++class ExerciseCommentInline(admin.TabularInline): # admin.StackedInlinemodel = ExerciseCommentextra = 1+class ExerciseAdmin(admin.ModelAdmin):#fields = ['name',]-+inlines = [ExerciseCommentInline]admin.site.register(Exercise, ExerciseAdmin)diff --git a/exercises/models.py b/exercises/models.pyindex 977711aff..c405dbefc 100644--- a/exercises/models.py+++ b/exercises/models.py@@ -1,17 +1,17 @@# -*- 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# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.@@ -23,13 +23,15 @@ from django.core.urlresolvers import reverseclass Language(models.Model):"""Language of an item (exercise, workout, etc.)"""-+#e.g. 'de'- short_name = models.CharField(max_length = 2, verbose_name = _('Language short name'))-+ short_name = models.CharField(max_length=2,+ verbose_name=_('Language short name'))+#e.g. 'Deutsch'- full_name = models.CharField(max_length = 30, verbose_name = _('Language full name'))-+ full_name = models.CharField(max_length=30,+ verbose_name=_('Language full name'))+def __unicode__(self):"""Return a more human-readable representation"""@@ -39,17 +41,18 @@ class Language(models.Model):class Muscle(models.Model):"""Muscle an exercise works out"""-+# Name, in latin, e.g. "Pectoralis major"- name = models.CharField(max_length = 50, verbose_name = _('Name'))-+ name = models.CharField(max_length=50,+ verbose_name=_('Name'))+# Whether to use the front or the back image for backgroundis_front = models.BooleanField(default=1)-+# Metaclass to set some other propertiesclass Meta:ordering = ["name", ]-+def __unicode__(self):"""Return a more human-readable representation"""@@ -59,19 +62,21 @@ class Muscle(models.Model):class ExerciseCategory(models.Model):"""Model for an exercise category"""- name = models.CharField(max_length=100, verbose_name = _('Name'),)- language = models.ForeignKey(Language, verbose_name = _('Language'))-+ name = models.CharField(max_length=100,+ verbose_name=_('Name'),)+ language = models.ForeignKey(Language,+ verbose_name=_('Language'))+# Metaclass to set some other propertiesclass Meta:verbose_name_plural = _("Exercise Categories")ordering = ["name", ]-+def __unicode__(self):"""Return a more human-readable representation"""return self.name-+def get_owner_object(self):"""Category has no owner information@@ -79,36 +84,35 @@ class ExerciseCategory(models.Model):return False--class Exercise(models.Model):"""Model for an exercise"""- category = models.ForeignKey(ExerciseCategory, verbose_name = _('Category'))- description = models.TextField(max_length = 2000,- blank = True,- verbose_name = _('Description'))- name = models.CharField(max_length = 200, verbose_name = _('Name'))-- muscles = models.ManyToManyField(Muscle, verbose_name = _('Muscles'))-+ category = models.ForeignKey(ExerciseCategory,+ verbose_name=_('Category'))+ description = models.TextField(max_length=2000,+ blank=True,+ verbose_name=_('Description'))+ name = models.CharField(max_length=200,+ verbose_name=_('Name'))++ muscles = models.ManyToManyField(Muscle,+ verbose_name=_('Muscles'))+# Metaclass to set some other propertiesclass Meta:ordering = ["name", ]--+def get_absolute_url(self):"""Returns the canonical URL to view an exercise"""- return reverse('exercises.views.exercise_view', kwargs= {'id': self.id})-+ return reverse('exercises.views.exercise_view', kwargs={'id': self.id})+def __unicode__(self):"""Return a more human-readable representation"""return self.name-def get_owner_object(self):"""Exercise has no owner information@@ -119,16 +123,16 @@ class Exercise(models.Model):class ExerciseComment(models.Model):"""Model for an exercise comment"""- exercise = models.ForeignKey(Exercise, verbose_name = _('Exercise'))+ exercise = models.ForeignKey(Exercise, verbose_name=_('Exercise'))comment = models.CharField(max_length=200,- verbose_name = _('Comment'),+ verbose_name=_('Comment'),help_text=_('A comment about how to correctly do this exercise.'))-+def __unicode__(self):"""Return a more human-readable representation"""return self.comment-+def get_owner_object(self):"""Comment has no owner informationdiff --git a/exercises/urls.py b/exercises/urls.pyindex 137cd2cd1..5fce910d3 100644--- a/exercises/urls.py+++ b/exercises/urls.py@@ -1,4 +1,4 @@-from django.conf.urls import patterns, include, url+from django.conf.urls import patterns, urlfrom django.contrib.auth.decorators import permission_requiredfrom exercises.views import ExerciseUpdateView@@ -21,31 +21,31 @@ urlpatterns = patterns('exercises.views',url(r'^exercise/(?P<id>\d+)/view/$', 'exercise_view'),url(r'^exercise/add/$',permission_required('exercises.change_exercise')(ExerciseAddView.as_view()),- name = 'exercise-add'),+ name='exercise-add'),url(r'^exercise/(?P<pk>\d+)/edit/$',permission_required('exercises.change_exercise')(ExerciseUpdateView.as_view()),- name = 'exercise-edit'),+ name='exercise-edit'),url(r'^exercise/(?P<pk>\d+)/delete/$',permission_required('exercises.change_exercise')(ExerciseDeleteView.as_view()),name='exercise-delete'),-+# Commentsurl(r'^exercise/(?P<exercise_pk>\d+)/comment/add/$',permission_required('exercises.change_exercise')(ExerciseCommentAddView.as_view()),- name = 'exercisecomment-add'),+ name='exercisecomment-add'),url(r'^exercise/comment/(?P<pk>\d+)/edit/$',permission_required('exercises.change_exercise')(ExerciseCommentEditView.as_view()),- name = 'exercisecomment-edit'),+ name='exercisecomment-edit'),url(r'^exercise/comment/(?P<id>\d+)/delete/$', 'exercisecomment_delete'),-+# Categoriesurl(r'^exercise/category/(?P<pk>\d+)/edit/$',permission_required('exercises.change_exercise')(ExerciseCategoryUpdateView.as_view()),- name = 'exercisecategory-edit'),+ name='exercisecategory-edit'),url(r'^exercise/category/add/$',permission_required('exercises.change_exercise')(ExerciseCategoryAddView.as_view()),- name = 'exercisecategory-add'),+ name='exercisecategory-add'),url(r'^exercise/category/(?P<pk>\d+)/delete/$',permission_required('exercises.change_exercise')(ExerciseCategoryDeleteView.as_view()),- name = 'exercisecategory-delete'),+ name='exercisecategory-delete'),)diff --git a/exercises/views.py b/exercises/views.pyindex 96acb538a..12cf8721a 100644--- a/exercises/views.py+++ b/exercises/views.py@@ -1,17 +1,17 @@# -*- 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 loggingimport json@@ -22,17 +22,13 @@ from django.shortcuts import get_object_or_404from django.http import HttpResponsefrom django.http import HttpResponseRedirectfrom django.forms import ModelForm-from django.forms import Textareafrom django.forms import ModelChoiceFieldfrom django.core.context_processors import csrf-from django.core.exceptions import ObjectDoesNotExistfrom django.core.urlresolvers import reversefrom django.core.urlresolvers import reverse_lazyfrom django.contrib.auth.decorators import permission_requiredfrom django.utils.translation import ugettext as _from django.utils.translation import ugettext_lazy-from django.utils.decorators import method_decorator-from django.utils import translationfrom django.utils.datastructures import SortedDictfrom django.views.generic import DeleteView@@ -43,7 +39,6 @@ from manager.utils import load_languagefrom manager.models import WorkoutLog-from exercises.models import Languagefrom exercises.models import Exercisefrom exercises.models import ExerciseCommentfrom exercises.models import ExerciseCategory@@ -62,28 +57,28 @@ logger = logging.getLogger('workout_manager.custom')class ExerciseCommentForm(ModelForm):class Meta:model = ExerciseComment- exclude=('exercise',)+ exclude = ('exercise',)class ExerciseCommentEditView(YamlFormMixin, UpdateView):"""Generic view to update an existing exercise comment"""-+active_tab = EXERCISE_TABmodel = ExerciseCommentform_class = ExerciseCommentFormtitle = ugettext_lazy('Edit exercise comment')-+def get_success_url(self):- return reverse('exercises.views.exercise_view', kwargs ={'id': self.object.exercise.id})+ return reverse('exercises.views.exercise_view', kwargs={'id': self.object.exercise.id})# Send some additional data to the templatedef get_context_data(self, **kwargs):context = super(ExerciseCommentEditView, self).get_context_data(**kwargs)context['form_action'] = reverse('exercisecomment-edit',kwargs={'pk': self.object.id})-+return context@@ -91,29 +86,29 @@ class ExerciseCommentAddView(YamlFormMixin, CreateView):"""Generic view to add a new exercise comment"""-+active_tab = EXERCISE_TABmodel = ExerciseCommentform_class = ExerciseCommentFormtitle = ugettext_lazy('Add exercise comment')-+def form_valid(self, form):- form.instance.exercise = Exercise.objects.get(pk = self.kwargs['exercise_pk'])-+ form.instance.exercise = Exercise.objects.get(pk=self.kwargs['exercise_pk'])+return super(ExerciseCommentAddView, self).form_valid(form)-- def get_success_url(self):- return reverse('exercises.views.exercise_view', kwargs ={'id': self.object.exercise.id})+ def get_success_url(self):+ return reverse('exercises.views.exercise_view', kwargs={'id': self.object.exercise.id})- # Send some additional data to the templatedef get_context_data(self, **kwargs):+ '''+ Send some additional data to the template+ '''context = super(ExerciseCommentAddView, self).get_context_data(**kwargs)context['form_action'] = reverse('exercisecomment-add',kwargs={'exercise_pk': self.kwargs['exercise_pk']})-- return context+ return context@permission_required('manager.add_exercisecomment')@@ -122,8 +117,8 @@ def exercisecomment_delete(request, id):comment = get_object_or_404(ExerciseComment, pk=id)exercise_id = comment.exercise.idcomment.delete()-- return HttpResponseRedirect(reverse('exercises.views.exercise_view', kwargs= {'id': exercise_id}))++ return HttpResponseRedirect(reverse('exercises.views.exercise_view', kwargs={'id': exercise_id}))@@ -134,156 +129,159 @@ def exercise_overview(request):"""Overview with all exercises"""language = load_language()-+template_data = {}template_data.update(csrf(request))-- template_data['categories'] = ExerciseCategory.objects.filter(language = language.id)++ template_data['categories'] = ExerciseCategory.objects.filter(language=language.id)template_data['active_tab'] = EXERCISE_TAB-+return render_to_response('overview.html',template_data,context_instance=RequestContext(request))-+def exercise_view(request, id, comment_id=None):""" Detail view for an exercise"""-+template_data = {}template_data['comment_edit'] = False-+# Load the exercise itselfexercise = get_object_or_404(Exercise, pk=id)template_data['exercise'] = exercisetemplate_data['active_tab'] = EXERCISE_TAB-+# Create the backgrounds that show what muscles the exercise works onbackgrounds_back = []backgrounds_front = []-+for muscle in exercise.muscles.all():if muscle.is_front:backgrounds_front.append('images/muscles/main/muscle-%s.svg' % muscle.id)else:backgrounds_back.append('images/muscles/main/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:+ if backgrounds_front:backgrounds_front.append('images/muscles/muscular_system_front.svg')-+if backgrounds_back:backgrounds_back.append('images/muscles/muscular_system_back.svg')-+template_data['muscle_backgrounds_front'] = backgrounds_fronttemplate_data['muscle_backgrounds_back'] = backgrounds_back--+# Load log- logs = WorkoutLog.objects.filter(user = request.user,- exercise = exercise)+ logs = WorkoutLog.objects.filter(user=request.user,+ exercise=exercise)entry_log = SortedDict()-+for entry in logs:if not entry_log.get(entry.date):entry_log[entry.date] = []entry_log[entry.date].append(entry)-+template_data['logs'] = entry_log---+# Renderreturn render_to_response('view.html',template_data,context_instance=RequestContext(request))+class ExercisesEditAddView(YamlFormMixin):"""- Generic view to subclass from for exercise adding and editing, since they share all- this settings+ Generic view to subclass from for exercise adding and editing, since they+ share all this settings"""- active_tab = EXERCISE_TAB+ active_tab = EXERCISE_TABmodel = Exercise-+form_fields = ['name','category','muscles','description']-+select_lists = ['category']- title = ugettext_lazy('Add exercise')+ title = ugettext_lazy('Add exercise')custom_js = 'init_tinymce();'-+def get_form_class(self):-+# Define the exercise form here because only at this point during the request# have we access to the currently used language. In other places Django defaults# 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 = Exerciseclass Media:- js = ('js/tinymce/tiny_mce.js',)-+ js = ('js/tinymce/tiny_mce.js',)+return ExerciseForm+class ExerciseUpdateView(ExercisesEditAddView, UpdateView):"""Generic view to update an existing exercise"""-+def get_context_data(self, **kwargs):context = super(ExerciseUpdateView, self).get_context_data(**kwargs)context['form_action'] = reverse('exercise-edit', kwargs={'pk': self.object.id})context['title'] = _('Edit %s') % self.object.name-+return context+class ExerciseAddView(ExercisesEditAddView, CreateView):"""Generic view to add a new exercise"""-+form_action = reverse_lazy('exercise-add')-++class ExerciseDeleteView(YamlDeleteMixin, DeleteView):"""Generic view to delete an existing exercise"""-+model = Exerciseactive_tab = EXERCISE_TABsuccess_url = reverse_lazy('exercises.views.exercise_overview')delete_message = ugettext_lazy('This will delete the exercise from all workouts.')-+# Send some additional data to the templatedef get_context_data(self, **kwargs):context = super(ExerciseDeleteView, self).get_context_data(**kwargs)-+context['title'] = _('Delete exercise %s?') % self.object.namecontext['form_action'] = reverse('exercise-delete', kwargs={'pk': self.kwargs['pk']})-+return context-+def exercise_search(request):"""Search an exercise, return the result as a JSON list"""-+# Perform the searchq = request.GET.get('term', '')user_language = load_language()- exercises = Exercise.objects.filter(name__icontains = q, category__language_id = user_language )\+ exercises = Exercise.objects.filter(name__icontains=q, category__language_id=user_language)\.order_by('category__name', 'name')-- # AJAX-request, this comes from the autocompleter. Create a list and send it back as JSON++ # AJAX-request, this comes from the autocompleter. Create a list and send+ # it back as JSONif request.is_ajax():-+results = []for exercise in exercises:exercise_json = {}@@ -291,14 +289,14 @@ def exercise_search(request):exercise_json['name'] = exercise.nameexercise_json['value'] = exercise.nameexercise_json['category'] = exercise.category.name-+results.append(exercise_json)data = json.dumps(results)-+# Return the results to the servermimetype = 'application/json'return HttpResponse(data, mimetype)-+# Usual search (perhaps JS disabled), present the results as normal HTML pageelse:template_data = {}@@ -309,30 +307,31 @@ def exercise_search(request):template_data,context_instance=RequestContext(request))+# ************************# Exercise categories# ************************class ExerciseCategoryForm(ModelForm):class Meta:model = ExerciseCategory- exclude=('language',)+ exclude = ('language',)class ExerciseCategoryAddView(YamlFormMixin, CreateView):"""Generic view to add a new exercise category"""-+active_tab = EXERCISE_TABmodel = ExerciseCategoryform_class = ExerciseCategoryFormsuccess_url = reverse_lazy('exercises.views.exercise_overview')title = ugettext_lazy('Add category')form_action = reverse_lazy('exercisecategory-add')-+def form_valid(self, form):form.instance.language = load_language()-+return super(ExerciseCategoryAddView, self).form_valid(form)@@ -340,7 +339,7 @@ class ExerciseCategoryUpdateView(YamlFormMixin, UpdateView):"""Generic view to update an existing exercise category"""-+active_tab = EXERCISE_TABmodel = ExerciseCategoryform_class = ExerciseCategoryForm@@ -351,12 +350,12 @@ class ExerciseCategoryUpdateView(YamlFormMixin, UpdateView):context = super(ExerciseCategoryUpdateView, self).get_context_data(**kwargs)context['form_action'] = reverse('exercisecategory-edit', kwargs={'pk': self.object.id})context['title'] = _('Edit %s') % self.object.name-+return context-+def form_valid(self, form):form.instance.language = load_language()-+return super(ExerciseCategoryUpdateView, self).form_valid(form)@@ -364,16 +363,16 @@ class ExerciseCategoryDeleteView(YamlDeleteMixin, DeleteView):"""Generic view to delete an existing exercise category"""-+model = ExerciseCategorysuccess_url = reverse_lazy('exercises.views.exercise_overview')delete_message = ugettext_lazy('This will also delete all exercises in this category.')-+# Send some additional data to the templatedef get_context_data(self, **kwargs):context = super(ExerciseCategoryDeleteView, self).get_context_data(**kwargs)-+context['title'] = _('Delete category %s?') % self.object.namecontext['form_action'] = reverse('exercise-delete', kwargs={'pk': self.kwargs['pk']})-+return contextdiff --git a/manager/templatetags/manager_extras.py b/manager/templatetags/manager_extras.pyindex e14e19a13..315b64253 100644--- a/manager/templatetags/manager_extras.py+++ b/manager/templatetags/manager_extras.py@@ -5,7 +5,7 @@ register = template.Library()@register.filter(name='get_current_settings')def get_current_settings(exercise, set_id):"""Does a filter on the sets-+We 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"""@@ -26,22 +26,22 @@ def pagination(page, page_range):"""return {'page': page,'page_range': page_range }--++@register.inclusion_tag('tags/render_weight_log.html')def render_weight_log(log):"""Renders a weight log series"""-+return {'log': log}--++@register.inclusion_tag('tags/yaml_form_element.html')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}