Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Format code according to PEP8, remove unused imports

Roland Geiderfa23210045f0
diff --git a/manager/models.py b/manager/models.py
index 5bbeb0d64..0734bf736 100644
--- a/manager/models.py
+++ b/manager/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/>.
@@ -33,32 +33,30 @@ logger = logging.getLogger('workout_manager.custom')
class TrainingSchedule(models.Model):
"""Model for a training schedule
"""
-
+
# Metaclass to set some other properties
class Meta:
ordering = ["-creation_date", ]
-
-
+
creation_date = models.DateField(_('Creation date'), auto_now_add=True)
- comment = models.TextField(verbose_name = _('Description'),
+ comment = models.TextField(verbose_name=_('Description'),
max_length=100,
blank=True,
- help_text = _('''A short description or goal of the workout.
+ help_text=_('''A short description or goal of the workout.
For example 'Focus on back' or 'Week 1 of program xy'.'''))
- user = models.ForeignKey(User, verbose_name = _('User'))
+ user = models.ForeignKey(User, verbose_name=_('User'))
-
def get_absolute_url(self):
"""
Returns the canonical URL to view a workout
"""
- return reverse('manager.views.view_workout', kwargs= {'id': self.id})
-
+ return reverse('manager.views.view_workout', kwargs={'id': self.id})
+
def __unicode__(self):
"""Return a more human-readable representation
"""
return str(self.creation_date)
-
+
def get_owner_object(self):
"""
Returns the object that has owner information
@@ -68,14 +66,13 @@ For example 'Focus on back' or 'Week 1 of program xy'.'''))
class DaysOfWeek(models.Model):
"""Model for the days of the week
-
+
This 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'))
-
-
+ verbose_name=_('Day of the week'))
+
def __unicode__(self):
"""Return a more human-readable representation
"""
@@ -86,41 +83,42 @@ class Day(models.Model):
"""Model for a training day
"""
- training = models.ForeignKey(TrainingSchedule, verbose_name = _('Training'))
+ training = models.ForeignKey(TrainingSchedule, verbose_name=_('Training'))
description = models.CharField(max_length=100,
- verbose_name = _('Description'),
+ verbose_name=_('Description'),
help_text=_('Ususally a description about what parts are trained, like "Arms" or "Pull Day"'))
day = models.ManyToManyField(DaysOfWeek,
- verbose_name = _('Day'))
-
+ 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.training
+
class Set(models.Model):
"""Model for a set of exercises
"""
- exerciseday = models.ForeignKey(Day, verbose_name = _('Exercise day'))
- exercises = models.ManyToManyField(Exercise, verbose_name = _('Exercises'))
- order = models.IntegerField(max_length = 1,
- blank = True,
- null = True,
- verbose_name = _('Order'))
- sets = models.IntegerField(validators = [MaxValueValidator(6)], verbose_name = _('Sets'))
-
+ exerciseday = models.ForeignKey(Day, verbose_name=_('Exercise day'))
+ exercises = models.ManyToManyField(Exercise, verbose_name=_('Exercises'))
+ order = models.IntegerField(max_length=1,
+ blank=True,
+ null=True,
+ verbose_name=_('Order'))
+ sets = models.IntegerField(validators=[MaxValueValidator(6)], verbose_name=_('Sets'))
+
# Metaclass to set some other properties
class Meta:
ordering = ["order", ]
-
+
def __unicode__(self):
"""Return a more human-readable representation
"""
@@ -136,18 +134,17 @@ class Set(models.Model):
class Setting(models.Model):
"""Settings for an exercise (weight, reps, etc.)
"""
-
+
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'))
- comment = models.CharField(max_length=100, blank=True, verbose_name = _('Comment'))
-
+ exercise = models.ForeignKey(Exercise, verbose_name=_('Exercises'))
+ reps = models.IntegerField(validators=[MaxValueValidator(40)], verbose_name=_('Repetitions'))
+ order = models.IntegerField(blank=True, verbose_name=_('Repetitions'))
+ comment = models.CharField(max_length=100, blank=True, verbose_name=_('Comment'))
+
# Metaclass to set some other properties
class Meta:
ordering = ["order", "id"]
-
-
+
def __unicode__(self):
"""Return a more human-readable representation
"""
@@ -164,22 +161,21 @@ class WorkoutLog(models.Model):
"""
A log entry for an exercise
"""
-
- user = models.ForeignKey(User, verbose_name = _('User'))
- exercise = models.ForeignKey(Exercise, verbose_name = _('Exercise'))
- workout = models.ForeignKey(TrainingSchedule, verbose_name = _('Workout'))
-
- reps = models.IntegerField(verbose_name = _('Repetitions'))
- weight = models.DecimalField(decimal_places = 2,
- max_digits = 5,
- verbose_name = _('Weight'))
- date = models.DateField(verbose_name = _('Date'))
-
+
+ user = models.ForeignKey(User, verbose_name=_('User'))
+ exercise = models.ForeignKey(Exercise, verbose_name=_('Exercise'))
+ workout = models.ForeignKey(TrainingSchedule, verbose_name=_('Workout'))
+
+ reps = models.IntegerField(verbose_name=_('Repetitions'))
+ weight = models.DecimalField(decimal_places=2,
+ max_digits=5,
+ verbose_name=_('Weight'))
+ date = models.DateField(verbose_name=_('Date'))
+
# Metaclass to set some other properties
class Meta:
ordering = ["date", "reps"]
-
-
+
def __unicode__(self):
"""
Return a more human-readable representation
@@ -204,12 +200,12 @@ class UserProfile(models.Model):
#
# Show exercise comments on workout view
- show_comments = models.BooleanField(verbose_name = _('Show exercise comments'),
+ show_comments = models.BooleanField(verbose_name=_('Show exercise comments'),
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'),
+ show_english_ingredients = models.BooleanField(verbose_name=_('Also use ingredients in English'),
help_text=_('''Check to also show ingredients in English while creating
a nutritional plan. These ingredients are extracted from a list provided
by the US Department of Agriculture. It is extremely complete, with around
diff --git a/manager/pdf.py b/manager/pdf.py
index 91c4e9803..93d0a07da 100644
--- a/manager/pdf.py
+++ b/manager/pdf.py
@@ -1,21 +1,20 @@
# -*- 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
-import uuid
import datetime
from django.http import HttpResponse
@@ -24,7 +23,6 @@ from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
-from manager.models import DaysOfWeek
from manager.models import TrainingSchedule
from reportlab.lib.styles import getSampleStyleSheet
@@ -41,231 +39,231 @@ logger = logging.getLogger('workout_manager.custom')
PDF functions
"""
+
@login_required
def workout_log(request, id):
"""Generates a PDF with the contents of the given workout
-
+
See also
* http://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/
* http://www.reportlab.com/apis/reportlab/dev/platypus.html
"""
-
+
#Load the workout
workout = get_object_or_404(TrainingSchedule, pk=id, user=request.user)
-
+
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % _('Workout')
-
+
# Create the PDF object, using the response object as its "file."
doc = SimpleDocTemplate(response,
- pagesize = A4,
+ pagesize=A4,
#pagesize = landscape(A4),
- leftMargin = cm,
- rightMargin = cm,
- topMargin = 0.5 * cm,
- bottomMargin = 0.5 * cm,
- title = _('Workout'),
- author = 'wger Workout Manager',
- subject = _('Workout for %s') % request.user.username)
+ leftMargin=cm,
+ rightMargin=cm,
+ topMargin=0.5 * cm,
+ bottomMargin=0.5 * cm,
+ title=_('Workout'),
+ author='wger Workout Manager',
+ subject=_('Workout for %s') % request.user.username)
# container for the 'Flowable' objects
elements = []
-
+
# stylesheet
styleSheet = getSampleStyleSheet()
-
+
style = ParagraphStyle(
- name = 'Normal',
+ name='Normal',
#fontName='Helvetica-Bold',
- fontSize = 8,
+ fontSize=8,
)
-
-
+
# table data, here we will put the workout info
data = []
-
-
+
# Init several counters and markers, this will be used after the iteration to
# set different borders and colours
day_markers = []
exercise_markers = {}
group_exercise_marker = {}
group_day_marker = {}
-
+
# Set the number of weeks for this workout
# (sets number of columns for the weight/date log)
nr_of_weeks = 7
-
+
# Set the first column of the weight log, depends on design
first_weight_column = 3
-
+
# Background colour for days
# Reportlab doesn't use the HTML hexadecimal format, but has a range of
# 0 till 1, so we have to convert here.
header_colour = colors.Color(int('73', 16) / 255.0,
int('8a', 16) / 255.0,
int('5f', 16) / 255.0)
-
-
+
#
# Iterate through the Workout
#
-
+
# Days
for day in workout.day_set.select_related():
set_count = 1
day_markers.append(len(data))
group_day_marker[day.id] = {'start': len(data), 'end': len(data)}
-
+
if not exercise_markers.get(day.id):
exercise_markers[day.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),
+ {'days': ', '.join(days_of_week),
'description': day.description},
styleSheet["Normal"])
-
+
data.append([P])
-
+
# Note: the _('Date') will be on the 3rd cell, but since we make a span
# over 3 cells, the value has to be on the 1st one
data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)
data.append([_('Nr.'), _('Exercise'), _('Reps')] + [_('Weight')] * nr_of_weeks)
-
+
# Sets
for set_obj in day.set_set.select_related():
group_exercise_marker[set_obj.id] = {'start': len(data), 'end': len(data)}
-
+
# Exercises
for exercise in set_obj.exercises.select_related():
-
+
group_exercise_marker[set_obj.id]['end'] = len(data)
-
+
# Note: '+1' here because there's an emtpy cell between days
exercise_markers[day.id].append(len(data) + 1)
setting_data = []
-
-
+
# Settings
- for setting in exercise.setting_set.filter(set_id = set_obj.id):
+ for setting in exercise.setting_set.filter(set_id=set_obj.id):
if setting.reps == 99:
repetitions = '∞'
else:
repetitions = str(setting.reps)
setting_data.append(repetitions)
-
# If there are more than 1 settings, don't output the repetitions
# e.g. "4 x 8 8 10 10" is shown only as "8 8 10 10", after all
# those 4 sets are not done four times!
if len(setting_data) == 0:
- out = '' # nothing set
-
+ out = '' # nothing set
+
elif len(setting_data) == 1:
out = str(set_obj.sets) + ' × ' + setting_data[0]
-
+
elif len(setting_data) > 1:
out = ', '.join(setting_data)
-
+
data.append([set_count, Paragraph(exercise.name, style), out] + [''] * nr_of_weeks)
set_count += 1
-
+
# Note: as above with _('Date'), the _('Impression') has to be here on
# the 1st cell so it is shown after adding a span
#data.append([_('Impression'), '', ''])
-
+
set_count += 1
data.append([''])
- group_day_marker[day.id]['end'] = len(data)
-
+ group_day_marker[day.id]['end'] = len(data)
+
# Set the widths and heights of rows and columns
# Note: 'None' is treated as 'automatic'. Either there is only one value for the whole list
# or exactly one for every row/column
colwidths = None
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'),
-
+ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
+
# Note: a padding of 3 seems to be the default
- ('LEFTPADDING', (0, 0), (-1, -1), 2),
+ ('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 cells
- previous_marker = 0
for marker in day_markers:
# Set background colour for headings
table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))
table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))
table_style.append(('BOX', (0, marker), (-1, marker + 2), 1.25, colors.black))
-
+
# Make the headings span the whole width
table_style.append(('SPAN', (0, marker), (-1, marker)))
-
+
# Make the space between days span the whole width
- table_style.append(('SPAN', (0, marker -1), (-1, marker -1)))
-
- # Manually set
+ table_style.append(('SPAN', (0, marker - 1), (-1, marker - 1)))
+
+ # Manually set
rowheights[marker - 1] = 5
-
+
# Make the date span 3 cells and align it to the right
- table_style.append(('ALIGN', (0, marker + 1), (2, marker +1), 'RIGHT'))
- table_style.append(('SPAN', (0, marker +1), (2, marker + 1)))
-
+ table_style.append(('ALIGN', (0, marker + 1), (2, marker + 1), 'RIGHT'))
+ table_style.append(('SPAN', (0, marker + 1), (2, marker + 1)))
# Combine the cells for exercises on the same set
for marker in group_exercise_marker:
start_marker = group_exercise_marker[marker]['start']
end_marker = group_exercise_marker[marker]['end']
-
- table_style.append(('VALIGN',(0, start_marker),(0, end_marker),'MIDDLE'))
+
+ table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
table_style.append(('SPAN', (0, start_marker), (0, end_marker)))
-
+
# Set an alternating background colour for rows
for i in exercise_markers:
counter = 1
for j in exercise_markers[i]:
if not j % 2:
- table_style.append(('BACKGROUND', (1, j -1), (-1, j -1), colors.lavender))
+ 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 right
for marker in group_day_marker:
start_marker = group_day_marker[marker]['start']
end_marker = group_day_marker[marker]['end']
-
+
#table_style.append(('ALIGN', (0, end_marker - 2), (2, end_marker - 2), 'RIGHT'))
-
-
+
# There is an empty cell between the day blocks, set a border around them
- table_style.append(('INNERGRID', (0, start_marker), (-1,end_marker -2 ), 0.25, colors.black))
- table_style.append(('BOX', (0, start_marker), (-1, end_marker -2), 1.25, colors.black))
-
-
+ table_style.append(('INNERGRID',
+ (0, start_marker),
+ (- 1, end_marker - 2),
+ 0.25,
+ colors.black))
+ table_style.append(('BOX',
+ (0, start_marker),
+ (-1, end_marker - 2),
+ 1.25,
+ colors.black))
+
# Set the table data
if data:
- t = Table(data, colwidths, rowheights, style = table_style)
-
+ t = Table(data, colwidths, rowheights, style=table_style)
+
# Manually set the width of the columns
for i in range(first_weight_column, nr_of_weeks + first_weight_column):
- t._argW[i] = 1.8 * cm # Columns for entering the log
-
- t._argW[0] = 0.6 * cm # Exercise numbering
- t._argW[1] = 3.5 * cm # Name of exercise
- t._argW[2] = 1.9 * cm # Repetitions
-
+ t._argW[i] = 1.8 * cm # Columns for entering the log
+
+ t._argW[0] = 0.6 * cm # Exercise numbering
+ t._argW[1] = 3.5 * cm # Name of exercise
+ t._argW[2] = 1.9 * cm # Repetitions
+
# There is nothing to output
else:
t = Paragraph(_('<i>This is an empty workout, what did you expect on the PDF?</i>'),
@@ -273,26 +271,26 @@ def workout_log(request, id):
#
# Add all elements to the document
- #
-
+ #
+
# Set the title (if available)
if workout.comment:
P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
- {'description' : workout.comment},
+ {'description': workout.comment},
styleSheet["Normal"])
elements.append(P)
-
+
# Filler
P = Paragraph('<para> </para>', styleSheet["Normal"])
elements.append(P)
# Append the table
elements.append(t)
-
+
# Footer, add filler paragraph
P = Paragraph('<para> </para>', styleSheet["Normal"])
elements.append(P)
-
+
# Print date and info
P = Paragraph('''<para align="left">
%(date)s -
@@ -308,9 +306,9 @@ def workout_log(request, id):
},
styleSheet["Normal"])
elements.append(P)
-
+
# write the document and send the response to the browser
doc.build(elements)
- return response
\ No newline at end of file
+ return response
diff --git a/manager/tests.py b/manager/tests.py
index 1e73f3015..db754fad8 100644
--- a/manager/tests.py
+++ b/manager/tests.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 License
diff --git a/manager/urls.py b/manager/urls.py
index 4832865e6..b08992459 100644
--- a/manager/urls.py
+++ b/manager/urls.py
@@ -1,4 +1,4 @@
-from django.conf.urls import patterns, include, url
+from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
@@ -12,57 +12,56 @@ from manager.views import DayCreateView
from workout_manager.constants import USER_TAB
-
urlpatterns = patterns('manager.views',
# The index page
url(r'^$', 'index', name='index'),
-
+
# User
url(r'^logout$', 'logout', name='logout'),
url(r'^user/registration$', 'registration'),
url(r'^user/preferences$', 'preferences'),
-
+
# Workout
url(r'^workout/overview$', 'overview'),
url(r'^workout/add$', 'add'),
url(r'^workout/(?P<pk>\d+)/copy/$',
'copy_workout',
- name = 'workout-copy'),
-
+ name='workout-copy'),
+
url(r'^workout/(?P<pk>\d+)/edit/$',
login_required(WorkoutEditView.as_view()),
- name = 'workout-edit'),
+ name='workout-edit'),
url(r'^workout/(?P<pk>\d+)/delete/$',
login_required(WorkoutDeleteView.as_view()),
- name = 'workout-delete'),
+ name='workout-delete'),
url(r'^workout/(?P<id>\d+)/view/$',
'view_workout',
- name = 'workout-view'),
+ name='workout-view'),
url(r'^workout/(?P<pk>\d+)/log/$',
login_required(WorkoutLogDetailView.as_view()),
- name = 'workout-log'),
-
-
+ name='workout-log'),
+
+
# Days
url(r'^workout/day/(?P<pk>\d+)/edit/$',
login_required(DayEditView.as_view()),
- name = 'day-edit'),
+ name='day-edit'),
url(r'^workout/(?P<workout_pk>\d+)/day/add/$',
login_required(DayCreateView.as_view()),
- name = 'day-add'),
+ name='day-add'),
url(r'^workout/(?P<id>\d+)/delete/day/(?P<day_id>\d+)$', 'delete_day'),
url(r'^workout/day/view/(?P<id>\d+)$', 'view_day'),
url(r'^workout/day/(?P<pk>\d+)/log/add/$',
'workout_log_add',
- name = 'day-log'),
-
+ name='day-log'),
+
# Sets and Settings
url(r'^workout/(?P<id>\d+)/day/(?P<day_id>\d+)/edit/set/(?P<set_id>\w*)$', 'edit_set'),
url(r'^workout/(?P<id>\d+)/day/(?P<day_id>\d+)/delete/set/(?P<set_id>\d+)$', 'delete_set'),
url(r'^workout/(?P<id>\d+)/set/(?P<set_id>\d+)/exercise/(?P<exercise_id>\d+)/edit/setting/(?P<setting_id>\d*)$', 'edit_setting'),
url(r'^workout/(?P<id>\d+)/set/(?P<set_id>\d+)/exercise/(?P<exercise_id>\d+)/delete/setting$', 'delete_setting'),
-
+
# AJAX
url(r'^workout/api/edit-set$', 'api_edit_set'),
url(r'^workout/api/edit-settting$', 'api_edit_setting'),
@@ -84,11 +83,11 @@ urlpatterns = urlpatterns + patterns('',
url(r'^user/password/change$',
'django.contrib.auth.views.password_change',
- {'template_name' : 'user/change_password.html',
- 'post_change_redirect' : reverse_lazy('index'),
- 'extra_context' : {'active_tab': USER_TAB}},
+ {'template_name': 'user/change_password.html',
+ 'post_change_redirect': reverse_lazy('index'),
+ 'extra_context': {'active_tab': USER_TAB}},
name='change-password'),
-
+
url(r'^user/password/reset/$',
'django.contrib.auth.views.password_reset',
{'template_name': 'user/password_reset_form.html'},
diff --git a/manager/utils.py b/manager/utils.py
index 746bb8199..963c795a7 100644
--- a/manager/utils.py
+++ b/manager/utils.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 License
from django.utils import translation
@@ -21,45 +21,47 @@ from exercises.models import Language
# Language functions
# ************************
+
def load_language():
"""Returns the currently used language, e.g. to load appropriate exercises
"""
# TODO: perhaps store a language preference in the user's profile?
-
+
# Read the first part of a composite language, e.g. 'de-at'
used_language = translation.get_language().split('-')[0]
-
+
try:
- language = Language.objects.get(short_name=used_language)
-
+ language = Language.objects.get(short_name=used_language)
+
# No luck, load english as our fall-back language
except ObjectDoesNotExist:
- language = Language.objects.get(short_name="en")
-
+ language = Language.objects.get(short_name="en")
+
return language
+
def load_ingredient_languages(request):
""" Filter the ingredients the user will see by its language.
-
+
Additionally, if the user has selected on his preference page that he wishes
to also see the ingredients in English (from the US Department of Agriculture),
show those too.
-
+
This only makes sense if the user's language isn't English, as he will be
presented those in that case anyway, so also do a check for this.
"""
-
+
language = load_language()
languages = (language.id,)
-
+
# Only registered users have a profile
if request.user.is_authenticated():
profile = request.user.get_profile()
show_english = profile.show_english_ingredients
-
+
# If the user's language is not english and has the preference, add english to the list
if show_english and language.short_name != 'en':
languages = (language.id, 2)
-
+
return languages
diff --git a/manager/views.py b/manager/views.py
index cb6a8605c..c0ac8349a 100644
--- a/manager/views.py
+++ b/manager/views.py
@@ -1,24 +1,24 @@
# -*- 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
import uuid
import datetime
-
+
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
@@ -39,7 +39,6 @@ from django.forms import ModelForm
from django.forms import EmailField
from django.forms import DateField
from django.forms import CharField
-from django.forms import SelectMultiple
from django.forms import DecimalField
from django.forms import ValidationError
from django.forms.models import modelformset_factory
@@ -50,11 +49,8 @@ from django.contrib.auth import login as django_login
from django.contrib.auth import logout as django_logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User as Django_User
-from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.forms import UserCreationForm
-from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.views import login as django_loginview
-from django.contrib.auth.views import password_change as django_pwchange
from django.views.generic import DeleteView
from django.views.generic import CreateView
@@ -75,7 +71,6 @@ from nutrition.models import NutritionPlan
from weight.models import WeightEntry
-from workout_manager import get_version
from workout_manager.constants import WORKOUT_TAB
from workout_manager.constants import USER_TAB
from workout_manager.constants import DATE_FORMATS
@@ -91,15 +86,16 @@ logger = logging.getLogger('workout_manager.custom')
# Misc functions
# ************************
+
@login_required
def index(request):
"""Show the index page, in our case, the last workout and nutritional plan
and the current weight
"""
-
+
template_data = {}
template_data['active_tab'] = USER_TAB
-
+
# Load the last workout, if one exists
try:
current_workout = TrainingSchedule.objects.filter(user=request.user).latest('creation_date')
@@ -107,24 +103,22 @@ def index(request):
except ObjectDoesNotExist:
current_workout = False
template_data['current_workout'] = current_workout
-
+
# Load the last nutritional plan, if one exists
try:
- plan = NutritionPlan.objects.filter(user = request.user).latest('creation_date')
+ plan = NutritionPlan.objects.filter(user=request.user).latest('creation_date')
except ObjectDoesNotExist:
plan = False
template_data['plan'] = plan
-
+
# Load the last logged weight entry, if one exists
try:
- weight = WeightEntry.objects.filter(user = request.user).latest('creation_date')
+ weight = WeightEntry.objects.filter(user=request.user).latest('creation_date')
except ObjectDoesNotExist:
weight = False
template_data['weight'] = weight
-
-
+
if current_workout:
-
# Format a bit the days so it doesn't have to be done in the template
week_day_result = []
for week in DaysOfWeek.objects.all():
@@ -135,40 +129,40 @@ def index(request):
day_has_workout = True
week_day_result.append((_(week.day_of_week), day.description, True))
break
-
-
+
if not day_has_workout:
week_day_result.append((_(week.day_of_week), _('Rest day'), False))
-
+
template_data['weekdays'] = week_day_result
-
-
+
if plan:
-
+
# Load the nutritional info
template_data['nutritional_info'] = plan.get_nutritional_values()
-
-
+
return render_to_response('index.html',
template_data,
context_instance=RequestContext(request))
+
+
# ************************
# User functions
# ************************
-
class UserPreferencesForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user',)
+
def login(request):
"""
Small wrapper around the django login view
"""
-
+
return django_loginview(request,
- template_name = 'user/login.html',
- extra_context = {'active_tab': USER_TAB})
+ template_name='user/login.html',
+ extra_context={'active_tab': USER_TAB})
+
def logout(request):
"""Logout the user
@@ -176,12 +170,13 @@ def logout(request):
django_logout(request)
return HttpResponseRedirect(reverse('login'))
+
class UserEmailForm(ModelForm):
email = EmailField(label=_("Email"),
- help_text = _("Completely optional, but needed to reset your password "
+ help_text=_("Completely optional, but needed to reset your password "
"in case you forget it."),
- required = False)
-
+ required=False)
+
def clean_email(self):
# Email must be unique systemwide
email = self.cleaned_data["email"]
@@ -193,19 +188,21 @@ class UserEmailForm(ModelForm):
return email
raise ValidationError(_("This email is already used."))
+
class RegistrationForm(UserCreationForm, UserEmailForm):
pass
+
def registration(request):
"""A form to allow for registration of new users
"""
template_data = {}
template_data.update(csrf(request))
template_data['active_tab'] = USER_TAB
-
+
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
-
+
# If the data is valid, log in and redirect
if form.is_valid():
username = form.cleaned_data['username']
@@ -222,33 +219,31 @@ def registration(request):
form = RegistrationForm()
template_data['form'] = form
-
+
return render_to_response('user/registration.html',
template_data,
context_instance=RequestContext(request))
-
def preferences(request):
"""An overview of all user preferences
"""
template_data = {}
template_data.update(csrf(request))
template_data['active_tab'] = USER_TAB
-
+
# Process the preferences form
if request.method == 'POST':
-
+
form = UserPreferencesForm(data=request.POST, instance=request.user.get_profile())
form.user = request.user
-
+
# Save the data if it validates
if form.is_valid():
form.save()
else:
form = UserPreferencesForm(instance=request.user.get_profile())
-
-
+
# Process the email form
#
# this is a bit ugly, but we need to take special care here, only instatiating
@@ -263,39 +258,40 @@ def preferences(request):
request.user.save()
else:
email_form = UserEmailForm(instance=request.user)
-
+
template_data['form'] = form
template_data['email_form'] = email_form
-
+
return render_to_response('user/preferences.html',
template_data,
context_instance=RequestContext(request))
+
@login_required
def api_user_preferences(request):
""" Allows the user to edit its preferences via AJAX calls
"""
-
+
if request.is_ajax():
-
+
# Show comments on workout view
if request.GET.get('do') == 'set_show-comments':
new_value = int(request.GET.get('show'))
-
+
profile = request.user.get_profile()
profile.show_comments = new_value
profile.save()
-
+
return HttpResponse(_('Success'))
-
+
# Show ingredients in english
elif request.GET.get('do') == 'set_english-ingredients':
new_value = int(request.GET.get('show'))
-
+
profile = request.user.get_profile()
profile.show_english_ingredients = new_value
profile.save()
-
+
return HttpResponse(_('Success'))
@@ -312,13 +308,13 @@ class WorkoutForm(ModelForm):
def overview(request):
"""An overview of all the user's workouts
"""
-
+
template_data = {}
template_data['active_tab'] = WORKOUT_TAB
-
+
latest_trainings = TrainingSchedule.objects.filter(user=request.user)
template_data['workouts'] = latest_trainings
-
+
return render_to_response('workout/overview.html',
template_data,
context_instance=RequestContext(request))
@@ -329,22 +325,20 @@ def view_workout(request, id):
"""
template_data = {}
template_data['active_tab'] = WORKOUT_TAB
-
+
workout = get_object_or_404(TrainingSchedule, pk=id, user=request.user)
template_data['workout'] = workout
-
-
+
# TODO: this can't be performant, see if it makes problems
# Create the backgrounds that show what muscles the workout will work on
backgrounds_front = []
backgrounds_back = []
- is_front = True
for day in workout.day_set.select_related():
for set in day.set_set.select_related():
for exercise in set.exercises.select_related():
for muscle in exercise.muscles.all():
muscle_bg = 'images/muscles/main/muscle-%s.svg' % muscle.id
-
+
# Add the muscles to the background list, but only once.
#
# While the combining effect (the more often a muscle gets
@@ -354,97 +348,95 @@ def view_workout(request, id):
backgrounds_front.append(muscle_bg)
elif not muscle.is_front and muscle_bg not in backgrounds_back:
backgrounds_back.append(muscle_bg)
-
+
# Append the correct "main" background, with the silhouette of the human body
backgrounds_front.append('images/muscles/muscular_system_front.svg')
backgrounds_back.append('images/muscles/muscular_system_back.svg')
-
+
template_data['muscle_backgrounds_front'] = backgrounds_front
template_data['muscle_backgrounds_back'] = backgrounds_back
-
-
- return render_to_response('workout/view.html',
+
+ return render_to_response('workout/view.html',
template_data,
context_instance=RequestContext(request))
class WorkoutCopyForm(Form):
- comment = CharField(max_length = 100,
- help_text = _('The goal or description of the new workout.'),
- required = False)
+ comment = CharField(max_length=100,
+ help_text=('The goal or description of the new workout.'),
+ required=False)
+
@login_required
def copy_workout(request, pk):
"""
Makes a copy of a workout
"""
-
+
workout = get_object_or_404(TrainingSchedule, pk=pk, user=request.user)
-
+
# Process request
if request.method == 'POST':
workout_form = WorkoutCopyForm(request.POST)
-
+
if workout_form.is_valid():
-
+
# Copy workout
days = workout.day_set.all()
-
+
workout_copy = workout
workout_copy.pk = None
workout_copy.comment = workout_form.cleaned_data['comment']
workout_copy.save()
-
+
# Copy the days
for day in days:
sets = day.set_set.all()
-
+
day_copy = day
day_copy.pk = None
day_copy.training = workout_copy
day_copy.save()
-
+
# Copy the sets
for current_set in sets:
current_set_id = current_set.id
exercises = current_set.exercises.all()
-
+
current_set_copy = current_set
current_set_copy.pk = None
current_set_copy.exerciseday = day_copy
current_set_copy.save()
-
+
# Exercises has Many2Many relationship
current_set_copy.exercises = exercises
-
+
# Go through the exercises
for exercise in exercises:
settings = exercise.setting_set.filter(set_id=current_set_id)
-
+
# Copy the settings
for setting in settings:
setting_copy = setting
setting_copy.pk = None
setting_copy.set = current_set_copy
setting_copy.save()
-
- return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs= {'id': workout.id}))
+
+ return HttpResponseRedirect(reverse('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['form_action'] = reverse('workout-copy', kwargs= {'pk': workout.id})
+ template_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))
-
-
@login_required
def add(request):
@@ -453,135 +445,130 @@ def add(request):
workout = TrainingSchedule()
workout.user = request.user
workout.save()
-
- return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs= {'id': workout.id}))
+
+ return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs={'id': workout.id}))
class WorkoutDeleteView(YamlDeleteMixin, DeleteView):
"""
Generic view to delete a workout routine
"""
-
+
active_tab = WORKOUT_TAB
model = TrainingSchedule
success_url = reverse_lazy('manager.views.overview')
title = ugettext_lazy('Delete workout')
form_action_urlname = 'workout-delete'
-
-
+
+
class WorkoutEditView(YamlFormMixin, UpdateView):
"""
Generic view to update an existing workout routine
"""
-
+
active_tab = WORKOUT_TAB
model = TrainingSchedule
form_class = WorkoutForm
title = ugettext_lazy('Edit workout')
form_action_urlname = 'workout-edit'
-
-
+
+
# ************************
# Day functions
# ************************
class DayForm(ModelForm):
class Meta:
model = Day
- exclude=('training',)
-
+ exclude = ('training',)
+
widgets = {
'day': TranslatedSelectMultiple()
}
-
+
class DayView(YamlFormMixin):
"""
Base generic view for exercise day
"""
-
+
active_tab = WORKOUT_TAB
model = Day
form_class = DayForm
-
+
def get_success_url(self):
- return reverse('manager.views.view_workout', kwargs ={'id': self.object.training.id})
+ return reverse('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"""
-
+
# Get the form
- form = super(DayView, self).get_form(form_class)
-
+ form = super(DayView, self).get_form(form_class)
+
# Calculate the used days ('used' by other days in the same workout)
if self.object:
workout = self.object.training
else:
- workout = TrainingSchedule.objects.get(pk = self.kwargs['workout_pk'])
-
+ workout = TrainingSchedule.objects.get(pk=self.kwargs['workout_pk'])
+
used_days = []
for day in workout.day_set.all():
for weekday in day.day.all():
if not self.object or day.id != self.object.id:
- used_days.append(weekday.id)
+ used_days.append(weekday.id)
used_days.sort()
-
+
# Set the queryset for day
form.fields['day'].queryset = DaysOfWeek.objects.exclude(id__in=used_days)
-
- return form
-
+ return form
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'])
+ form.instance.training = TrainingSchedule.objects.get(pk=self.kwargs['workout_pk'])
return super(DayCreateView, self).form_valid(form)
-
+
# Send some additional data to the template
def get_context_data(self, **kwargs):
context = super(DayCreateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('day-add',
- kwargs={'workout_pk': self.kwargs['workout_pk']})
+ kwargs={'workout_pk': self.kwargs['workout_pk']})
return context
-
@login_required
def delete_day(request, id, day_id):
"""Deletes the day with ID day_id belonging to workout with ID id
"""
-
+
# Load the day
day = get_object_or_404(Day, pk=day_id)
-
+
# Check if the user is the owner of the object
if day.training.user == request.user:
day.delete()
- return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs= {'id': id}))
+ return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs={'id': id}))
else:
return HttpResponseForbidden()
@@ -589,26 +576,26 @@ def delete_day(request, id, day_id):
@login_required
def view_day(request, id):
"""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
day = get_object_or_404(Day, pk=id)
if day.training.user != request.user:
return HttpResponseForbidden()
-
+
template_data['day'] = day
-
+
return render_to_response('day/view.html',
template_data,
context_instance=RequestContext(request))
+
# ************************
# Set functions
# ************************
-
class SetForm(ModelForm):
class Meta:
model = Set
@@ -616,192 +603,188 @@ class SetForm(ModelForm):
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
- # https://code.djangoproject.com/ticket/9321
+ # https://code.djangoproject.com/ticket/9321
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.')
+ self.fields['exercises'].help_text=_('You can search for more than one exercise, '
+ 'they will be grouped together for a superset.')
@login_required
def edit_set(request, id, day_id, set_id=None):
""" Edits/creates a set
"""
-
+
template_data = {}
template_data.update(csrf(request))
template_data['active_tab'] = WORKOUT_TAB
-
+
# Load workout
workout = get_object_or_404(TrainingSchedule, pk=id, user=request.user)
template_data['workout'] = workout
-
+
# Load day
day = get_object_or_404(Day, pk=day_id)
template_data['day'] = day
-
+
# Load set
-
+
# If the object is new, we will receice a 'None' (string) as the ID
# from the template, so we check for it (ValueError) and for an actual
# None (TypeError)
try:
int(set_id)
workout_set = get_object_or_404(Set, pk=set_id)
-
+
# Check if all objects belong to the workout
- if workout_set.exerciseday.id != day.id:
+ if workout_set.exerciseday.id != day.id:
return HttpResponseForbidden()
except ValueError, TypeError:
workout_set = Set()
-
+
template_data['set'] = workout_set
-
+
# Check if all objects belong to the workout
if day.training.id != workout.id:
return HttpResponseForbidden()
-
-
+
# Process request
if request.method == 'POST':
-
+
set_form = SetForm(request.POST, instance=workout_set)
-
+
# If the data is valid, save and redirect
if set_form.is_valid():
workout_set = set_form.save(commit=False)
workout_set.exerciseday = day
workout_set.save()
-
+
# The exercises are ManyToMany in DB, so we have to save with this function
set_form.save_m2m()
-
- return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs= {'id': id}))
+
+ return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs={'id': id}))
else:
set_form = SetForm(instance=workout_set)
template_data['set_form'] = set_form
-
+
return render_to_response('set/edit.html',
template_data,
context_instance=RequestContext(request))
+
@login_required
def delete_set(request, id, day_id, set_id):
""" Deletes the given set
"""
-
+
# Load the set
set_obj = get_object_or_404(Set, pk=set_id)
-
+
# Check if the user is the owner of the object
if set_obj.exerciseday.training.user == request.user:
set_obj.delete()
- return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs= {'id': id}))
+ return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs={'id': id}))
else:
return HttpResponseForbidden()
-
+
+
@login_required
def api_edit_set(request):
""" Allows to edit the order of the sets via an AJAX call
"""
-
+
if request.is_ajax():
-
+
# Set the order of the reps
if request.GET.get('do') == 'set_order':
day_id = request.GET.get('day_id')
new_set_order = request.GET.get('order')
-
- data = new_set_order
+
order = 0
for i in new_set_order.strip(',').split(','):
set_id = i.split('-')[1]
order += 1
-
+
set_obj = get_object_or_404(Set, pk=set_id, exerciseday=day_id)
-
+
# Check if the user is the owner of the object
if set_obj.exerciseday.training.user == request.user:
set_obj.order = order
set_obj.save()
else:
return HttpResponseForbidden()
-
-
+
return HttpResponse(_('Success'))
-
+
# This part is responsible for the in-place editing of the sets and settings
if request.GET.get('do') == 'edit_set':
template_data = {}
template_data.update(csrf(request))
-
+
# Load the objects
set_id = request.GET.get('set')
workout_set = get_object_or_404(Set, pk=set_id)
template_data['set'] = workout_set
-
+
exercise_id = request.GET.get('exercise')
exercise = get_object_or_404(Exercise, pk=exercise_id)
-
-
+
# Allow editing settings/repetitions that are not yet associated with the set
#
# We calculate here how many are there already [.filter(...)] and how many there could
# be at all (workout_set.sets)
current_settings = exercise.setting_set.filter(set_id=set_id).count()
diff = int(workout_set.sets) - current_settings
-
+
# If there are 'free slots', create some UUIDs for them, this gives them unique form
# names in the HTML and makes our lifes easier
new_settings = []
if diff > 0:
-
+
# Note: use UUIDs version 1 because they are monotonously increasing
# and the order of the fields later is important
new_settings = [uuid.uuid1() for i in range(0, diff)]
template_data['new_settings'] = new_settings
-
-
+
# Process request
if request.method == 'POST':
-
+
new_exercise_id = request.POST.get('current_exercise')
new_exercise = get_object_or_404(Exercise, pk=new_exercise_id)
-
+
# When there is more than one exercise per set, we need to manually set and replace
# the IDs here, otherwise they get lost
request_copy = request.POST
request_copy = request_copy.copy()
-
- exercise_list = [ i for i in request_copy.getlist('exercises') if i != exercise_id]
+
+ exercise_list = [i for i in request_copy.getlist('exercises') if i != exercise_id]
request_copy.setlist('exercises', exercise_list)
request_copy.update({'exercises': new_exercise_id})
-
-
+
set_form = SetForm(request_copy, instance=workout_set)
-
+
if set_form.is_valid():
set_form.save()
-
+
# Init a counter for the order in case we have to set it for new settings
# We don't actually care how hight the counter actually is, as long as the new
# settings get a number that puts them at the end
order_counter = 1
new_settings = []
-
+
# input fields for settings 'setting-x, setting-y, etc.',
# new settings: 'new-setting-UUID1, new-setting-UUID2, etc.'
for i in request.POST:
order_counter += 1
-
+
# old settings, update
if i.startswith('setting'):
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
@@ -812,33 +795,31 @@ def api_edit_set(request):
setting.reps = reps
setting.exercise = new_exercise
setting.save()
-
-
+
# New settings, put in a list, see below
if i.startswith('new-setting') and request.POST[i]:
-
+
new_settings.append(i)
-
+
# new settings, sort by name (important to keep the order as
# it was inputted in the website),create object and save
new_settings.sort()
for i in new_settings:
reps = int(request.POST[i])
-
+
setting = Setting()
setting.exercise = new_exercise
setting.set = workout_set
setting.reps = reps
setting.order = order_counter
setting.save()
-
+
template_data['exercise'] = exercise
-
+
return render_to_response('setting/ajax_edit.html',
template_data,
context_instance=RequestContext(request))
-
# ************************
# Settings functions
@@ -848,67 +829,68 @@ class SettingForm(ModelForm):
model = Setting
exclude = ('set', 'exercise')
+
@login_required
def edit_setting(request, id, set_id, exercise_id, setting_id=None):
template_data = {}
template_data.update(csrf(request))
template_data['active_tab'] = WORKOUT_TAB
-
+
# Load workout
workout = get_object_or_404(TrainingSchedule, pk=id, user=request.user)
template_data['workout'] = workout
-
+
# Load set and the FormSet
set_obj = get_object_or_404(Set, pk=set_id)
template_data['set'] = set_obj
-
+
SettingFormSet = modelformset_factory(Setting,
- exclude = ('set', 'exercise'),
- max_num = int(set_obj.sets),
- extra = int(set_obj.sets))
-
+ exclude=('set', 'exercise'),
+ max_num=int(set_obj.sets),
+ extra=int(set_obj.sets))
+
# Load exercise
exercise = get_object_or_404(Exercise, pk=exercise_id)
template_data['exercise'] = exercise
-
-
+
# Check that the set belongs to the workout
- if set_obj.exerciseday.training.id != workout.id:
+ if set_obj.exerciseday.training.id != workout.id:
return HttpResponseForbidden()
-
+
# Load setting
if not setting_id:
setting = Setting()
else:
setting = get_object_or_404(Setting, pk=setting_id)
template_data['setting'] = setting
-
+
# Process request
if request.method == 'POST':
-
+
# Process the FormSet, setting the set and the exercise
setting_form = SettingFormSet(request.POST)
if setting_form.is_valid():
-
+
order = 1
instances = setting_form.save(commit=False)
for setting_instance in instances:
setting_instance.set = set_obj
setting_instance.exercise = exercise
-
+
# Manualy set the order, the user can later use drag&drop to change this
if not setting_instance.order:
setting_instance.order = order
-
+
setting_instance.save()
-
+
order += 1
-
- return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs= {'id': id}))
+
+ return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs={'id': id}))
else:
- setting_form = SettingFormSet(queryset=Setting.objects.filter(exercise_id=exercise.id, set_id=set_obj.id))
+ setting_form = SettingFormSet(queryset=Setting.objects.filter(exercise_id=exercise.id,
+ set_id=set_obj.id))
template_data['setting_form'] = setting_form
-
+
return render_to_response('setting/edit.html',
template_data,
context_instance=RequestContext(request))
@@ -917,26 +899,25 @@ def edit_setting(request, id, set_id, exercise_id, setting_id=None):
def api_edit_setting(request):
""" 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':
new_setting_order = request.GET.get('order')
-
+
order = 0
for i in new_setting_order.strip(',').split(','):
setting_id = i.split('-')[1]
order += 1
-
+
setting_obj = get_object_or_404(Setting, pk=setting_id)
-
+
# Check if the user is the owner of the object
if setting_obj.set.exerciseday.training.user == request.user:
setting_obj.order = order
setting_obj.save()
else:
return HttpResponseForbidden()
-
-
+
return HttpResponse(_('Success'))
@@ -944,16 +925,15 @@ def api_edit_setting(request):
def delete_setting(request, id, set_id, exercise_id):
"""Deletes all the settings belonging to set_id and exercise_id
"""
-
+
# Load the workout
workout = get_object_or_404(TrainingSchedule, pk=id, user=request.user)
-
+
# Delete all settings
settings = Setting.objects.filter(exercise_id=exercise_id, set_id=set_id)
settings.delete()
-
- return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs= {'id': id}))
+ return HttpResponseRedirect(reverse('manager.views.view_workout', kwargs={'id': id}))
# ************************
@@ -969,31 +949,32 @@ class HelperDateForm(Form):
class WorkoutLogForm(ModelForm):
'''
Helper form for a WorkoutLog.
-
+
The field for the weight is overwritten here, activating localization (so a
German user can use ',' as the separator)
'''
- weight = DecimalField(decimal_places = 2,
- max_digits = 5,
+ weight = DecimalField(decimal_places=2,
+ max_digits=5,
localize=True)
-
+
class Meta:
model = WorkoutLog
+
def workout_log_add(request, pk):
'''
Add a new workout log
'''
-
+
template_data = {}
template_data.update(csrf(request))
template_data['active_tab'] = WORKOUT_TAB
-
+
# Load the day and check ownership
day = get_object_or_404(Day, pk=pk)
if day.get_owner_object().user != request.user:
return HttpResponseForbidden()
-
+
# We need several lists here because we need to assign specific form to each
# exercise: the entries for weight and repetitions have no indicator to which
# exercise they belong besides the form-ID, from Django's formset
@@ -1001,21 +982,21 @@ def workout_log_add(request, pk):
total_sets = 0
exercise_list = {}
form_to_exercise = {}
-
+
for exercise_set in day.set_set.all():
for exercise in exercise_set.exercises.all():
-
+
# Maximum possible values
total_sets = total_sets + int(exercise_set.sets)
counter_before = counter
counter = counter + int(exercise_set.sets) - 1
- form_id_range = range(counter_before, counter +1)
-
+ form_id_range = range(counter_before, counter + 1)
+
# Add to list
- exercise_list[exercise.id] = {'obj' : exercise,
+ exercise_list[exercise.id] = {'obj': exercise,
'sets': int(exercise_set.sets),
'form_ids': form_id_range}
-
+
counter = counter + 1
# Helper mapping form-ID <--> Exercise
for id in form_id_range:
@@ -1023,54 +1004,53 @@ 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,
+ form=WorkoutLogForm,
exclude=('user',
'workout',
'date'),
extra = total_sets)
# Process the request
if request.method == 'POST':
-
+
# Make a copy of the POST data and go through it. The reason for this is
# that the form expects a value for the exercise which is not present in
# the form (for space and usability reasons)
-
+
post_copy = request.POST.copy()
-
+
for form_id in form_to_exercise:
- if post_copy.get('form-%s-weight' % form_id) or post_copy.get('form-%s-reps' % form_id):
+ if post_copy.get('form-%s-weight' % form_id) or post_copy.get('form-%s-reps' % form_id):
post_copy['form-%s-exercise' % form_id] = form_to_exercise[form_id].id
-
+
# Pass the new data to the forms
- formset = WorkoutLogFormSet(data = post_copy)
- dateform = HelperDateForm(data = post_copy)
+ formset = WorkoutLogFormSet(data=post_copy)
+ dateform = HelperDateForm(data=post_copy)
if dateform.is_valid():
log_date = dateform.cleaned_data['date']
-
+
# If the data is valid, save and redirect to log overview page
if formset.is_valid():
- instances = formset.save(commit = False)
+ instances = formset.save(commit=False)
for instance in instances:
-
+
instance.user = request.user
instance.workout = day.training
instance.date = log_date
instance.save()
-
+
return HttpResponseRedirect(reverse('workout-log', kwargs={'pk': day.training.id}))
else:
# Initialise the formset with a queryset that won't return any objects
# (we only add new logs here and that seems to be the fastest way)
- formset = WorkoutLogFormSet(queryset=WorkoutLog.objects.filter(exercise = -1))
-
+ formset = WorkoutLogFormSet(queryset=WorkoutLog.objects.filter(exercise=-1))
+
formatted_date = date_format(datetime.date.today(), "SHORT_DATE_FORMAT")
dateform = HelperDateForm(initial={'date': formatted_date})
-
# Pass the correct forms to the exercise list
for exercise in exercise_list:
-
+
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]
@@ -1079,8 +1059,8 @@ def workout_log_add(request, pk):
template_data['exercises'] = exercise_list
template_data['formset'] = formset
template_data['dateform'] = dateform
- template_data['form_action'] = reverse('day-log', kwargs = {'pk': pk})
-
+ template_data['form_action'] = reverse('day-log', kwargs={'pk': pk})
+
return render_to_response('day/log.html',
template_data,
context_instance=RequestContext(request))
@@ -1090,53 +1070,52 @@ class WorkoutLogDetailView(DetailView):
'''
An overview of the workout's log
'''
-
+
# TODO: check ownership
-
+
model = TrainingSchedule
template_name = 'workout/log.html'
context_object_name = 'workout'
-
- def get_context_data(self,**kwargs):
-
+
+ def get_context_data(self, **kwargs):
+
# Call the base implementation first to get a context
- context =super(WorkoutLogDetailView, self).get_context_data(**kwargs)
-
+ context = super(WorkoutLogDetailView, self).get_context_data(**kwargs)
+
# Active tab
context['active_tab'] = WORKOUT_TAB
-
+
# Process the log entries so they are easier to show on template and can be used
# as input for the D3.js diagrams
workout_log = {}
for day in self.object.day_set.select_related():
workout_log[day] = {}
-
-
+
for set in day.set_set.select_related():
exercise_log = {}
-
+
for exercise in set.exercises.select_related():
exercise_log[exercise] = []
entry_log = SortedDict()
entry_log_by_reps = SortedDict()
-
+
for entry in exercise.workoutlog_set.all():
if not entry_log.get(entry.date):
entry_log[entry.date] = []
entry_log[entry.date].append(entry)
-
+
if not entry_log_by_reps.get(entry.reps):
entry_log_by_reps[entry.reps] = []
entry_log_by_reps[entry.reps].append(entry)
if entry_log:
exercise_log[exercise].append(entry_log)
-
+
if exercise_log:
workout_log[day][exercise] = {}
workout_log[day][exercise]['log_by_date'] = entry_log
workout_log[day][exercise]['log_by_reps'] = entry_log_by_reps
-
+
context['workout_log'] = workout_log
-
+
return context
diff --git a/nutrition/models.py b/nutrition/models.py
index 0cb28bd5a..267299065 100644
--- a/nutrition/models.py
+++ b/nutrition/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/>.
@@ -29,33 +29,31 @@ from exercises.models import Language
class NutritionPlan(models.Model):
""" A nutrition plan
"""
-
+
# Metaclass to set some other properties
class Meta:
-
+
# Order by creation_date, descending (oldest first)
ordering = ["-creation_date", ]
-
- user = models.ForeignKey(User, verbose_name = _('User'))
- language = models.ForeignKey(Language, verbose_name = _('Language'))
+
+ user = models.ForeignKey(User, verbose_name=_('User'))
+ language = models.ForeignKey(Language, verbose_name=_('Language'))
creation_date = models.DateField(_('Creation date'), auto_now_add=True)
- 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"'))
+ 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"'))
def __unicode__(self):
"""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('nutrition.views.view', kwargs= {'id': self.id})
-
+ return reverse('nutrition.views.view', kwargs={'id': self.id})
def get_nutritional_values(self):
# Sum the nutrional info
@@ -69,96 +67,93 @@ class NutritionPlan(models.Model):
'sodium': 0}
for meal in self.meal_set.select_related():
for item in meal.mealitem_set.select_related():
-
+
# Don't proceed if the ingredient was input by hand or has freetext units
if item.ingredient and item.amount_gramm:
nutritional_info['energy'] += item.ingredient.energy * item.amount_gramm / 100
- nutritional_info['protein'] += item.ingredient.protein * item.amount_gramm / 100
- nutritional_info['carbohydrates'] += item.ingredient.carbohydrates * item.amount_gramm / 100
+ nutritional_info['protein'] += item.ingredient.protein * 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['fat'] += item.ingredient.fat * item.amount_gramm / 100
+ nutritional_info['carbohydrates_sugar'] += item.ingredient.carbohydrates_sugar * item.amount_gramm / 100
+
+ nutritional_info['fat'] += item.ingredient.fat * item.amount_gramm / 100
if 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 / 100
+
if item.ingredient.fibres:
- nutritional_info['fibres'] += item.ingredient.fibres * item.amount_gramm / 100
-
+ nutritional_info['fibres'] += item.ingredient.fibres * item.amount_gramm / 100
+
if item.ingredient.sodium:
- nutritional_info['sodium'] += item.ingredient.sodium * item.amount_gramm / 100
+ nutritional_info['sodium'] += item.ingredient.sodium * item.amount_gramm / 100
return nutritional_info
-
-
+
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
-
+
class Ingredient(models.Model):
""" An ingredient, with some approximate nutrition values
"""
-
+
# Metaclass to set some other properties
class Meta:
ordering = ["name", ]
-
- language = models.ForeignKey(Language, verbose_name = _('Language'))
-
+
+ language = models.ForeignKey(Language, verbose_name=_('Language'))
+
name = models.CharField(max_length=200,
- verbose_name = _('Name'),)
-
+ verbose_name=_('Name'),)
+
energy = models.IntegerField(
- verbose_name = _('Energy'),
- help_text = _('In kcal per 100g'))
-
+ verbose_name=_('Energy'),
+ help_text=_('In kcal per 100g'))
+
protein = models.FloatField(
- verbose_name = _('Protein'),
- help_text = _('In g per 100g of product'))
-
+ 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_sugar = models.FloatField(blank = True,
- null = True,
- verbose_name = _('Sugar content in carbohydrates'),
- help_text = _('In g per 100g of product'))
-
- fat = models.FloatField(blank = True,
- verbose_name = _('Fat'),
- help_text = _('In g per 100g of product'))
-
- fat_saturated = models.FloatField(blank = True,
- null = True,
- verbose_name = _('Saturated fat content in fats'),
- help_text = _('In g per 100g of product'))
-
- fibres = models.FloatField(blank = True,
- null = True,
- verbose_name = _('Fibres'),
- help_text = _('In g per 100g of product'))
-
- sodium = models.FloatField(blank = True,
- null = True,
- verbose_name = _('Sodium'),
- help_text = _('In g per 100g of product'))
-
+ verbose_name=_('Carbohydrates'),
+ help_text=_('In g per 100g of product'))
+
+ carbohydrates_sugar = models.FloatField(blank=True,
+ null=True,
+ verbose_name=_('Sugar content in carbohydrates'),
+ help_text=_('In g per 100g of product'))
+
+ fat = models.FloatField(blank=True,
+ verbose_name=_('Fat'),
+ help_text=_('In g per 100g of product'))
+
+ fat_saturated = models.FloatField(blank=True,
+ null=True,
+ verbose_name=_('Saturated fat content in fats'),
+ help_text=_('In g per 100g of product'))
+
+ fibres = models.FloatField(blank=True,
+ null=True,
+ verbose_name=_('Fibres'),
+ help_text=_('In g per 100g of product'))
+
+ sodium = models.FloatField(blank=True,
+ null=True,
+ verbose_name=_('Sodium'),
+ help_text=_('In g per 100g of product'))
+
def get_absolute_url(self):
"""
Returns the canonical URL to view this object
"""
- return reverse('nutrition.views.ingredient_view', kwargs= {'id': self.id})
-
-
+ return reverse('nutrition.views.ingredient_view', kwargs={'id': self.id})
+
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s" % (self.name, )
-
def get_owner_object(self):
"""
Ingredient has no owner information
@@ -169,22 +164,20 @@ class Ingredient(models.Model):
class Meal(models.Model):
""" A meal
"""
-
+
# Metaclass to set some other properties
class Meta:
ordering = ["time", ]
-
-
- plan = models.ForeignKey(NutritionPlan, verbose_name = _('Nutrition plan'))
- order = models.IntegerField(max_length = 1, blank = True, verbose_name = _('Order'))
- time = models.TimeField(null = True, blank = True, verbose_name = _('Time (approx)'))
-
+
+ plan = models.ForeignKey(NutritionPlan, verbose_name=_('Nutrition plan'))
+ order = models.IntegerField(max_length=1, blank=True, verbose_name=_('Order'))
+ time = models.TimeField(null=True, blank=True, verbose_name=_('Time (approx)'))
+
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s Meal" % (self.order,)
-
def get_owner_object(self):
"""
Returns the object that has owner information
@@ -195,28 +188,20 @@ class Meal(models.Model):
class MealItem(models.Model):
""" 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'))
+
+ meal = models.ForeignKey(Meal, verbose_name=_('Nutrition plan'))
+ order = models.IntegerField(max_length=1, blank=True, verbose_name=_('Order'))
amount_gramm = models.IntegerField(max_length=4,
- blank = True,
- validators = [MaxValueValidator(1000)],
- verbose_name = _('Amount in gramms'))
- #amount_freetext = models.CharField(max_length=30,
- # blank = True,
- # verbose_name = _('Amount (freetext)'),
- # help_text = _('The amount in another unit, e.g. "a spoonfull" or "3 pieces"'))
- #ingredient_freetext = models.CharField(max_length=150,
- # blank = True,
- # verbose_name = _('Ingredient'),
- # help_text = _('If the ingredient is not in the system, enter the name here'))
- ingredient = models.ForeignKey(Ingredient, verbose_name = _('Ingredient'))
-
+ blank=True,
+ validators=[MaxValueValidator(1000)],
+ verbose_name=_('Amount in gramms'))
+ ingredient = models.ForeignKey(Ingredient, verbose_name=_('Ingredient'))
+
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s %s %s" % (self.order, self.amount_gramm or self.amount_freetext, self.ingredient)
-
+
def get_owner_object(self):
"""
Returns the object that has owner information
diff --git a/nutrition/tests.py b/nutrition/tests.py
index e2f61809d..749ae5031 100644
--- a/nutrition/tests.py
+++ b/nutrition/tests.py
@@ -1,26 +1,22 @@
# -*- 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.test import TestCase
-from django.test import LiveServerTestCase
from django.core.urlresolvers import reverse
-from selenium.webdriver.common.keys import Keys
-
from manager.tests.testcase import WorkoutManagerLiveServerTestCase
logger = logging.getLogger('workout_manager.custom')
@@ -32,64 +28,64 @@ class NutritionTest(WorkoutManagerLiveServerTestCase):
"""
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')
@@ -99,12 +95,12 @@ class NutritionTest(WorkoutManagerLiveServerTestCase):
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/nutrition/urls.py b/nutrition/urls.py
index aaba47b09..d0ee295ef 100644
--- a/nutrition/urls.py
+++ b/nutrition/urls.py
@@ -1,4 +1,4 @@
-from django.conf.urls import patterns, include, url
+from django.conf.urls import patterns, url
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import login_required
@@ -13,14 +13,14 @@ from nutrition.views import MealEditView
urlpatterns = patterns('nutrition.views',
url(r'^nutrition/overview/$', 'overview'),
-
+
# Plans
url(r'^nutrition/add/$', 'add'),
url(r'^nutrition/(?P<id>\d+)/view/$', 'view'),
url(r'^nutrition/(?P<pk>\d+)/copy/$',
'copy',
- name = 'nutrition-copy'),
-
+ name='nutrition-copy'),
+
url(r'^nutrition/(?P<pk>\d+)/delete/$',
login_required(PlanDeleteView.as_view()),
name='nutrition-delete'),
@@ -28,7 +28,7 @@ urlpatterns = patterns('nutrition.views',
login_required(PlanEditView.as_view()),
name='nutrition-edit'),
url(r'^nutrition/(?P<id>\d+)/pdf/$', 'export_pdf'),
-
+
# Meals
url(r'^nutrition/(?P<plan_pk>\d+)/meal/add/$',
login_required(MealCreateView.as_view()),
@@ -36,26 +36,26 @@ urlpatterns = patterns('nutrition.views',
url(r'^nutrition/meal/(?P<pk>\d+)/edit/$',
login_required(MealEditView.as_view()),
name='meal-edit'),
-
+
url(r'^nutrition/(?P<id>\d+)/delete/meal/$', 'delete_meal'),
-
+
# Meal items
url(r'^nutrition/(?P<id>\d+)/edit/meal/(?P<meal_id>\d+)/item/(?P<item_id>\w*)$', 'edit_meal_item'),
url(r'^nutrition/delete/meal/item/(?P<item_id>\d+)$', 'delete_meal_item'),
-
+
# Ingredients
url(r'^nutrition/ingredient/(?P<pk>\d+)/delete/$',
permission_required('exercises.change_exercise')(IngredientDeleteView.as_view()),
name='ingredient-delete'),
-
+
url(r'^nutrition/ingredient/(?P<pk>\d+)/edit/$',
permission_required('exercises.change_exercise')(IngredientEditView.as_view()),
name='ingredient-edit'),
-
+
url(r'^nutrition/ingredient/add/$',
permission_required('exercises.change_exercise')(IngredientCreateView.as_view()),
name='ingredient-add'),
-
+
url(r'^nutrition/ingredient/overview/$', 'ingredient_overview'),
url(r'^nutrition/ingredient/(?P<id>\d+)/view/$', 'ingredient_view'),
url(r'^nutrition/ingredient/search/$', 'ingredient_search'),
diff --git a/nutrition/views.py b/nutrition/views.py
index 132287bb8..480a47d40 100644
--- a/nutrition/views.py
+++ b/nutrition/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 License
import logging
import json
@@ -25,9 +25,7 @@ from django.http import HttpResponseForbidden
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
-from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
-from django.contrib.auth.decorators import permission_required
from django.forms import ModelForm
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
@@ -55,7 +53,7 @@ from workout_manager import get_version
from workout_manager.constants import NUTRITION_TAB
from workout_manager.generic_views import YamlFormMixin
from workout_manager.generic_views import YamlDeleteMixin
-from workout_manager import helpers
+from workout_manager import helpers
logger = logging.getLogger('workout_manager.custom')
@@ -68,49 +66,53 @@ logger = logging.getLogger('workout_manager.custom')
class PlanForm(ModelForm):
class Meta:
model = NutritionPlan
- exclude=('user', 'language', )
+ exclude = ('user', 'language', )
+
@login_required
def overview(request):
template_data = {}
template_data.update(csrf(request))
template_data['active_tab'] = NUTRITION_TAB
-
- plans = NutritionPlan.objects.filter(user = request.user)
+
+ plans = NutritionPlan.objects.filter(user=request.user)
template_data['plans'] = plans
-
+
return render_to_response('nutrition_overview.html',
template_data,
context_instance=RequestContext(request))
+
@login_required
def add(request):
"""Add a new nutrition plan and redirect to its page
"""
-
+
plan = NutritionPlan()
plan.user = request.user
plan.language = load_language()
plan.save()
-
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': plan.id}))
+
+ return HttpResponseRedirect(reverse('nutrition.views.view', kwargs={'id': plan.id}))
+
class PlanDeleteView(YamlDeleteMixin, DeleteView):
"""
Generic view to delete a nutritional plan
"""
-
+
active_tab = NUTRITION_TAB
model = NutritionPlan
success_url = reverse_lazy('nutrition.views.overview')
title = ugettext_lazy('Delete nutritional plan?')
form_action_urlname = 'nutrition-delete'
+
class PlanEditView(YamlFormMixin, UpdateView):
"""
Generic view to update an existing nutritional plan
"""
-
+
active_tab = NUTRITION_TAB
model = NutritionPlan
form_class = PlanForm
@@ -124,81 +126,81 @@ def view(request, id):
"""
template_data = {}
template_data['active_tab'] = NUTRITION_TAB
-
+
plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
template_data['plan'] = plan
-
+
# Load the language and pass it to the template
language = load_language()
template_data['language'] = language
-
+
# Get the nutrional info
-
+
template_data['nutritional_data'] = plan.get_nutritional_values()
-
- return render_to_response('view_nutrition_plan.html',
+
+ return render_to_response('view_nutrition_plan.html',
template_data,
context_instance=RequestContext(request))
+
@login_required
def copy(request, pk):
"""
Copy the nutrition plan
"""
-
+
plan = get_object_or_404(NutritionPlan, pk=pk, user=request.user)
-
-
+
# Copy plan
meals = plan.meal_set.all()
-
+
plan_copy = plan
plan_copy.pk = None
plan_copy.save()
-
+
# Copy the meals
for meal in meals:
meal_items = meal.mealitem_set.all()
-
+
meal_copy = meal
meal_copy.pk = None
meal_copy.plan = plan_copy
meal_copy.save()
-
+
# Copy the individual meal entries
for item in meal_items:
item_copy = item
item_copy.pk = None
item_copy.meal = meal_copy
item.save()
-
+
# Redirect
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': plan.id}))
+ return HttpResponseRedirect(reverse('nutrition.views.view', kwargs={'id': plan.id}))
def export_pdf(request, id):
"""Generates a PDF with the contents of a nutrition plan
-
+
See also
* http://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/
* http://www.reportlab.com/apis/reportlab/dev/platypus.html
"""
-
+
#Load the workout
plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
-
+
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(mimetype='application/pdf')
-
+
# Translators: translation can only have ASCII characters
- response['Content-Disposition'] = 'attachment; filename=%s.pdf' % _('nutritional-plan')
-
+ response['Content-Disposition'] = 'attachment; filename=%s.pdf' % _('nutritional-plan')
+
# Create the PDF object, using the response object as its "file."
doc = SimpleDocTemplate(response,
- pagesize = A4,
- title = _('Workout'),
- author = _('Workout Manager'),
- subject = _('Nutritional plan %s') % request.user.username)
+ pagesize=A4,
+ title=_('Workout'),
+ author=_('Workout Manager'),
+ subject=_('Nutritional plan %s') % request.user.username)
# Background colour for header
# Reportlab doesn't use the HTML hexadecimal format, but has a range of
@@ -206,26 +208,24 @@ def export_pdf(request, id):
header_colour = colors.Color(int('73', 16) / 255.0,
int('8a', 16) / 255.0,
int('5f', 16) / 255.0)
-
-
+
# container for the 'Flowable' objects
elements = []
-
+
styleSheet = getSampleStyleSheet()
data = []
-
+
# Iterate through the Plan
meal_markers = []
ingredient_markers = []
-
-
+
# Meals
i = 0
for meal in plan.meal_set.select_related():
i += 1
-
+
meal_markers.append(len(data))
-
+
if not meal.time:
P = Paragraph('<para align="center"><strong>%(meal_nr)s</strong></para>' %
{'meal_nr': i},
@@ -236,67 +236,61 @@ def export_pdf(request, id):
'meal_time': meal.time.strftime("%H:%M")},
styleSheet["Normal"])
data.append([P])
-
+
# Ingredients
for item in meal.mealitem_set.select_related():
ingredient_markers.append(len(data))
-
+
P = Paragraph('<para>%s</para>' % item.ingredient.name,
styleSheet["Normal"])
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)
]
-
+
# Set specific styles, e.g. background for title cells
- previous_marker = 0
for marker in meal_markers:
# Set background colour for headings
table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))
table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))
-
+
# Make the headings span the whole width
table_style.append(('SPAN', (0, marker), (-1, marker)))
-
- t = Table(data, style = table_style)
-
+ t = Table(data, style=table_style)
+
# Manually set the width of the columns
t._argW[0] = 2 * cm
-
# Set the title (if available)
if plan.description:
P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
- {'description' : plan.description},
+ {'description': plan.description},
styleSheet["Normal"])
elements.append(P)
-
+
# Filler
P = Paragraph('<para> </para>', styleSheet["Normal"])
elements.append(P)
-
-
# append the table to the document
elements.append(t)
-
-
+
# Footer, add filler paragraph
P = Paragraph('<para> </para>', styleSheet["Normal"])
elements.append(P)
-
+
# Print date and info
P = 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",
+ {'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)
-
+
doc.build(elements)
return response
@@ -309,40 +303,41 @@ def export_pdf(request, id):
class MealForm(ModelForm):
class Meta:
model = Meal
- exclude=('plan', 'order')
+ exclude = ('plan', 'order')
+
class MealItemForm(ModelForm):
class Meta:
model = MealItem
- exclude=('meal', 'order')
+ exclude = ('meal', 'order')
class MealCreateView(YamlFormMixin, CreateView):
"""
Generic view to add a new meal to a nutrition plan
"""
-
+
active_tab = NUTRITION_TAB
model = Meal
form_class = MealForm
title = ugettext_lazy('Add new meal')
owner_object = {'pk': 'plan_pk', 'class': NutritionPlan}
-
+
def form_valid(self, form):
- plan = get_object_or_404(NutritionPlan, pk = self.kwargs['plan_pk'], user=self.request.user)
+ plan = get_object_or_404(NutritionPlan, pk=self.kwargs['plan_pk'], user=self.request.user)
form.instance.plan = plan
form.instance.order = 1
return super(MealCreateView, self).form_valid(form)
-
+
def get_success_url(self):
- return reverse('nutrition.views.view', kwargs ={'id': self.object.plan.id})
+ return reverse('nutrition.views.view', kwargs={'id': self.object.plan.id})
# Send some additional data to the template
def get_context_data(self, **kwargs):
context = super(MealCreateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('meal-add',
kwargs={'plan_pk': self.kwargs['plan_pk']})
-
+
return context
@@ -350,74 +345,72 @@ class MealEditView(YamlFormMixin, UpdateView):
"""
Generic view to update an existing meal
"""
-
+
active_tab = NUTRITION_TAB
model = Meal
form_class = MealForm
title = ugettext_lazy('Edit meal')
form_action_urlname = 'meal-edit'
-
+
def get_success_url(self):
- return reverse('nutrition.views.view', kwargs ={'id': self.object.plan.id})
+ return reverse('nutrition.views.view', kwargs={'id': self.object.plan.id})
+
-
@login_required
def delete_meal(request, id):
"""Deletes the meal with the given ID
"""
-
+
# Load the meal
meal = get_object_or_404(Meal, pk=id)
plan = meal.plan
-
+
# Only delete if the user is the owner
if plan.user == request.user:
meal.delete()
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': plan.id}))
+ return HttpResponseRedirect(reverse('nutrition.views.view', kwargs={'id': plan.id}))
else:
return HttpResponseForbidden()
-
# ************************
# Meal ingredient functions
# ************************
-
@login_required
def delete_meal_item(request, item_id):
"""Deletes the meal ingredient with the given ID
"""
-
+
# Load the item
item = get_object_or_404(MealItem, pk=item_id)
plan = item.meal.plan
-
+
# Only delete if the user is the owner
if plan.user == request.user:
item.delete()
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': plan.id}))
+ return HttpResponseRedirect(reverse('nutrition.views.view', kwargs={'id': plan.id}))
else:
return HttpResponseForbidden()
+
@login_required
def edit_meal_item(request, id, meal_id, item_id=None):
"""Form to add a meal to a plan
"""
template_data = {}
template_data['active_tab'] = NUTRITION_TAB
-
+
# Load the plan
plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
template_data['plan'] = plan
-
+
# Load the meal
meal = get_object_or_404(Meal, pk=meal_id)
template_data['meal'] = meal
-
+
if meal.plan != plan:
return HttpResponseForbidden()
-
-
+
# Load the meal item
# If the object is new, we will receice a 'None' (string) as the ID
# from the template, so we check for it (ValueError) and for an actual
@@ -427,81 +420,81 @@ def edit_meal_item(request, id, meal_id, item_id=None):
meal_item = get_object_or_404(MealItem, pk=item_id)
template_data['ingredient'] = meal_item.ingredient.id
template_data['ingredient_searchfield'] = meal_item.ingredient.name
-
+
except ValueError, TypeError:
meal_item = MealItem()
template_data['meal_item'] = meal_item
-
+
# Check that javascript is activated This is used to hide the drop down list with the
# ingredients and use the autocompleter version instead. This is not only nicer but also much
# faster as the ingredient list from USDA is many thosand entries long.
js_active = request.GET.get('js', False)
template_data['js_active'] = js_active
-
-
+
# Process request
if request.method == 'POST':
meal_form = MealItemForm(request.POST, instance=meal_item)
-
+
# Pass the ingredient ID back to the template, this is originally set by the JQuery
# autocompleter, in case of errors (max. gramms reached), we need to set the ID manually
# so the user can simply submit again.
template_data['ingredient'] = request.POST.get('ingredient', '')
-
+
template_data['ingredient_searchfield'] = request.POST.get('ingredient_searchfield', '')
-
-
+
# If the data is valid, save and redirect
if meal_form.is_valid():
meal_item = meal_form.save(commit=False)
meal_item.meal = meal
meal_item.order = 1
meal_item.save()
-
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': id}))
-
+
+ return HttpResponseRedirect(reverse('nutrition.views.view', kwargs={'id': id}))
+
else:
meal_form = MealItemForm(instance=meal_item)
template_data['form'] = meal_form
-
- return render_to_response('edit_meal_item.html',
+
+ return render_to_response('edit_meal_item.html',
template_data,
context_instance=RequestContext(request))
+
# ************************
# Ingredient functions
# ************************
def ingredient_overview(request):
"""Show an overview of all ingredients
"""
-
+
template_data = {}
template_data['active_tab'] = NUTRITION_TAB
-
+
# Filter the ingredients the user will see by its language
# (the user can also want to see ingredients in English, see load_ingredient_languages)
languages = load_ingredient_languages(request)
-
+
# Load the ingredients and paginate it
- ingredients_list = Ingredient.objects.filter(language__in = languages)
-
+ ingredients_list = Ingredient.objects.filter(language__in=languages)
+
pagination = helpers.pagination(ingredients_list, request.GET.get('page'))
template_data['page_range'] = pagination['page_range']
template_data['ingredients'] = pagination['page']
-
+
return render_to_response('ingredient_overview.html',
template_data,
context_instance=RequestContext(request))
-
+
+
def ingredient_view(request, id):
template_data = {}
template_data['active_tab'] = NUTRITION_TAB
-
+
ingredient = get_object_or_404(Ingredient, pk=id)
template_data['ingredient'] = ingredient
-
- return render_to_response('view_ingredient.html',
+
+ return render_to_response('view_ingredient.html',
template_data,
context_instance=RequestContext(request))
@@ -509,26 +502,25 @@ def ingredient_view(request, id):
class IngredientForm(ModelForm):
class Meta:
model = Ingredient
- exclude=('language',)
+ exclude = ('language',)
class IngredientDeleteView(YamlDeleteMixin, DeleteView):
"""
Generic view to delete an existing ingredient
"""
-
+
model = Ingredient
template_name = 'delete.html'
success_url = reverse_lazy('nutrition.views.ingredient_overview')
-
-
+
# Send some additional data to the template
def get_context_data(self, **kwargs):
context = super(IngredientDeleteView, self).get_context_data(**kwargs)
-
+
context['title'] = _('Delete %s?') % self.object.name
context['form_action'] = reverse('ingredient-delete', kwargs={'pk': self.kwargs['pk']})
-
+
return context
@@ -536,7 +528,7 @@ class IngredientEditView(YamlFormMixin, UpdateView):
"""
Generic view to update an existing ingredient
"""
-
+
active_tab = NUTRITION_TAB
model = Ingredient
form_class = IngredientForm
@@ -544,23 +536,22 @@ class IngredientEditView(YamlFormMixin, UpdateView):
form_action_urlname = 'ingredient-edit'
-class IngredientCreateView(YamlFormMixin, CreateView):
+class IngredientCreateView(YamlFormMixin, CreateView):
"""
Generic view to add a new ingredient
"""
-
+
active_tab = NUTRITION_TAB
model = Ingredient
form_class = IngredientForm
title = ugettext_lazy('Add a new ingredient')
form_action = reverse_lazy('ingredient-add')
-
+
def form_valid(self, form):
form.instance.language = load_language()
return super(IngredientCreateView, self).form_valid(form)
-
def ingredient_search(request):
"""Search for an exercise, return the result as a JSON list or as HTML page, depending on how
the function was invoked
@@ -568,14 +559,14 @@ def ingredient_search(request):
# Filter the ingredients the user will see by its language
# (the user can also want to see ingredients in English, see load_ingredient_languages)
languages = load_ingredient_languages(request)
-
+
# Perform the search
q = request.GET.get('term', '')
- ingredients = Ingredient.objects.filter(name__icontains = q, language__in = languages)
-
+ ingredients = Ingredient.objects.filter(name__icontains=q, language__in=languages)
+
# AJAX-request, this comes from the autocompleter. Create a list and send it back as JSON
if request.is_ajax():
-
+
results = []
for ingredient in ingredients:
ingredient_json = {}
@@ -584,11 +575,11 @@ def ingredient_search(request):
ingredient_json['value'] = ingredient.name
results.append(ingredient_json)
data = json.dumps(results)
-
+
# Return the results to the server
mimetype = 'application/json'
return HttpResponse(data, mimetype)
-
+
# Usual search (perhaps JS disabled), present the results as normal HTML page
else:
template_data = {}
diff --git a/weight/admin.py b/weight/admin.py
index 9f726b1e2..e5eba14fa 100644
--- a/weight/admin.py
+++ b/weight/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 License
from weight.models import WeightEntry
diff --git a/weight/models.py b/weight/models.py
index eba67c07d..73ec02cff 100644
--- a/weight/models.py
+++ b/weight/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/>.
@@ -20,25 +20,25 @@ from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
+
class WeightEntry(models.Model):
"""Model for a weight point
"""
- creation_date = models.DateField(verbose_name = _('Date'))
- weight = models.FloatField(verbose_name = _('Weight'))
- user = models.ForeignKey(User, verbose_name = _('User'))
+ creation_date = models.DateField(verbose_name=_('Date'))
+ weight = models.FloatField(verbose_name=_('Weight'))
+ user = models.ForeignKey(User, verbose_name=_('User'))
# Metaclass to set some other properties
class Meta:
-
+
# Order by creation_date, ascending (oldest last), better for diagram
ordering = ["creation_date", ]
-
+
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s: %s kg" % (self.creation_date, self.weight)
-
-
+
def get_owner_object(self):
"""
Returns the object that has owner information
diff --git a/weight/tests.py b/weight/tests.py
index e11a66240..668fda2fb 100644
--- a/weight/tests.py
+++ b/weight/tests.py
@@ -1,27 +1,23 @@
# -*- 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.test import TestCase
-from django.test import LiveServerTestCase
from django.core.urlresolvers import reverse
-from selenium.webdriver.common.keys import Keys
-
from manager.tests.testcase import WorkoutManagerLiveServerTestCase
logger = logging.getLogger('workout_manager.custom')
@@ -33,30 +29,29 @@ class WeigtTest(WorkoutManagerLiveServerTestCase):
"""
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)
@@ -64,43 +59,42 @@ class WeigtTest(WorkoutManagerLiveServerTestCase):
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)
@@ -110,51 +104,51 @@ class WeigtTest(WorkoutManagerLiveServerTestCase):
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
+ # 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/weight/urls.py b/weight/urls.py
index f8f51f083..7d35dfb23 100644
--- a/weight/urls.py
+++ b/weight/urls.py
@@ -1,4 +1,4 @@
-from django.conf.urls import patterns, include, url
+from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from weight.views import WeightAddView
@@ -8,15 +8,15 @@ urlpatterns = patterns('weight.views',
url(r'^weight/add/$',
login_required(WeightAddView.as_view()),
- name = 'weight-add'),
-
+ name='weight-add'),
+
url(r'^weight/(?P<pk>\d+)/edit/$',
login_required(WeightUpdateView.as_view()),
- name = 'weight-edit'),
-
+ name='weight-edit'),
+
url(r'^weight/export_csv/$', 'export_csv'),
url(r'^weight/overview/$', 'overview'),
url(r'^weight/api/get_weight_data/$', 'get_weight_data'),
-
+
)