Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add scheduing options for workouts, first version, #8
Roland Geider0cdc90c380b1
diff --git a/wger/manager/fixtures/test-schedules.json b/wger/manager/fixtures/test-schedules.jsonnew file mode 100644index 000000000..18d44148e--- /dev/null+++ b/wger/manager/fixtures/test-schedules.json@@ -0,0 +1,94 @@+[+ {+ "pk": 1,+ "model": "manager.schedule",+ "fields": {+ "name": "my cool schedule that i found on the internet",+ "is_active": true,+ "first_step": null,+ "user": 2,+ "start_date": "2013-04-21",+ "is_loop": false+ }+ },+ {+ "pk": 2,+ "model": "manager.schedule",+ "fields": {+ "name": "my cool schedule that i found on the internet",+ "is_active": false,+ "first_step": null,+ "user": 1,+ "start_date": "2013-04-21",+ "is_loop": true+ }+ },+ {+ "pk": 3,+ "model": "manager.schedule",+ "fields": {+ "name": "another schedule of mine",+ "is_active": false,+ "first_step": null,+ "user": 1,+ "start_date": "2013-02-01",+ "is_loop": false+ }+ },+ {+ "pk": 4,+ "model": "manager.schedule",+ "fields": {+ "name": "Yet another cool schedule",+ "is_active": true,+ "first_step": null,+ "user": 1,+ "start_date": "2012-10-20",+ "is_loop": false+ }+ },+ {+ "pk": 1,+ "model": "manager.schedulestep",+ "fields": {+ "duration": 3,+ "comment": "",+ "workout": 1,+ "order": 1,+ "schedule": 2+ }+ },+ {+ "pk": 2,+ "model": "manager.schedulestep",+ "fields": {+ "duration": 5,+ "comment": "",+ "workout": 2,+ "order": 2,+ "schedule": 2+ }+ },+ {+ "pk": 3,+ "model": "manager.schedulestep",+ "fields": {+ "duration": 2,+ "comment": "",+ "workout": 1,+ "order": 3,+ "schedule": 2+ }+ },+ {+ "pk": 4,+ "model": "manager.schedulestep",+ "fields": {+ "duration": 3,+ "comment": "",+ "workout": 3,+ "order": 4,+ "schedule": 1+ }+ }+]diff --git a/wger/manager/migrations/0003_auto__add_schedule__add_schedulestep__chg_field_workout_comment.py b/wger/manager/migrations/0003_auto__add_schedule__add_schedulestep__chg_field_workout_comment.pynew file mode 100644index 000000000..a228a3efd--- /dev/null+++ b/wger/manager/migrations/0003_auto__add_schedule__add_schedulestep__chg_field_workout_comment.py@@ -0,0 +1,191 @@+# -*- coding: utf-8 -*-+import datetime+from south.db import db+from south.v2 import SchemaMigration+from django.db import models+++class Migration(SchemaMigration):++ def forwards(self, orm):+ # Adding model 'Schedule'+ db.create_table('manager_schedule', (+ ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),+ ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),+ ('first_step', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='first', unique=True, null=True, to=orm['manager.ScheduleStep'])),+ ('name', self.gf('django.db.models.fields.CharField')(max_length=100)),+ ('start_date', self.gf('django.db.models.fields.DateField')()),+ ('is_active', self.gf('django.db.models.fields.BooleanField')(default=True)),+ ('is_loop', self.gf('django.db.models.fields.BooleanField')(default=False)),+ ))+ db.send_create_signal('manager', ['Schedule'])++ # Adding model 'ScheduleStep'+ db.create_table('manager_schedulestep', (+ ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),+ ('schedule', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['manager.Schedule'])),+ ('workout', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['manager.Workout'])),+ ('duration', self.gf('django.db.models.fields.IntegerField')(max_length=1)),+ ('order', self.gf('django.db.models.fields.IntegerField')(default=1, max_length=1)),+ ('comment', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),+ ))+ db.send_create_signal('manager', ['ScheduleStep'])+++ # Changing field 'Workout.comment'+ db.alter_column('manager_workout', 'comment', self.gf('django.db.models.fields.CharField')(max_length=100))++ def backwards(self, orm):+ # Deleting model 'Schedule'+ db.delete_table('manager_schedule')++ # Deleting model 'ScheduleStep'+ db.delete_table('manager_schedulestep')+++ # Changing field 'Workout.comment'+ db.alter_column('manager_workout', 'comment', self.gf('django.db.models.fields.TextField')(max_length=100))++ models = {+ 'auth.group': {+ 'Meta': {'object_name': 'Group'},+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),+ 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})+ },+ 'auth.permission': {+ 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},+ 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})+ },+ 'auth.user': {+ 'Meta': {'object_name': 'User'},+ 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),+ 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),+ 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),+ 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),+ 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),+ 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),+ 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),+ 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),+ 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),+ 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),+ 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})+ },+ 'contenttypes.contenttype': {+ 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},+ 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})+ },+ 'exercises.exercise': {+ 'Meta': {'ordering': "['name']", 'object_name': 'Exercise'},+ 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['exercises.ExerciseCategory']"}),+ 'creation_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),+ 'description': ('django.db.models.fields.TextField', [], {'max_length': '2000', 'blank': 'True'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'muscles': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['exercises.Muscle']", 'symmetrical': 'False'}),+ 'muscles_secondary': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'secondary_muscles'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['exercises.Muscle']"}),+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),+ 'status': ('django.db.models.fields.CharField', [], {'default': "'1'", 'max_length': '2'}),+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})+ },+ 'exercises.exercisecategory': {+ 'Meta': {'ordering': "['name']", 'object_name': 'ExerciseCategory'},+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['exercises.Language']"}),+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})+ },+ 'exercises.language': {+ 'Meta': {'object_name': 'Language'},+ 'full_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'short_name': ('django.db.models.fields.CharField', [], {'max_length': '2'})+ },+ 'exercises.muscle': {+ 'Meta': {'ordering': "['name']", 'object_name': 'Muscle'},+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'is_front': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})+ },+ 'manager.day': {+ 'Meta': {'object_name': 'Day'},+ 'day': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['manager.DaysOfWeek']", 'symmetrical': 'False'}),+ 'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'training': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['manager.Workout']"})+ },+ 'manager.daysofweek': {+ 'Meta': {'object_name': 'DaysOfWeek'},+ 'day_of_week': ('django.db.models.fields.CharField', [], {'max_length': '9'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})+ },+ 'manager.schedule': {+ 'Meta': {'object_name': 'Schedule'},+ 'first_step': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'first'", 'unique': 'True', 'null': 'True', 'to': "orm['manager.ScheduleStep']"}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),+ 'is_loop': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),+ 'start_date': ('django.db.models.fields.DateField', [], {}),+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})+ },+ 'manager.schedulestep': {+ 'Meta': {'object_name': 'ScheduleStep'},+ 'comment': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),+ 'duration': ('django.db.models.fields.IntegerField', [], {'max_length': '1'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'order': ('django.db.models.fields.IntegerField', [], {'default': '1', 'max_length': '1'}),+ 'schedule': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['manager.Schedule']"}),+ 'workout': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['manager.Workout']"})+ },+ 'manager.set': {+ 'Meta': {'ordering': "['order']", 'object_name': 'Set'},+ 'exerciseday': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['manager.Day']"}),+ 'exercises': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['exercises.Exercise']", 'symmetrical': 'False'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'order': ('django.db.models.fields.IntegerField', [], {'max_length': '1', 'null': 'True', 'blank': 'True'}),+ 'sets': ('django.db.models.fields.IntegerField', [], {'default': '4'})+ },+ 'manager.setting': {+ 'Meta': {'ordering': "['order', 'id']", 'object_name': 'Setting'},+ 'comment': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),+ 'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['exercises.Exercise']"}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'order': ('django.db.models.fields.IntegerField', [], {'blank': 'True'}),+ 'reps': ('django.db.models.fields.IntegerField', [], {}),+ 'set': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['manager.Set']"})+ },+ 'manager.userprofile': {+ 'Meta': {'object_name': 'UserProfile'},+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'is_temporary': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),+ 'show_comments': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),+ 'show_english_ingredients': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),+ 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})+ },+ 'manager.workout': {+ 'Meta': {'ordering': "['-creation_date']", 'object_name': 'Workout'},+ 'comment': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),+ 'creation_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})+ },+ 'manager.workoutlog': {+ 'Meta': {'ordering': "['date', 'reps']", 'object_name': 'WorkoutLog'},+ 'date': ('django.db.models.fields.DateField', [], {}),+ 'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['exercises.Exercise']"}),+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'reps': ('django.db.models.fields.IntegerField', [], {}),+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),+ 'weight': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),+ 'workout': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['manager.Workout']"})+ }+ }++ complete_apps = ['manager']\ No newline at end of filediff --git a/wger/manager/models.py b/wger/manager/models.pyindex 3683db579..dfe132f8c 100644--- a/wger/manager/models.py+++ b/wger/manager/models.py@@ -15,6 +15,7 @@# 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/>.+import datetimeimport loggingimport json@@ -25,7 +26,7 @@ from django.utils.datastructures import SortedDictfrom django.contrib.auth.models import Userfrom django.core.validators import MaxValueValidatorfrom django.core.urlresolvers import reverse-+from django.core.exceptions import ObjectDoesNotExistfrom wger.exercises.models import Exercise@@ -44,11 +45,11 @@ class Workout(models.Model):ordering = ["-creation_date", ]creation_date = models.DateField(_('Creation date'), auto_now_add=True)- comment = models.TextField(verbose_name=_('Description'),+ comment = models.CharField(verbose_name=_('Description'),max_length=100,blank=True,- help_text=_('''A short description or goal of the workout.-For example 'Focus on back' or 'Week 1 of program xy'.'''))+ 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'))def get_absolute_url(self):@@ -61,7 +62,103 @@ For example 'Focus on back' or 'Week 1 of program xy'.'''))'''Return a more human-readable representation'''- return str(self.creation_date)+ return "{0}".format(self.comment)++ def get_owner_object(self):+ '''+ Returns the object that has owner information+ '''+ return self+++class ScheduleManager(models.Manager):+ '''+ Custom manager for workout schedules+ '''++ def get_current_workout(self, user):+ '''+ Finds the currently active workout for the user, by checking the schedules+ and the workouts+ '''++ # Try first to find an active schedule that has steps+ try:+ schedule = Schedule.objects.filter(user=user).get(is_active=True)+ if schedule.schedulestep_set.count():+ active_workout = schedule.get_current_scheduled_workout().workout+ else:+ # This is kind of wrong, but lets us continue to the correct place+ raise ObjectDoesNotExist++ # there are no active schedules, just return the last workout+ except ObjectDoesNotExist:++ schedule = False+ try:+ active_workout = Workout.objects.filter(user=user).latest('creation_date')++ # no luck, there aren't even workouts for the user+ except ObjectDoesNotExist:+ active_workout = False++ return (active_workout, schedule)+++class Schedule(models.Model):+ '''+ Model for a workout schedule.++ A schedule is a collection of workous that are done for a certain time.+ E.g. workouts A, B, C, A, B, C, and so on.+ '''++ objects = ScheduleManager()+ '''Custom manager'''++ user = models.ForeignKey(User,+ verbose_name=_('User'),+ editable=False)+ '''+ The user this schedule belongs to. This could be accessed through a step+ that points to a workout, that points to a user, but this is more straight+ forward and performant+ '''++ first_step = models.OneToOneField('ScheduleStep',+ verbose_name=_('First step'),+ related_name='first',+ blank=True,+ null=True,+ editable=False)+ '''The first step in the schedule'''++ name = models.CharField(verbose_name=_('Name'),+ max_length=100,+ help_text=_("Name or short description of the schedule. "+ "For example 'Program XYZ'."))+ '''Name or short description of the schedule.'''++ start_date = models.DateField(verbose_name=_('Start date'),+ default=datetime.date.today)+ '''The start date of this schedule'''++ is_active = models.BooleanField(verbose_name=_('Schedule active'),+ default=True,+ help_text=_("Tick the box if you want to mark this schedule "+ "as your active one (will be shown e.g. on your "+ "dashboard). All other schedules will then be "+ "marked as inactive"))+ '''A flag indicating whether the schedule is active (needed for dashboard)'''++ is_loop = models.BooleanField(verbose_name=_('Is loop'),+ default=False,+ help_text=_("Tick the box if you want to repeat the schedules "+ "in a loop (i.e. A, B, C, A, B, C, and so on)"))+ '''A flag indicating whether the schedule should act as a loop'''++ def get_absolute_url(self):+ return reverse('schedule-view', kwargs={'pk': self.id})def get_owner_object(self):'''@@ -69,6 +166,89 @@ For example 'Focus on back' or 'Week 1 of program xy'.'''))'''return self+ def save(self, *args, **kwargs):+ '''+ Only one schedule can be marked as active at a time+ '''+ if self.is_active:+ Schedule.objects.filter(user=self.user).update(is_active=False)+ self.is_active = True++ super(Schedule, self).save(*args, **kwargs)++ def get_current_scheduled_workout(self):+ '''+ Returns the currently active schedule step for a user+ '''+ steps = self.schedulestep_set.all()+ today = datetime.date.today()+ start_date = self.start_date+ found = False+ if not steps:+ return False+ while not found:+ for step in steps:+ current_limit = start_date + datetime.timedelta(weeks=step.duration)+ if current_limit > today:+ found = True+ return step+ if self.is_loop:+ start_date = current_limit+ else:+ return False+++class ScheduleStep(models.Model):+ '''+ Model for a step in a workout schedule.++ A step is basically a workout a with a bit of metadata (next and previous+ steps, duration, etc.)+ '''++ class Meta:+ '''+ Set default ordering+ '''+ ordering = ["order", ]++ schedule = models.ForeignKey(Schedule,+ verbose_name=_('schedule'),+ editable=False)+ '''The schedule is step belongs to'''++ workout = models.ForeignKey(Workout)+ '''The workout this step manages'''++ duration = models.IntegerField(max_length=1,+ verbose_name=_('Duration'),+ help_text=_('The duration in weeks'),+ default=4)+ '''The duration in weeks'''++ order = models.IntegerField(verbose_name=_('Order'),+ max_length=1,+ default=1,+ editable=False)++ comment = models.CharField(verbose_name=_('Comment'),+ max_length=100,+ help_text=_("A short comment or description"),+ blank=True)+ '''Short comment about the step'''++ def get_owner_object(self):+ '''+ Returns the object that has owner information+ '''+ return self.workout++ def __unicode__(self):+ '''+ Return a more human-readable representation+ '''+ return "ID: {0}".format(self.id)+class DaysOfWeek(models.Model):'''diff --git a/wger/manager/templates/index.html b/wger/manager/templates/index.htmlindex d111bbbca..99b9acd5d 100644--- a/wger/manager/templates/index.html+++ b/wger/manager/templates/index.html@@ -12,6 +12,7 @@<div class="ym-gbox-left"><h3>{% trans "Workout"%}</h3>{% if current_workout %}+ <p><a href="{% url 'wger.manager.views.workout.view' current_workout.id %}">{% if current_workout.comment %}{{ current_workout.comment }}@@ -19,8 +20,8 @@{% trans "Workout" %}{% endif %}</a>- <br> β {{ current_workout.creation_date }}-+ </p>+ β {{ current_workout.creation_date }}<ul>{% for day, exercise, is_workout in weekdays %}@@ -35,6 +36,13 @@{% endfor %}</ul>+ {% if schedule %}+ <p>+ β {% trans "This workout is part of a schedule:" %}+ <a href="{{schedule.get_absolute_url}}">{{schedule.name}}</a>+ </p>+ {% endif %}+{% else %}<div class="box warning">{% trans "No workouts found." %} {% trans "Use link to add one." %}@@ -49,6 +57,7 @@<h3>{% trans "Nutrition plan"%}</h3>{% if plan %}+ <p><a href="{% url 'wger.nutrition.views.plan.view' plan.id %}">{% if plan.description %}{{ plan.description }}@@ -56,7 +65,8 @@{% trans "Nutrition plan" %}{% endif %}</a>- <br> β {{ plan.creation_date }}+ </p>+ β {{ plan.creation_date }}<ul><li>@@ -115,10 +125,6 @@</div></div></div>--<p>- <em>{% trans "After adding a workout or a nutritional plan, you can edit them to set a goal." %}</em>-</p>{% endblock %}@@ -134,4 +140,11 @@title="{% trans 'My preferences' %}">{% trans "My preferences" %}</a></p>++<h3>{% trans "Info" %}</h3>+<p>{% blocktrans %}The current workout is selected from your active schedule+or, if you don't have one, simply by date.{% endblocktrans %}</p>++<p>{% trans "After adding a workout or a nutritional plan, you can edit them to set a goal." %}+</p>{% endblock %}diff --git a/wger/manager/templates/navigation.html b/wger/manager/templates/navigation.htmlindex 9bbbb29ba..47229b66c 100644--- a/wger/manager/templates/navigation.html+++ b/wger/manager/templates/navigation.html@@ -20,7 +20,16 @@{# #}{# Workout tab #}{# #}- <li {% if active_tab == 'workout' %}class="active"{% endif %}><a href="{% url 'wger.manager.views.workout.overview' %}" rel="nofollow">{% trans "Workouts" %}</a></li>+ <li class="dropdown {% if active_tab == 'workout' %}active{% endif %}">+ <a href="{% url 'wger.manager.views.workout.overview' %}"+ rel="nofollow"+ class="dropdown-toggle"+ data-toggle="dropdown">{% trans "Workouts" %} <b class="caret"></b></a>+ <ul class="dropdown-menu">+ <li><a href="{% url 'wger.manager.views.workout.overview' %}" rel="nofollow">{% trans "Workouts" %}</a></li>+ <li><a href="{% url 'schedule-overview' %}" rel="nofollow">{% trans "Workouts schedules" %}</a></li>+ </ul>+ </li>{# #}diff --git a/wger/manager/templates/schedule/overview.html b/wger/manager/templates/schedule/overview.htmlnew file mode 100644index 000000000..9778c37f5--- /dev/null+++ b/wger/manager/templates/schedule/overview.html@@ -0,0 +1,75 @@+{% extends "base.html" %}+{% load url from future %}+{% load i18n %}+{% load staticfiles %}++{% block title %}{% trans "Your schedules" %}{% endblock %}+++{% block content %}+<table id="workout-table">+ <thead>+ <tr>+ <th>{% trans "Active" %}</th>+ <th>{% trans "Description" %}</th>+ <th>{% trans "Date" %}</th>+ </tr>+ </thead>+ <tbody>+ {% for schedule in schedules %}+ <tr>+ <td>+ {% if schedule.is_active %}+ <img src="{% static 'images/icons/status-on.svg' %}"+ width="22"+ height="22"+ alt="{% trans 'Schedule active' %}"+ title="{% trans 'Schedule active' %}">+ {% endif %}+ </td>+ <td>+ <a href="{% url 'schedule-view' schedule.id %}">+ {{ schedule.name }}+ </a>+ </td>+ <td>+ {{ schedule.start_date }}+ </td>+ </tr>+ {% empty %}+ <tr>+ <td colspan="3">+ {% trans "No schedules found." %} {% trans "Use link to add one." %}+ </td>+ </tr>+ {% endfor %}+ </tbody>+</table>++<p>+<a href="{% url 'schedule-add' %}"+ class="modal-dialog">+<img src="{% static 'images/icons/new.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Add schedule' %}"+ title="{% trans 'Add schedule' %}">+{% trans "Add schedule" %}</a>+</p>++{% endblock %}+++{% block sidebar %}+<h3>{% trans "Your schedules" %}</h3>+<p>{% blocktrans %}Schedules are collections of workouts that you do in+succession.{% endblocktrans %}</p>++<p>{% blocktrans %}You can indicate how long you want to do each workout+before jumping to the next. It is also possible to create a loop, so you+always do the same workouts in succession, e.g. A > B > C > A > B > C and so on.{% endblocktrans %}</p>++<p>{% blocktrans %}The currently active schedule will remain active (and be+shown e.g. in your dashboard) till it reaches the last workout or till you+deactivate it, if it is a loop.{% endblocktrans %}</p>+{% endblock %}diff --git a/wger/manager/templates/schedule/view.html b/wger/manager/templates/schedule/view.htmlnew file mode 100644index 000000000..95faf0a4d--- /dev/null+++ b/wger/manager/templates/schedule/view.html@@ -0,0 +1,100 @@+{% extends "base.html" %}+{% load url from future %}+{% load i18n %}+{% load staticfiles %}++{% block title %}{{schedule.name}}{% endblock %}+++{% block content %}+<table id="workout-table">+ <thead>+ <tr>+ <th>{% trans "Step" %}</th>+ <th>{% trans "Workout" %}</th>+ <th>{% trans "Duration (in weeks)" %}</th>+ </tr>+ </thead>+ <tbody>+ {% for step in schedule.schedulestep_set.all %}+ <tr>+ <td>+ {% if active_workout == step %}<strong>{% endif %}+ <a href="{% url 'step-edit' step.id %}" class="modal-dialog">{{ forloop.counter }}</a>+ {% if active_workout == step %}</strong>{% endif %}+ </td>+ <td>+ {% if active_workout == step %}<strong>{% endif %}+ <a href="{% url 'wger.manager.views.workout.view' step.workout.id %}">{{ step.workout }}</a>+ {% if active_workout == step %}</strong>{% endif %}+ </td>+ <td>+ {% if active_workout == step %}<strong>{% endif %}+ {{ step.duration }}+ {% if active_workout == step %}**</strong>{% endif %}++ </td>+ </tr>+ {% endfor %}+ {% if schedule.is_loop %}+ <tr>+ <td colspan="3">+ <div class="alert alert-info" style="margin-bottom:0px;">+ {% trans "This schedule is a loop and will go through the workouts above till you deactivate it" %}+ </div>+ </td>+ </tr>+ {% endif %}+ </tbody>+</table>++<p>+<a href="{% url 'step-add' schedule.id %}"+ class="modal-dialog">+<img src="{% static 'images/icons/new.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Add workout' %}"+ title="{% trans 'Add workout' %}">+{% trans "Add workout" %}</a>+</p>+{% endblock %}+++{% block sidebar %}+<h3>{% trans "Adding workouts" %}</h3>++<p>{% blocktrans %}Add as many workouts to the schedule as you want. You can+later edit the order per drag-and-drop. It's also possible to add one workout+more than once.{% endblocktrans %}</p>+++<p>{% blocktrans %}At vero eos et accusam et justo duo dolores et ea rebum. Stet+clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.+Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod+tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.{% endblocktrans %}</p>++<h3>{% trans "Options" %}</h3>+<p>+<a href="{% url 'schedule-delete' schedule.id %}"+ class="modal-dialog">+<img src="{% static 'images/icons/trash.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Delete schedule' %}"+ title="{% trans 'Delete schedule' %}">+{% trans "Delete schedule" %}</a>+</p>++<p>+<a href="{% url 'schedule-edit' schedule.id %}"+ class="modal-dialog">+<img src="{% static 'images/icons/edit.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Edit schedule' %}"+ title="{% trans 'Edit schedule' %}">+{% trans "Edit schedule" %}</a>+</p>++{% endblock %}diff --git a/wger/manager/tests/__init__.py b/wger/manager/tests/__init__.pyindex f06c1bb95..ff239963a 100644--- a/wger/manager/tests/__init__.py+++ b/wger/manager/tests/__init__.py@@ -5,6 +5,8 @@ from wger.manager.tests.change_password import *from wger.manager.tests.workout import *from wger.manager.tests.day import *from wger.manager.tests.set import *+from wger.manager.tests.schedule import *+from wger.manager.tests.schedule_step import *from wger.manager.tests.weight_log import *from wger.manager.tests.copy_workout import *from wger.manager.tests.pdf import *diff --git a/wger/manager/tests/schedule.py b/wger/manager/tests/schedule.pynew file mode 100644index 000000000..fa6e2da12--- /dev/null+++ b/wger/manager/tests/schedule.py@@ -0,0 +1,162 @@+# 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 datetime++from django.core.urlresolvers import reverse++from wger.manager.models import Schedule+from wger.manager.models import Workout++from wger.manager.tests.testcase import STATUS_CODES_FAIL+from wger.manager.tests.testcase import WorkoutManagerTestCase+from wger.manager.tests.testcase import WorkoutManagerDeleteTestCase+from wger.manager.tests.testcase import WorkoutManagerEditTestCase+from wger.manager.tests.testcase import WorkoutManagerAddTestCase++logger = logging.getLogger('workout_manager.custom')+++class CreateScheduleTestCase(WorkoutManagerAddTestCase):+ '''+ Tests adding a schedule+ '''++ object_class = Schedule+ url = 'schedule-add'+ pk = 5+ user_success = 'test'+ user_fail = False+ data = {'name': 'My cool schedule',+ 'start_date': datetime.date.today(),+ 'is_active': True,+ 'is_loop': True}+++class DeleteScheduleTestCase(WorkoutManagerDeleteTestCase):+ '''+ Tests deleting a schedule+ '''++ object_class = Schedule+ url = 'schedule-delete'+ pk = 1+ user_success = 'test'+ user_fail = 'admin'+++class EditScheduleTestCase(WorkoutManagerEditTestCase):+ '''+ Tests editing a schedule+ '''++ object_class = Schedule+ url = 'schedule-edit'+ pk = 3+ data = {'name': 'An updated name',+ 'start_date': datetime.date.today(),+ 'is_active': True,+ 'is_loop': True}+++class ScheduleTestCase(WorkoutManagerTestCase):+ '''+ Other tests+ '''++ def schedule_detail_page(self, fail=False):+ '''+ Helper function+ '''++ response = self.client.get(reverse('schedule-view', kwargs={'pk': 2}))+ if fail:+ self.assertIn(response.status_code, STATUS_CODES_FAIL)+ else:+ self.assertEqual(response.status_code, 200)+ self.assertContains(response, 'This schedule is a loop')++ schedule = Schedule.objects.get(pk=2)+ schedule.is_loop = False+ schedule.save()++ response = self.client.get(reverse('schedule-view', kwargs={'pk': 2}))+ self.assertEqual(response.status_code, 200)+ self.assertNotContains(response, 'This schedule is a loop')++ def test_schedule_detail_page_owner(self):+ '''+ Tests the schedule detail page as the owning user+ '''++ self.user_login()+ self.schedule_detail_page()++ def test_schedule_detail_page_other(self):+ '''+ Tests the schedule detail page as a different user+ '''++ self.user_login('test')+ self.schedule_detail_page(fail=True)++ def test_schedule_overview(self):+ '''+ Tests the schedule overview+ '''+ self.user_login()++ response = self.client.get(reverse('schedule-overview'))+ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.context['schedules']), 3)+ self.assertContains(response, 'Schedule active')++ schedule = Schedule.objects.get(pk=4)+ schedule.is_active = False+ schedule.save()++ response = self.client.get(reverse('schedule-overview'))+ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.context['schedules']), 3)+ self.assertNotContains(response, 'Schedule active')++ def test_schedule_active(self):+ '''+ Tests that only one schedule can be active at a time (per user)+ '''+ def get_schedules():+ schedule1 = Schedule.objects.get(pk=2)+ schedule2 = Schedule.objects.get(pk=3)+ schedule3 = Schedule.objects.get(pk=4)++ return (schedule1, schedule2, schedule3)++ self.user_login()+ (schedule1, schedule2, schedule3) = get_schedules()+ self.assertTrue(schedule3.is_active)++ schedule1.is_active = True+ schedule1.save()+ (schedule1, schedule2, schedule3) = get_schedules()+ self.assertTrue(schedule1.is_active)+ self.assertFalse(schedule2.is_active)+ self.assertFalse(schedule3.is_active)++ schedule2.is_active = True+ schedule2.save()+ (schedule1, schedule2, schedule3) = get_schedules()+ self.assertFalse(schedule1.is_active)+ self.assertTrue(schedule2.is_active)+ self.assertFalse(schedule3.is_active)diff --git a/wger/manager/tests/schedule_step.py b/wger/manager/tests/schedule_step.pynew file mode 100644index 000000000..1e0f942cd--- /dev/null+++ b/wger/manager/tests/schedule_step.py@@ -0,0 +1,54 @@+# 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 datetime++from django.core.urlresolvers import reverse+from django.core.urlresolvers import reverse_lazy++from wger.manager.models import Schedule+from wger.manager.models import ScheduleStep+from wger.manager.models import Workout++from wger.manager.tests.testcase import STATUS_CODES_FAIL+from wger.manager.tests.testcase import WorkoutManagerTestCase+from wger.manager.tests.testcase import WorkoutManagerDeleteTestCase+from wger.manager.tests.testcase import WorkoutManagerEditTestCase+from wger.manager.tests.testcase import WorkoutManagerAddTestCase+++class CreateScheduleStepTestCase(WorkoutManagerAddTestCase):+ '''+ Tests adding a schedule+ '''++ object_class = ScheduleStep+ url = reverse_lazy('step-add', kwargs={'schedule_pk': 1})+ pk = 5+ user_success = 'test'+ user_fail = False+ data = {'workout': 3,+ 'duration': 4}+++class EditScheduleStepTestCase(WorkoutManagerEditTestCase):+ '''+ Tests editing a schedule+ '''++ object_class = ScheduleStep+ url = 'step-edit'+ pk = 2+ data = {'workout': 1,+ 'duration': 8}diff --git a/wger/manager/tests/temporary_users.py b/wger/manager/tests/temporary_users.pyindex f5c8e498f..384e3dcfc 100644--- a/wger/manager/tests/temporary_users.py+++ b/wger/manager/tests/temporary_users.py@@ -94,7 +94,7 @@ class DemoUserTestCase(WorkoutManagerTestCase):'''Tests that demo users see a notice on every page'''- demo_notice_text = 'You are using a temporary account'+ demo_notice_text = 'You are using a guest account'self.user_login('demo')self.assertContains(self.client.get(reverse('dashboard')), demo_notice_text)self.assertContains(self.client.get(reverse('wger.manager.views.workout.overview')),diff --git a/wger/manager/tests/testcase.py b/wger/manager/tests/testcase.pyindex 5a44f251a..c5dcb52a3 100644--- a/wger/manager/tests/testcase.py+++ b/wger/manager/tests/testcase.py@@ -34,7 +34,8 @@ class WorkoutManagerTestCase(TestCase):'test-weight-units','test-ingredients','test-nutrition-data',- 'test-workout-data')+ 'test-workout-data',+ 'test-schedules')current_user = 'anonymous'def setUp(self):diff --git a/wger/manager/urls.py b/wger/manager/urls.pyindex c314dd987..d11b779e6 100644--- a/wger/manager/urls.py+++ b/wger/manager/urls.py@@ -3,6 +3,8 @@ from django.contrib.auth.decorators import login_requiredfrom django.core.urlresolvers import reverse_lazyfrom django.views.generic import TemplateView+from wger.manager.views import schedule+from wger.manager.views import schedule_stepfrom wger.manager.views.workout import WorkoutEditViewfrom wger.manager.views.workout import WorkoutDeleteViewfrom wger.manager.views.log import WorkoutLogDetailView@@ -63,6 +65,31 @@ urlpatterns = patterns('wger.manager.views',login_required(WorkoutLogUpdateView.as_view()),name='workout-log-edit'),+ # Schedules+ url(r'^workout/schedule/overview$',+ 'schedule.overview',+ name='schedule-overview'),+ url(r'^workout/schedule/add$',+ login_required(schedule.ScheduleCreateView.as_view()),+ name='schedule-add'),+ url(r'^workout/schedule/(?P<pk>\d+)/view/$',+ 'schedule.view',+ name='schedule-view'),+ url(r'^workout/schedule/(?P<pk>\d+)/edit/$',+ login_required(schedule.ScheduleEditView.as_view()),+ name='schedule-edit'),+ url(r'^workout/schedule/(?P<pk>\d+)/delete/$',+ login_required(schedule.ScheduleDeleteView.as_view()),+ name='schedule-delete'),++ # Schedule steps+ url(r'^workout/schedule/(?P<schedule_pk>\d+)/step/add$',+ login_required(schedule_step.StepCreateView.as_view()),+ name='step-add'),+ url(r'^workout/schedule/step/(?P<pk>\d+)/edit$',+ login_required(schedule_step.StepEditView.as_view()),+ name='step-edit'),+# Daysurl(r'^workout/day/(?P<pk>\d+)/edit/$',login_required(DayEditView.as_view()),diff --git a/wger/manager/views/misc.py b/wger/manager/views/misc.pyindex 261195a1d..dc231da62 100644--- a/wger/manager/views/misc.py+++ b/wger/manager/views/misc.py@@ -38,6 +38,7 @@ from wger.manager.demo import create_temporary_userfrom wger.manager.models import DaysOfWeekfrom wger.manager.models import Workout+from wger.manager.models import Schedulefrom wger.nutrition.models import NutritionPlan@@ -87,12 +88,11 @@ def dashboard(request):template_data = {}- # Load the last workout, if one exists- try:- current_workout = Workout.objects.filter(user=request.user).latest('creation_date')- except ObjectDoesNotExist:- current_workout = False+ # Load the last workout, either from a schedule or a 'regular' one+ (current_workout, schedule) = Schedule.objects.get_current_workout(request.user)+template_data['current_workout'] = current_workout+ template_data['schedule'] = schedule# Load the last nutritional plan, if one existstry:diff --git a/wger/manager/views/schedule.py b/wger/manager/views/schedule.pynew file mode 100644index 000000000..1b472369e--- /dev/null+++ b/wger/manager/views/schedule.py@@ -0,0 +1,121 @@+# -*- coding: utf-8 -*-++# This file is part of Workout Manager.+#+# Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++import logging++from django.template import RequestContext+from django.shortcuts import render_to_response+from django.shortcuts import get_object_or_404+from django.http import HttpResponseRedirect+from django.core.context_processors import csrf+from django.core.urlresolvers import reverse+from django.core.urlresolvers import reverse_lazy+from django.utils.translation import ugettext as _+from django.utils.translation import ugettext_lazy++from django.contrib.auth.decorators import login_required++from django.views.generic import CreateView+from django.views.generic import DeleteView+from django.views.generic import UpdateView++from wger.manager.models import Schedule+from wger.manager.models import Workout++from wger.manager.forms import WorkoutForm+from wger.manager.forms import WorkoutCopyForm+++from wger.utils.generic_views import YamlFormMixin+from wger.utils.generic_views import YamlDeleteMixin+++logger = logging.getLogger('workout_manager.custom')+++@login_required+def overview(request):+ '''+ An overview of all the user's schedules+ '''++ template_data = {}+ template_data['schedules'] = Schedule.objects.filter(user=request.user)+ return render_to_response('schedule/overview.html',+ template_data,+ context_instance=RequestContext(request))+++@login_required+def view(request, pk):+ '''+ Show the workout schedule+ '''+ template_data = {}++ schedule = get_object_or_404(Schedule, pk=pk, user=request.user)+ template_data['schedule'] = schedule+ if schedule.is_active:+ template_data['active_workout'] = schedule.get_current_scheduled_workout()+ else:+ template_data['active_workout'] = False++ schedule.get_current_scheduled_workout()++ return render_to_response('schedule/view.html',+ template_data,+ context_instance=RequestContext(request))+++class ScheduleCreateView(YamlFormMixin, CreateView):+ '''+ Creates a new workout schedule+ '''++ model = Schedule+ success_url = reverse_lazy('schedule-overview')+ title = ugettext_lazy('Create schedule')+ form_action = reverse_lazy('schedule-add')++ def form_valid(self, form):+ '''set the submitter'''+ form.instance.user = self.request.user+ return super(ScheduleCreateView, self).form_valid(form)++ def get_success_url(self):+ return reverse_lazy('schedule-view', kwargs={'pk': self.object.id})+++class ScheduleDeleteView(YamlDeleteMixin, DeleteView):+ '''+ Generic view to delete a schedule+ '''++ model = Schedule+ success_url = reverse_lazy('schedule-overview')+ title = ugettext_lazy('Delete schedule')+ form_action_urlname = 'schedule-delete'+ messages = ugettext_lazy('Schedule was successfully deleted')+++class ScheduleEditView(YamlFormMixin, UpdateView):+ '''+ Generic view to update an existing workout routine+ '''++ model = Schedule+ title = ugettext_lazy('Edit schedule')+ form_action_urlname = 'schedule-edit'diff --git a/wger/manager/views/schedule_step.py b/wger/manager/views/schedule_step.pynew file mode 100644index 000000000..595755fc5--- /dev/null+++ b/wger/manager/views/schedule_step.py@@ -0,0 +1,138 @@+# -*- coding: utf-8 -*-++# This file is part of Workout Manager.+#+# Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++import logging++from django.template import RequestContext+from django.shortcuts import render_to_response+from django.shortcuts import get_object_or_404+from django.http import HttpResponseRedirect+from django.core.context_processors import csrf+from django.core.urlresolvers import reverse+from django.core.urlresolvers import reverse_lazy+from django.utils.translation import ugettext as _+from django.utils.translation import ugettext_lazy+from django.db import models+from django.forms import ModelForm+from django.forms import ModelChoiceField++from django.contrib.auth.decorators import login_required++from django.views.generic import CreateView+from django.views.generic import DeleteView+from django.views.generic import UpdateView++from wger.manager.models import Schedule+from wger.manager.models import ScheduleStep+from wger.manager.models import Workout++from wger.manager.forms import WorkoutForm+from wger.manager.forms import WorkoutCopyForm+++from wger.utils.generic_views import YamlFormMixin+from wger.utils.generic_views import YamlDeleteMixin+++logger = logging.getLogger('workout_manager.custom')+++@login_required+def view(request, pk):+ '''+ Show the workout schedule+ '''+ template_data = {}++ step = get_object_or_404(ScheduleStep, pk=pk)+ template_data['step'] = step++ return render_to_response('schedule_step/view.html',+ template_data,+ context_instance=RequestContext(request))+++class StepCreateView(YamlFormMixin, CreateView):+ '''+ Creates a new workout schedule+ '''++ model = ScheduleStep+ title = ugettext_lazy('Add step to schedule')++ def get_form_class(self):+ '''+ The form can only show the workouts belonging to the user.++ This is defined here because only at this point during the request+ have we access to the current user+ '''++ class StepForm(ModelForm):+ workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user))++ class Meta:+ model = ScheduleStep++ return StepForm++ def get_context_data(self, **kwargs):+ context = super(StepCreateView, self).get_context_data(**kwargs)+ context['form_action'] = reverse('step-add',+ kwargs={'schedule_pk': self.kwargs['schedule_pk']})+ return context++ def get_success_url(self):+ return reverse('schedule-view', kwargs={'pk': self.kwargs['schedule_pk']})++ def form_valid(self, form):+ '''Set the schedule and the order'''++ schedule = Schedule.objects.get(pk=self.kwargs['schedule_pk'])++ max_order = schedule.schedulestep_set.all().aggregate(models.Max('order'))+ form.instance.schedule = schedule+ form.instance.order = (max_order['order__max'] or 0) + 1+ return super(StepCreateView, self).form_valid(form)+++class StepEditView(YamlFormMixin, UpdateView):+ '''+ Generic view to update an existing schedule step+ '''++ model = ScheduleStep+ title = ugettext_lazy('Edit schedule step')+ form_action_urlname = 'step-edit'++ def get_form_class(self):+ '''+ The form can only show the workouts belonging to the user.++ This is defined here because only at this point during the request+ have we access to the current user+ '''++ class StepForm(ModelForm):+ workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user))++ class Meta:+ model = ScheduleStep++ return StepForm++ def get_success_url(self):+ return reverse('schedule-view', kwargs={'pk': self.object.schedule_id})