Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Replace single triple quotes

Roland Geider6a8655d77c67
diff --git a/extras/bench/test_Simple.py b/extras/bench/test_Simple.py
index 128db61b3..93dc86d62 100644
--- a/extras/bench/test_Simple.py
+++ b/extras/bench/test_Simple.py
@@ -1,27 +1,27 @@
# -*- coding: iso-8859-15 -*-
-'''
+"""
Simple FunkLoad test
-'''
+"""
import unittest
from random import random
from funkload.FunkLoadTestCase import FunkLoadTestCase
class Simple(FunkLoadTestCase):
- '''
+ """
This test uses the configuration file Simple.conf.
- '''
+ """
def setUp(self):
- '''
+ """
Setting up test.
- '''
+ """
self.server_url = self.conf_get('main', 'url')
def test_simple(self):
# The description should be set in the configuration file
server_url = self.server_url
- # Exercises
+ # Exercises
self.get(server_url + '/en/exercise/overview/', description='Get exercise overview')
self.get(server_url + '/en/exercise/muscle/overview/', description='Get muscle overview')
self.get(server_url + '/de/exercise/79/view/', description='Get exercise page')
diff --git a/extras/scripts/filter-fixtures.py b/extras/scripts/filter-fixtures.py
index dbffbe8bd..529a42572 100644
--- a/extras/scripts/filter-fixtures.py
+++ b/extras/scripts/filter-fixtures.py
@@ -14,21 +14,21 @@
#
# You should have received a copy of the GNU Affero General Public License
-'''
+"""
Simple script that filters the output of django's dumpdata command into more
manageable chunks.
Create the data.json e.g. with:
python ../../manage.py dumpdata --indent 4 --natural-foreign > data.json
-'''
+"""
import json
def filter_dump(data, model_list, filename):
- '''
+ """
Helper function
- '''
+ """
filter_data = [i for i in data if i['model'] in model_list]
with open(filename, 'w') as outfile:
json.dump(filter_data, outfile, indent=4)
diff --git a/wger/__main__.py b/wger/__main__.py
index ff4bbeba2..96cb41190 100644
--- a/wger/__main__.py
+++ b/wger/__main__.py
@@ -22,11 +22,11 @@ import sys
from invoke import run
-'''
+"""
This simple wrapper script is used as a console entry point in the packaged
version of the application. It simply redirects all arguments to the invoke
command, which does all the work.
-'''
+"""
invoke_cmd = 'invoke '
diff --git a/wger/config/models.py b/wger/config/models.py
index 705ee5615..309852379 100644
--- a/wger/config/models.py
+++ b/wger/config/models.py
@@ -43,11 +43,11 @@ logger = logging.getLogger(__name__)
class LanguageConfig(models.Model):
- '''
+ """
Configuration for languages
Allows to specify what exercises and ingredients are shown for each language
- '''
+ """
SHOW_ITEM_EXERCISES = '1'
SHOW_ITEM_INGREDIENTS = '2'
SHOW_ITEM_LIST = (
@@ -69,21 +69,21 @@ class LanguageConfig(models.Model):
show = models.BooleanField(default=1)
class Meta:
- '''
+ """
Set some other properties
- '''
+ """
ordering = ["item", "language_target", ]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"Config for language {0}".format(self.language)
def save(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
super(LanguageConfig, self).save(*args, **kwargs)
@@ -95,9 +95,9 @@ class LanguageConfig(models.Model):
delete_template_fragment_cache('exercise-overview', self.language_id)
def delete(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
# Cached objects
cache.delete(cache_mapper.get_language_config_key(self.language, self.item))
@@ -110,12 +110,12 @@ class LanguageConfig(models.Model):
class GymConfig(models.Model):
- '''
+ """
System wide configuration for gyms
At the moment this only allows to set one gym as the default
TODO: close registration (users can only become members thorough an admin)
- '''
+ """
default_gym = models.ForeignKey(Gym,
verbose_name=_('Default gym'),
@@ -126,20 +126,20 @@ class GymConfig(models.Model):
null=True,
blank=True,
on_delete=models.CASCADE)
- '''
+ """
Default gym for the wger installation
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"Default gym {0}".format(self.default_gym)
def save(self, *args, **kwargs):
- '''
+ """
Perform additional tasks
- '''
+ """
if self.default_gym:
# All users that have no gym set in the profile are edited
diff --git a/wger/config/signals.py b/wger/config/signals.py
index 7d882b105..8f3de71ed 100644
--- a/wger/config/signals.py
+++ b/wger/config/signals.py
@@ -26,10 +26,10 @@ from wger.core.models import Language
@receiver(post_save, sender=Language)
def init_language_config(sender, instance, created, **kwargs):
- '''
+ """
Creates language config entries when new languages are created
(all combinations of all languages)
- '''
+ """
for language_source in Language.objects.all():
for language_target in Language.objects.all():
if not LanguageConfig.objects.filter(language=language_source)\
diff --git a/wger/config/tests/test_custom_header.py b/wger/config/tests/test_custom_header.py
index 35d963e74..41e72642a 100644
--- a/wger/config/tests/test_custom_header.py
+++ b/wger/config/tests/test_custom_header.py
@@ -24,9 +24,9 @@ from wger.gym.models import Gym
class GymNameHeaderTestCase(WorkoutManagerTestCase):
- '''
+ """
Test case for showing gym name on application header
- '''
+ """
def check_header(self, gym=None):
@@ -34,9 +34,9 @@ class GymNameHeaderTestCase(WorkoutManagerTestCase):
self.assertEqual(response.context['custom_header'], gym)
def test_custom_header_gym_members(self):
- '''
+ """
Test the custom header for gym members
- '''
+ """
# Gym 1, custom header activated
gym = Gym.objects.get(pk=1)
@@ -62,7 +62,7 @@ class GymNameHeaderTestCase(WorkoutManagerTestCase):
self.check_header(gym=None)
def test_custom_header_anonymous_user(self):
- '''
+ """
Test the custom header for logged out users
- '''
+ """
self.check_header(gym=None)
diff --git a/wger/config/tests/test_gym_config.py b/wger/config/tests/test_gym_config.py
index 8317ea0d6..d9d50c858 100644
--- a/wger/config/tests/test_gym_config.py
+++ b/wger/config/tests/test_gym_config.py
@@ -30,14 +30,14 @@ from wger.gym.models import (
class GymConfigTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the system wide gym configuration
- '''
+ """
def test_default_gym(self):
- '''
+ """
Test that newly registered users get a gym
- '''
+ """
gym = Gym.objects.get(pk=2)
gym_config = GymConfig.objects.get(pk=1)
@@ -58,9 +58,9 @@ class GymConfigTestCase(WorkoutManagerTestCase):
self.assertEqual(new_user.gymuserconfig.gym, gym)
def test_no_default_gym(self):
- '''
+ """
Test the user registration without a default gym
- '''
+ """
gym_config = GymConfig.objects.get(pk=1)
gym_config.default_gym = None
@@ -80,9 +80,9 @@ class GymConfigTestCase(WorkoutManagerTestCase):
self.assertRaises(GymUserConfig.DoesNotExist, GymUserConfig.objects.get, user=new_user)
def test_update_userprofile(self):
- '''
+ """
Test setting the gym for users when setting a default gym
- '''
+ """
UserProfile.objects.update(gym=None)
GymUserConfig.objects.all().delete()
diff --git a/wger/config/tests/test_language_config.py b/wger/config/tests/test_language_config.py
index fda4ec5ad..690b0f541 100644
--- a/wger/config/tests/test_language_config.py
+++ b/wger/config/tests/test_language_config.py
@@ -21,9 +21,9 @@ from wger.core.tests.base_testcase import WorkoutManagerEditTestCase
class EditLanguageConfigTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a language config
- '''
+ """
object_class = LanguageConfig
url = 'config:language_config:edit'
diff --git a/wger/config/views/gym_config.py b/wger/config/views/gym_config.py
index 8c284d09b..ad1021032 100644
--- a/wger/config/views/gym_config.py
+++ b/wger/config/views/gym_config.py
@@ -34,18 +34,18 @@ logger = logging.getLogger(__name__)
class GymConfigUpdateView(WgerFormMixin, UpdateView):
- '''
+ """
Generic view to edit the gym config table
- '''
+ """
model = GymConfig
fields = '__all__'
permission_required = 'config.change_gymconfig'
success_url = reverse_lazy('gym:gym:list')
def get_object(self):
- '''
+ """
Return the only gym config object
- '''
+ """
return GymConfig.objects.get(pk=1)
def get_context_data(self, **kwargs):
diff --git a/wger/config/views/language_config.py b/wger/config/views/language_config.py
index f1082171e..079f16d3b 100644
--- a/wger/config/views/language_config.py
+++ b/wger/config/views/language_config.py
@@ -41,17 +41,17 @@ class LanguageConfigUpdateView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
UpdateView):
- '''
+ """
Generic view to edit a language config
- '''
+ """
model = LanguageConfig
fields = ['show']
permission_required = 'config.change_languageconfig'
def get_success_url(self):
- '''
+ """
Return to the language page
- '''
+ """
return reverse_lazy('core:language:view', kwargs={'pk': self.object.language_id})
def get_context_data(self, **kwargs):
diff --git a/wger/core/api/resources.py b/wger/core/api/resources.py
index 3553121f1..19e98b2ad 100644
--- a/wger/core/api/resources.py
+++ b/wger/core/api/resources.py
@@ -30,14 +30,14 @@ from wger.utils.resources import UserObjectsOnlyAuthorization
class UserProfileResource(ModelResource):
- '''
+ """
Resource for user profiles
- '''
+ """
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(user=bundle.request.user)
class Meta:
@@ -48,9 +48,9 @@ class UserProfileResource(ModelResource):
class LanguageResource(ModelResource):
- '''
+ """
Resource for languages
- '''
+ """
class Meta:
queryset = Language.objects.all()
filtering = {'id': ALL,
@@ -59,9 +59,9 @@ class LanguageResource(ModelResource):
class DaysOfWeekResource(ModelResource):
- '''
+ """
Resource for days of the week
- '''
+ """
class Meta:
queryset = DaysOfWeek.objects.all()
@@ -70,9 +70,9 @@ class DaysOfWeekResource(ModelResource):
class LicenseResource(ModelResource):
- '''
+ """
Resource for licenses
- '''
+ """
class Meta:
queryset = License.objects.all()
filtering = {'id': ALL,
diff --git a/wger/core/api/serializers.py b/wger/core/api/serializers.py
index 4a0585fc4..abb3bcbe9 100644
--- a/wger/core/api/serializers.py
+++ b/wger/core/api/serializers.py
@@ -30,61 +30,61 @@ from wger.core.models import (
class UserprofileSerializer(serializers.ModelSerializer):
- '''
+ """
Workout session serializer
- '''
+ """
class Meta:
model = UserProfile
fields = '__all__'
class UsernameSerializer(serializers.Serializer):
- '''
+ """
Serializer to extract the username
- '''
+ """
username = serializers.CharField()
class LanguageSerializer(serializers.ModelSerializer):
- '''
+ """
Language serializer
- '''
+ """
class Meta:
model = Language
fields = '__all__'
class DaysOfWeekSerializer(serializers.ModelSerializer):
- '''
+ """
DaysOfWeek serializer
- '''
+ """
class Meta:
model = DaysOfWeek
fields = '__all__'
class LicenseSerializer(serializers.ModelSerializer):
- '''
+ """
License serializer
- '''
+ """
class Meta:
model = License
fields = '__all__'
class RepetitionUnitSerializer(serializers.ModelSerializer):
- '''
+ """
Repetition unit serializer
- '''
+ """
class Meta:
model = RepetitionUnit
fields = '__all__'
class WeightUnitSerializer(serializers.ModelSerializer):
- '''
+ """
Weight unit serializer
- '''
+ """
class Meta:
model = WeightUnit
fields = '__all__'
diff --git a/wger/core/api/views.py b/wger/core/api/views.py
index 6e33346e0..067431d3a 100644
--- a/wger/core/api/views.py
+++ b/wger/core/api/views.py
@@ -48,40 +48,40 @@ from wger.utils.permissions import (
class UserProfileViewSet(viewsets.ModelViewSet):
- '''
+ """
API endpoint for workout objects
- '''
+ """
is_private = True
serializer_class = UserprofileSerializer
permission_classes = (WgerPermission, UpdateOnlyPermission)
ordering_fields = '__all__'
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return UserProfile.objects.filter(user=self.request.user)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(User, 'user')]
@action(detail=True)
def username(self, request, pk):
- '''
+ """
Return the username
- '''
+ """
user = self.get_object().user
return Response(UsernameSerializer(user).data)
class LanguageViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for workout objects
- '''
+ """
queryset = Language.objects.all()
serializer_class = LanguageSerializer
ordering_fields = '__all__'
@@ -90,9 +90,9 @@ class LanguageViewSet(viewsets.ReadOnlyModelViewSet):
class DaysOfWeekViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for workout objects
- '''
+ """
queryset = DaysOfWeek.objects.all()
serializer_class = DaysOfWeekSerializer
ordering_fields = '__all__'
@@ -100,9 +100,9 @@ class DaysOfWeekViewSet(viewsets.ReadOnlyModelViewSet):
class LicenseViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for workout objects
- '''
+ """
queryset = License.objects.all()
serializer_class = LicenseSerializer
ordering_fields = '__all__'
@@ -112,9 +112,9 @@ class LicenseViewSet(viewsets.ReadOnlyModelViewSet):
class RepetitionUnitViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for repetition units objects
- '''
+ """
queryset = RepetitionUnit.objects.all()
serializer_class = RepetitionUnitSerializer
ordering_fields = '__all__'
@@ -122,9 +122,9 @@ class RepetitionUnitViewSet(viewsets.ReadOnlyModelViewSet):
class WeightUnitViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for weight units objects
- '''
+ """
queryset = WeightUnit.objects.all()
serializer_class = WeightUnitSerializer
ordering_fields = '__all__'
diff --git a/wger/core/demo.py b/wger/core/demo.py
index 1aa29cee3..bb1e2babc 100644
--- a/wger/core/demo.py
+++ b/wger/core/demo.py
@@ -52,9 +52,9 @@ logger = logging.getLogger(__name__)
def create_temporary_user():
- '''
+ """
Creates a temporary user
- '''
+ """
username = uuid.uuid4().hex[:-2]
password = uuid.uuid4().hex[:-2]
email = ''
@@ -71,9 +71,9 @@ def create_temporary_user():
def create_demo_entries(user):
- '''
+ """
Creates some demo data for temporary users
- '''
+ """
# (this is a bit ugly and long...)
language = load_language()
diff --git a/wger/core/forms.py b/wger/core/forms.py
index 73c2ef4d7..2efd29451 100644
--- a/wger/core/forms.py
+++ b/wger/core/forms.py
@@ -39,11 +39,11 @@ from wger.core.models import UserProfile
class UserLoginForm(AuthenticationForm):
- '''
+ """
Form for logins
Overwritten here just to change the label on the 'username' field
- '''
+ """
username = forms.CharField(label=_("Username or email"), max_length=254)
@@ -75,14 +75,14 @@ class UserEmailForm(forms.ModelForm):
fields = ('email', )
def clean_email(self):
- '''
+ """
Email must be unique system wide
However, this check should only be performed when the user changes his
email, otherwise the uniqueness check will because it will find one user
(the current one) using the same email. Only when the user changes it, do
we want to check that nobody else has that email
- '''
+ """
email = self.cleaned_data["email"]
if not email:
@@ -109,12 +109,12 @@ class UserPersonalInformationForm(UserEmailForm):
class PasswordConfirmationForm(Form):
- '''
+ """
A simple password confirmation form.
This can be used to make sure the user really wants to perform a dangerous
action. The form must be initialised with a user object.
- '''
+ """
password = CharField(label=_("Password"),
widget=PasswordInput,
help_text=_('Please enter your current password.'))
@@ -124,9 +124,9 @@ class PasswordConfirmationForm(Form):
super(PasswordConfirmationForm, self).__init__(data=data)
def clean_password(self):
- '''
+ """
Check that the password supplied matches the one for the user
- '''
+ """
password = self.cleaned_data.get('password', None)
if not self.user.check_password(password):
raise ValidationError(_('Invalid password'))
@@ -134,9 +134,9 @@ class PasswordConfirmationForm(Form):
class RegistrationForm(UserCreationForm, UserEmailForm):
- '''
+ """
Registration form
- '''
+ """
# Manually set the language to 'en', otherwise the language used seems to
# randomly one of the application languages. This also appears to happen
@@ -147,20 +147,20 @@ class RegistrationForm(UserCreationForm, UserEmailForm):
class RegistrationFormNoCaptcha(UserCreationForm, UserEmailForm):
- '''
+ """
Registration form without captcha field
This is used when registering through an app, in that case there is not
such a spam danger and simplifies the registration process on a mobile
device.
- '''
+ """
pass
class FeedbackRegisteredForm(forms.Form):
- '''
+ """
Feedback form used for logged in users
- '''
+ """
contact = forms.CharField(max_length=50,
min_length=10,
label=_('Contact'),
@@ -176,8 +176,8 @@ class FeedbackRegisteredForm(forms.Form):
class FeedbackAnonymousForm(FeedbackRegisteredForm):
- '''
+ """
Feedback form used for anonymous users (has additionally a reCaptcha field)
- '''
+ """
captcha = ReCaptchaField(label=_('Confirmation text'),
help_text=_('As a security measure, please enter the previous words'),)
diff --git a/wger/core/management/commands/clear-cache.py b/wger/core/management/commands/clear-cache.py
index c88316bf3..209a804e2 100644
--- a/wger/core/management/commands/clear-cache.py
+++ b/wger/core/management/commands/clear-cache.py
@@ -36,9 +36,9 @@ from wger.utils.cache import (
class Command(BaseCommand):
- '''
+ """
Clears caches (HTML, etc.)
- '''
+ """
help = 'Clears the application cache. You *must* pass an option selecting ' \
'what exactly you want to clear. See available options.'
@@ -64,9 +64,9 @@ class Command(BaseCommand):
help='Clear ALL cached entries')
def handle(self, **options):
- '''
+ """
Process the options
- '''
+ """
if (not options['clear_template']
and not options['clear_workout']
diff --git a/wger/core/management/commands/delete-temp-users.py b/wger/core/management/commands/delete-temp-users.py
index a957bf522..e8bd740f8 100644
--- a/wger/core/management/commands/delete-temp-users.py
+++ b/wger/core/management/commands/delete-temp-users.py
@@ -26,9 +26,9 @@ from wger.core.models import UserProfile
class Command(BaseCommand):
- '''
+ """
Helper admin command to clean up demo users, to be called e.g. by cron
- '''
+ """
help = 'Deletes all temporary users older than 1 week'
diff --git a/wger/core/management/commands/extract-i18n.py b/wger/core/management/commands/extract-i18n.py
index c1adc5cf6..684d38588 100644
--- a/wger/core/management/commands/extract-i18n.py
+++ b/wger/core/management/commands/extract-i18n.py
@@ -27,9 +27,9 @@ from wger.exercises.models import (
class Command(BaseCommand):
- '''
+ """
Helper command to read out the strings to manually include in the .po files
- '''
+ """
help = 'Read out all strings that have to be included manually in the .po file'
diff --git a/wger/core/management/commands/update-user-cache.py b/wger/core/management/commands/update-user-cache.py
index 7d680f329..822d448fd 100644
--- a/wger/core/management/commands/update-user-cache.py
+++ b/wger/core/management/commands/update-user-cache.py
@@ -23,18 +23,18 @@ from wger.gym.helpers import get_user_last_activity
class Command(BaseCommand):
- '''
+ """
Updates the user cache table
- '''
+ """
help = 'Update the user cache-table. This is only needed when the python' \
'code used to calculate any of the cached entries is changed and ' \
'the ones in the database need to be updated to reflect the new logic.'
def handle(self, **options):
- '''
+ """
Process the options
- '''
+ """
print('** Updating last activity')
for user in User.objects.all():
diff --git a/wger/core/migrations/0006_auto_20151025_2237.py b/wger/core/migrations/0006_auto_20151025_2237.py
index fbabd1c8c..0f33852f7 100644
--- a/wger/core/migrations/0006_auto_20151025_2237.py
+++ b/wger/core/migrations/0006_auto_20151025_2237.py
@@ -5,9 +5,9 @@ from django.db import migrations, models
def create_usercache(apps, schema_editor):
- '''
+ """
Creates a usercache table for all users
- '''
+ """
User = apps.get_model("auth", "User")
Usercache = apps.get_model("core", "Usercache")
WorkoutLog = apps.get_model("manager", "WorkoutLog")
@@ -44,9 +44,9 @@ def create_usercache(apps, schema_editor):
def delete_usercache(apps, schema_editor):
- '''
+ """
Deletes the usercache table for all users
- '''
+ """
Usercache = apps.get_model("core", "Usercache")
for cache in Usercache.objects.all():
cache.delete()
diff --git a/wger/core/migrations/0009_auto_20160303_2340.py b/wger/core/migrations/0009_auto_20160303_2340.py
index 6fb4207a9..003028f4a 100644
--- a/wger/core/migrations/0009_auto_20160303_2340.py
+++ b/wger/core/migrations/0009_auto_20160303_2340.py
@@ -5,12 +5,12 @@ from django.db import migrations, models
def insert_data(apps, schema_editor):
- '''
+ """
Inserts initial data for repetition and weight units
Needed so that the migrations can go through without having to load any
fixtures or perform any intermediate steps.
- '''
+ """
WeightUnit = apps.get_model('core', 'WeightUnit')
WeightUnit(name='kg', pk=1).save()
WeightUnit(name='lb', pk=2).save()
diff --git a/wger/core/models.py b/wger/core/models.py
index 0298003dc..ee7298a8d 100644
--- a/wger/core/models.py
+++ b/wger/core/models.py
@@ -38,9 +38,9 @@ from wger.weight.models import WeightEntry
class Language(models.Model):
- '''
+ """
Language of an item (exercise, workout, etc.)
- '''
+ """
# e.g. 'de'
short_name = models.CharField(max_length=2,
@@ -51,41 +51,41 @@ class Language(models.Model):
verbose_name=_('Language full name'))
class Meta:
- '''
+ """
Set Meta options
- '''
+ """
ordering = ["full_name", ]
#
# Django methods
#
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{0} ({1})".format(self.full_name, self.short_name)
def get_absolute_url(self):
- '''
+ """
Returns the canonical URL to view a language
- '''
+ """
return reverse('core:language:view', kwargs={'pk': self.id})
#
# Own methods
#
def get_owner_object(self):
- '''
+ """
Muscle has no owner information
- '''
+ """
return False
def birthdate_validator(birthdate):
- '''
+ """
Checks to see if entered birthdate (datetime.date object) is
between 10 and 100 years of age.
- '''
+ """
max_year = birthdate.replace(year=(birthdate.year + 100))
min_year = birthdate.replace(year=(birthdate.year + 10))
today = datetime.date.today()
@@ -123,24 +123,24 @@ class UserProfile(models.Model):
user = models.OneToOneField(User,
editable=False,
on_delete=models.CASCADE)
- '''
+ """
The user
- '''
+ """
gym = models.ForeignKey(Gym,
editable=False,
null=True,
blank=True,
on_delete=models.SET_NULL)
- '''
+ """
The gym this user belongs to, if any
- '''
+ """
is_temporary = models.BooleanField(default=False,
editable=False)
- '''
+ """
Flag to mark a temporary user (demo account)
- '''
+ """
#
# User preferences
@@ -150,18 +150,18 @@ class UserProfile(models.Model):
help_text=_('Check to show exercise comments on the '
'workout view'),
default=True)
- '''
+ """
Show exercise comments on workout view
- '''
+ """
# Also show ingredients in english while composing a nutritional plan
# (obviously this is only meaningful if the user has a language other than english)
show_english_ingredients = models.BooleanField(
verbose_name=_('Also use ingredients in English'),
- help_text=_('''Check to also show ingredients in English while creating
+ 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
-7000 entries, but can be somewhat overwhelming and make the search difficult.'''),
+7000 entries, but can be somewhat overwhelming and make the search difficult."""),
default=True)
workout_reminder_active = models.BooleanField(verbose_name=_('Activate workout reminders'),
@@ -185,12 +185,12 @@ by the US Department of Agriculture. It is extremely complete, with around
last_workout_notification = models.DateField(editable=False,
blank=False,
null=True)
- '''
+ """
The last time the user got a workout reminder email
This is needed e.g. to check daily per cron for old workouts but only
send users an email once per week
- '''
+ """
notification_language = models.ForeignKey(Language,
verbose_name=_('Notification language'),
@@ -205,18 +205,18 @@ by the US Department of Agriculture. It is extremely complete, with around
help_text=_('Check to activate timer pauses between '
'exercises.'),
default=True)
- '''
+ """
Switch to activate pauses in the gym view
- '''
+ """
timer_pause = IntegerField(verbose_name=_('Default duration of workout pauses'),
help_text=_('Default duration in seconds of pauses used by '
'the timer in the gym mode.'),
default=90,
validators=[MinValueValidator(10), MaxValueValidator(400)])
- '''
+ """
Default duration of workout pauses in the gym view
- '''
+ """
#
# User statistics
@@ -225,27 +225,27 @@ by the US Department of Agriculture. It is extremely complete, with around
blank=False,
null=True,
validators=[MinValueValidator(10), MaxValueValidator(100)])
- '''The user's age'''
+ """The user's age"""
birthdate = models.DateField(verbose_name=('Date of Birth'),
blank=False,
null=True,
validators=[birthdate_validator])
- '''The user's date of birth'''
+ """The user's date of birth"""
height = IntegerField(verbose_name=_('Height (cm)'),
blank=False,
validators=[MinValueValidator(140), MaxValueValidator(230)],
null=True)
- '''The user's height'''
+ """The user's height"""
gender = models.CharField(max_length=1,
choices=GENDER,
default=GENDER_MALE,
blank=False,
null=True)
- '''Gender'''
+ """Gender"""
sleep_hours = IntegerField(verbose_name=_('Hours of sleep'),
help_text=_('The average hours of sleep per day'),
@@ -253,7 +253,7 @@ by the US Department of Agriculture. It is extremely complete, with around
blank=False,
null=True,
validators=[MinValueValidator(4), MaxValueValidator(10)])
- '''The average hours of sleep per day'''
+ """The average hours of sleep per day"""
work_hours = IntegerField(verbose_name=_('Work'),
help_text=_('Average hours per day'),
@@ -261,7 +261,7 @@ by the US Department of Agriculture. It is extremely complete, with around
blank=False,
null=True,
validators=[MinValueValidator(1), MaxValueValidator(15)])
- '''The average hours at work per day'''
+ """The average hours at work per day"""
work_intensity = models.CharField(verbose_name=_('Physical intensity'),
help_text=_('Approximately'),
@@ -270,7 +270,7 @@ by the US Department of Agriculture. It is extremely complete, with around
default=INTENSITY_LOW,
blank=False,
null=True)
- '''Physical intensity of work'''
+ """Physical intensity of work"""
sport_hours = IntegerField(verbose_name=_('Sport'),
help_text=_('Average hours per week'),
@@ -278,7 +278,7 @@ by the US Department of Agriculture. It is extremely complete, with around
blank=False,
null=True,
validators=[MinValueValidator(1), MaxValueValidator(30)])
- '''The average hours performing sports per week'''
+ """The average hours performing sports per week"""
sport_intensity = models.CharField(verbose_name=_('Physical intensity'),
help_text=_('Approximately'),
@@ -287,7 +287,7 @@ by the US Department of Agriculture. It is extremely complete, with around
default=INTENSITY_MEDIUM,
blank=False,
null=True)
- '''Physical intensity of sport activities'''
+ """Physical intensity of sport activities"""
freetime_hours = IntegerField(verbose_name=_('Free time'),
help_text=_('Average hours per day'),
@@ -295,7 +295,7 @@ by the US Department of Agriculture. It is extremely complete, with around
blank=False,
null=True,
validators=[MinValueValidator(1), MaxValueValidator(15)])
- '''The average hours of free time per day'''
+ """The average hours of free time per day"""
freetime_intensity = models.CharField(verbose_name=_('Physical intensity'),
help_text=_('Approximately'),
@@ -304,7 +304,7 @@ by the US Department of Agriculture. It is extremely complete, with around
default=INTENSITY_LOW,
blank=False,
null=True)
- '''Physical intensity during free time'''
+ """Physical intensity during free time"""
calories = IntegerField(verbose_name=_('Total daily calories'),
help_text=_('Total caloric intake, including e.g. any surplus'),
@@ -312,7 +312,7 @@ by the US Department of Agriculture. It is extremely complete, with around
blank=False,
null=True,
validators=[MinValueValidator(1500), MaxValueValidator(5000)])
- '''Basic caloric intake based on physical activity'''
+ """Basic caloric intake based on physical activity"""
#
# Others
@@ -321,14 +321,14 @@ by the US Department of Agriculture. It is extremely complete, with around
max_length=2,
choices=UNITS,
default=UNITS_KG)
- '''Preferred weight unit'''
+ """Preferred weight unit"""
ro_access = models.BooleanField(verbose_name=_('Allow external access'),
help_text=_('Allow external users to access your workouts and '
'logs in a read-only mode. You need to set this '
'before you can share links e.g. to social media.'),
default=False)
- '''Allow anonymous read-only access'''
+ """Allow anonymous read-only access"""
num_days_weight_reminder = models.IntegerField(verbose_name=_('Automatic reminders for weight '
'entries'),
@@ -338,14 +338,14 @@ by the US Department of Agriculture. It is extremely complete, with around
validators=[MinValueValidator(0),
MaxValueValidator(30)],
default=0)
- '''Number of Days for email weight reminder'''
+ """Number of Days for email weight reminder"""
@property
def weight(self):
- '''
+ """
Returns the last weight entry, done here to make the behaviour
more consistent with the other settings (age, height, etc.)
- '''
+ """
try:
weight = WeightEntry.objects.filter(user=self.user).latest().weight
except WeightEntry.DoesNotExist:
@@ -354,9 +354,9 @@ by the US Department of Agriculture. It is extremely complete, with around
@property
def address(self):
- '''
+ """
Return the address as saved in the current contract (user's gym)
- '''
+ """
out = {'zip_code': '',
'city': '',
'street': '',
@@ -371,35 +371,35 @@ by the US Department of Agriculture. It is extremely complete, with around
return out
def clean(self):
- '''
+ """
Make sure the total amount of hours is 24
- '''
+ """
if ((self.sleep_hours and self.freetime_hours and self.work_hours)
and (self.sleep_hours + self.freetime_hours + self.work_hours) > 24):
raise ValidationError(_('The sum of all hours has to be 24'))
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"Profile for user {0}".format(self.user)
@property
def use_metric(self):
- '''
+ """
Simple helper that checks whether the user uses metric units or not
:return: Boolean
- '''
+ """
return self.weight_unit == 'kg'
def calculate_bmi(self):
- '''
+ """
Calculates the user's BMI
Formula: weight/height^2
- weight in kg
- height in m
- '''
+ """
# If not all the data is available, return 0, otherwise the result
# of the calculation below breaks django's template filters
@@ -411,11 +411,11 @@ by the US Department of Agriculture. It is extremely complete, with around
self.height / decimal.Decimal(100.0))
def calculate_basal_metabolic_rate(self, formula=1):
- '''
+ """
Calculates the basal metabolic rate.
Currently only the Mifflin-St.Jeor formula is supported
- '''
+ """
factor = 5 if self.gender == self.GENDER_MALE else -161
weight = self.weight if self.use_metric else AbstractWeight(self.weight, 'lb').kg
@@ -431,13 +431,13 @@ by the US Department of Agriculture. It is extremely complete, with around
return decimal.Decimal(str(rate)).quantize(TWOPLACES)
def calculate_activities(self):
- '''
+ """
Calculates the calories needed by additional physical activities
Factors taken from
* https://en.wikipedia.org/wiki/Physical_activity_level
* http://www.fao.org/docrep/007/y5686e/y5686e07.htm
- '''
+ """
# Sleep
sleep = self.sleep_hours * 0.95
@@ -473,9 +473,9 @@ by the US Department of Agriculture. It is extremely complete, with around
return decimal.Decimal(str(total)).quantize(TWOPLACES)
def user_bodyweight(self, weight):
- '''
+ """
Create a new weight entry as needed
- '''
+ """
if (not WeightEntry.objects.filter(user=self.user).exists()
or (datetime.date.today()
- WeightEntry.objects.filter(user=self.user).latest().date
@@ -494,178 +494,178 @@ by the US Department of Agriculture. It is extremely complete, with around
return entry
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self
class UserCache(models.Model):
- '''
+ """
A table used to cache expensive queries or similar
- '''
+ """
user = models.OneToOneField(User, editable=False, on_delete=models.CASCADE)
- '''
+ """
The user
- '''
+ """
last_activity = models.DateField(null=True)
- '''
+ """
The user's last activity.
Values for this entry are saved by signals as calculated by the
get_user_last_activity helper function.
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"Cache for user {0}".format(self.user)
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'))
class Meta:
- '''
+ """
Order by day-ID, this is needed for some DBs
- '''
+ """
ordering = ["pk", ]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.day_of_week
class License(models.Model):
- '''
+ """
License for an item (exercise, ingredient, etc.)
- '''
+ """
full_name = models.CharField(max_length=60,
verbose_name=_('Full name'),
help_text=_('If a license has been localized, e.g. the Creative '
'Commons licenses for the different countries, add '
'them as separate entries here.'))
- '''Full name'''
+ """Full name"""
short_name = models.CharField(max_length=15,
verbose_name=_('Short name, e.g. CC-BY-SA 3'))
- '''Short name, e.g. CC-BY-SA 3'''
+ """Short name, e.g. CC-BY-SA 3"""
url = models.URLField(verbose_name=_('Link'),
help_text=_('Link to license text or other information'),
blank=True,
null=True)
- '''URL to full license text or other information'''
+ """URL to full license text or other information"""
class Meta:
- '''
+ """
Set Meta options
- '''
+ """
ordering = ["full_name", ]
#
# Django methods
#
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{0} ({1})".format(self.full_name, self.short_name)
#
# Own methods
#
def get_owner_object(self):
- '''
+ """
License has no owner information
- '''
+ """
return None
class RepetitionUnit(models.Model):
- '''
+ """
Setting unit, used in combination with an amount such as '10 reps', '5 km'
- '''
+ """
class Meta:
- '''
+ """
Set Meta options
- '''
+ """
ordering = ["name", ]
name = models.CharField(max_length=100,
verbose_name=_('Name'))
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
#
# Own methods
#
def get_owner_object(self):
- '''
+ """
Unit has no owner information
- '''
+ """
return None
@property
def is_repetition(self):
- '''
+ """
Checks that the repetition unit is a repetition proper
This is done basically to not litter the code with magic IDs
- '''
+ """
return self.id == 1
class WeightUnit(models.Model):
- '''
+ """
Weight unit, used in combination with an amount such as '10 kg', '5 plates'
- '''
+ """
class Meta:
- '''
+ """
Set Meta options
- '''
+ """
ordering = ["name", ]
name = models.CharField(max_length=100,
verbose_name=_('Name'))
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
#
# Own methods
#
def get_owner_object(self):
- '''
+ """
Unit has no owner information
- '''
+ """
return None
@property
def is_weight(self):
- '''
+ """
Checks that the unit is a weight proper
This is done basically to not litter the code with magic IDs
- '''
+ """
return self.id in (1, 2)
diff --git a/wger/core/signals.py b/wger/core/signals.py
index 6031bf35b..7f8ad15ae 100644
--- a/wger/core/signals.py
+++ b/wger/core/signals.py
@@ -36,28 +36,28 @@ from wger.utils.helpers import disable_for_loaddata
@disable_for_loaddata
def create_user_profile(sender, instance, created, **kwargs):
- '''
+ """
Every new user gets a profile
- '''
+ """
if created:
UserProfile.objects.create(user=instance)
@disable_for_loaddata
def create_user_cache(sender, instance, created, **kwargs):
- '''
+ """
Every new user gets a cache table
- '''
+ """
if created:
UserCache.objects.create(user=instance)
@receiver(pre_save, sender=UserProfile)
def set_user_age(sender, instance, **kwargs):
- '''
+ """
Inputting or changing a user's birthdate will auto-update the
user's age as well if user's age has not been set
- '''
+ """
if instance.age is None and instance.birthdate is not None:
today = datetime.date.today()
birthday = instance.birthdate
diff --git a/wger/core/templatetags/wger_extras.py b/wger/core/templatetags/wger_extras.py
index 0d26daba6..723a5d209 100644
--- a/wger/core/templatetags/wger_extras.py
+++ b/wger/core/templatetags/wger_extras.py
@@ -43,21 +43,21 @@ register = template.Library()
@register.filter(name='get_current_settings')
def get_current_settings(exercise, set_id):
- '''
+ """
Does a filter on the sets
We need to do this here because it's not possible to pass arguments to function in
the template, and we are only interested on the settings that belong to the current
set
- '''
+ """
return exercise.setting_set.filter(set_id=set_id)
@register.inclusion_tag('tags/render_day.html')
def render_day(day, editable=True):
- '''
+ """
Renders a day as it will be displayed in the workout overview
- '''
+ """
return {'day': day.canonical_representation,
'workout': day.training,
'editable': editable}
@@ -65,9 +65,9 @@ def render_day(day, editable=True):
@register.inclusion_tag('tags/pagination.html')
def pagination(paginator, page):
- '''
+ """
Renders the necessary links to paginating a long list
- '''
+ """
# For very long lists (e.g. the English ingredient with more than 8000 items)
# we muck around here to remove the pages not inmediately 'around' the current
@@ -97,9 +97,9 @@ def pagination(paginator, page):
@register.inclusion_tag('tags/render_weight_log.html')
def render_weight_log(log, div_uuid, user=None):
- '''
+ """
Renders a weight log series
- '''
+ """
return {'log': log,
'div_uuid': div_uuid,
@@ -108,9 +108,9 @@ def render_weight_log(log, div_uuid, user=None):
@register.inclusion_tag('tags/license-sidebar.html')
def license_sidebar(license, author=None):
- '''
+ """
Renders the license notice for exercises
- '''
+ """
return {'license': license,
'author': author}
@@ -118,9 +118,9 @@ def license_sidebar(license, author=None):
@register.inclusion_tag('tags/language_select.html', takes_context=True)
def language_select(context, language):
- '''
+ """
Renders a link to change the current language.
- '''
+ """
return {'language_name': language[1],
'path': 'images/icons/flag-{0}.svg'.format(language[0]),
@@ -129,35 +129,35 @@ def language_select(context, language):
@register.filter
def get_item(dictionary, key):
- '''
+ """
Allows to access a specific key in a dictionary in a template
- '''
+ """
return dictionary.get(key)
@register.simple_tag
def auto_link_css(mobile=False, css=''):
- '''
+ """
Adds the appropriate classes to a sidebar link depending on the site version
:param mobile: true if mobile version of site
:param css: the CSS class, if any, of the link
:return: the complete CSS classes, wrapped in class="foo"
- '''
+ """
css = css + ' btn btn-default btn-block' if mobile else css
return mark_safe('class="{0}"'.format(css))
@register.simple_tag
def fa_class(class_name='', size='', fixed_width=True):
- '''
+ """
Helper function to help add font awesome classes to elements
:param class_name: the CSS class name, without the "fa-" prefix
:param size: the size of the icon
:param fixed_width: toggle for fixed icon width
:return: the complete CSS classes
- '''
+ """
css = ''
if not class_name:
return css
@@ -173,14 +173,14 @@ def fa_class(class_name='', size='', fixed_width=True):
@register.simple_tag
def trans_weight_unit(unit, user=None):
- '''
+ """
Returns the correct (translated) weight unit
:param unit: the weight unit. Allowed values are 'kg' and 'g'
:param user: the user object, needed to access the profile. If this evaluates
to False, metric is used
:return: translated unit
- '''
+ """
if not user or user.userprofile.use_metric:
if unit == 'kg':
return _('kg')
@@ -195,9 +195,9 @@ def trans_weight_unit(unit, user=None):
@register.filter
def format_username(user):
- '''
+ """
Formats the username according to the information available
- '''
+ """
if user.get_full_name():
return user.get_full_name()
elif user.email:
@@ -220,10 +220,10 @@ class SpacelessNode(template.base.Node):
@register.tag
def spaceless_config(parser, token):
- '''
+ """
This is django's spaceless tag, copied here to use our configurable
SpacelessNode
- '''
+ """
nodelist = parser.parse(('endspaceless_config',))
parser.delete_first_token()
return SpacelessNode(nodelist)
@@ -234,56 +234,56 @@ def spaceless_config(parser, token):
#
@register.filter(name='form_field_add_css')
def form_field_add_css(field, css):
- '''
+ """
Adds a CSS class to a form field. This is needed among other places for
bootstrap 3, which needs a 'form-control' class in the field itself
- '''
+ """
return field.as_widget(attrs={"class": css})
@register.filter(name='is_checkbox')
def is_checkbox(field):
- '''
+ """
Tests if a field element is a checkbox, as it needs to be handled slightly different
:param field: a form field
:return: boolen
- '''
+ """
return isinstance(field.field.widget, CheckboxInput)
@register.filter(name='is_multiple')
def is_multiple(field):
- '''
+ """
Tests if a field element is a multiple select rendered as a checkbox, as it
needs to be handled slightly different
:param field: a form field
:return: boolen
- '''
+ """
return isinstance(field.field.widget, BootstrapSelectMultiple) \
or isinstance(field.field.widget, BootstrapSelectMultipleTranslatedOriginal)
@register.filter(name='is_fileupload')
def is_fileupload(field):
- '''
+ """
Tests if a field element is a file upload, as it needs to be handled slightly different
:param field: a form field
:return: boolen
- '''
+ """
return isinstance(field.field.widget, ClearableFileInput)
@register.inclusion_tag('tags/render_form_element.html')
def render_form_field(field):
- '''
+ """
Renders a form field with all necessary labels, help texts and labels
within 'form-group'.
See bootstrap documentation for details: http://getbootstrap.com/css/#forms
- '''
+ """
return {'field': field}
@@ -326,7 +326,7 @@ def render_form_errors(form):
@register.inclusion_tag('tags/render_form_fields.html')
def render_form_fields(form, submit_text='Save', show_save=True):
- '''
+ """
Comfort function that renders all fields in a form, as well as the submit
button
@@ -340,7 +340,7 @@ def render_form_fields(form, submit_text='Save', show_save=True):
:param form: the form to be rendered
:param save_text: the text to use on the submit button
- '''
+ """
return {'form': form,
'show_save': show_save,
diff --git a/wger/core/tests/api_base_test.py b/wger/core/tests/api_base_test.py
index 47d75eb15..db0cc71c4 100644
--- a/wger/core/tests/api_base_test.py
+++ b/wger/core/tests/api_base_test.py
@@ -26,72 +26,72 @@ from wger.core.tests.base_testcase import BaseTestCase
class ApiBaseTestCase(APITestCase):
api_version = 'v2'
- '''
+ """
The current API version to test
- '''
+ """
resource = None
- '''
+ """
The current resource to be tested (Model class)
- '''
+ """
pk = None
- '''
+ """
The pk of the detail view to test
- '''
+ """
private_resource = True
- '''
+ """
A flag indicating whether the resource can be updated (POST, PATCH)
by the owning user (workout, etc.)
- '''
+ """
user_access = 'test'
- '''
+ """
Owner user authorized to change the data (workout, etc.)
- '''
+ """
user_fail = 'admin'
- '''
+ """
A different user
- '''
+ """
data = {}
- '''
+ """
Dictionary with the data used for testing
- '''
+ """
special_endpoints = ()
- '''
+ """
A list of special endpoints to check, e.g. the canonical representation of
a workout.
- '''
+ """
def get_resource_name(self):
- '''
+ """
Returns the name of the resource. The default is the name of the model
class used in lower letters
- '''
+ """
return self.resource.__name__.lower()
@property
def url(self):
- '''
+ """
Return the URL to use for testing
- '''
+ """
return '/api/{0}/{1}/'.format(self.api_version, self.get_resource_name())
@property
def url_detail(self):
- '''
+ """
Return the detail URL to use for testing
- '''
+ """
return '{0}{1}/'.format(self.url, self.pk)
def get_credentials(self, username=None):
- '''
+ """
Authenticates a user
- '''
+ """
if not username:
username = self.user_access
user_obj = User.objects.get(username=username)
@@ -100,22 +100,22 @@ class ApiBaseTestCase(APITestCase):
class ApiGetTestCase(object):
- '''
+ """
Base test case for testing GET access to the API
- '''
+ """
def test_ordering(self):
- '''
+ """
Test that ordering the resource works
- '''
+ """
pass
# TODO: implement this
def test_get_detail(self):
- '''
+ """
Tests accessing the detail view of a resource
- '''
+ """
if self.private_resource:
response = self.client.get(self.url_detail)
@@ -136,9 +136,9 @@ class ApiGetTestCase(object):
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_overview(self):
- '''
+ """
Test accessing the overview view of a resource
- '''
+ """
if self.private_resource:
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
@@ -153,9 +153,9 @@ class ApiGetTestCase(object):
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_special_endpoints(self):
- '''
+ """
Test accessing any special endpoint the resource could have
- '''
+ """
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
@@ -174,14 +174,14 @@ class ApiGetTestCase(object):
class ApiPostTestCase(object):
- '''
+ """
Base test case for testing POST access to the API
- '''
+ """
def test_post_detail(self):
- '''
+ """
POSTing to a detail view is not allowed
- '''
+ """
if self.private_resource:
# Anonymous user
@@ -213,9 +213,9 @@ class ApiPostTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_post(self):
- '''
+ """
Tests POSTing (adding) a new object
- '''
+ """
if self.private_resource:
# Anonymous user
@@ -252,9 +252,9 @@ class ApiPostTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_post_special_endpoints(self):
- '''
+ """
Tests that it's not possible to POST to the special endpoints
- '''
+ """
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
@@ -276,14 +276,14 @@ class ApiPostTestCase(object):
class ApiPatchTestCase(object):
- '''
+ """
Base test case for testing PATCH access to the API
- '''
+ """
def test_patch_detail(self):
- '''
+ """
Test PATCHING a detail view
- '''
+ """
if self.private_resource:
# Anonymous user
@@ -321,9 +321,9 @@ class ApiPatchTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_patch(self):
- '''
+ """
PATCHING to the overview is not allowed
- '''
+ """
if self.private_resource:
# Anonymous user
@@ -345,9 +345,9 @@ class ApiPatchTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_patch_special_endpoints(self):
- '''
+ """
Tests that it's not possible to patch to the special endpoints
- '''
+ """
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
@@ -369,14 +369,14 @@ class ApiPatchTestCase(object):
class ApiPutTestCase(object):
- '''
+ """
Base test case for testing PUT access to the API
- '''
+ """
def test_put_detail(self):
- '''
+ """
PUTing to a detail view is allowed
- '''
+ """
if self.private_resource:
# Anonymous user
@@ -426,9 +426,9 @@ class ApiPutTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_put(self):
- '''
+ """
Tests PUTTING (adding) a new object
- '''
+ """
if self.private_resource:
# Anonymous user
@@ -451,9 +451,9 @@ class ApiPutTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_put_special_endpoints(self):
- '''
+ """
Tests that it's not possible to PUT to the special endpoints
- '''
+ """
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
@@ -475,14 +475,14 @@ class ApiPutTestCase(object):
class ApiDeleteTestCase(object):
- '''
+ """
Base test case for testing DELETE access to the API
- '''
+ """
def test_delete_detail(self):
- '''
+ """
Tests DELETEing an object
- '''
+ """
if self.private_resource:
# Anonymous user
count_before = self.resource.objects.all().count()
@@ -520,9 +520,9 @@ class ApiDeleteTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_delete(self):
- '''
+ """
DELETEing to the overview is not allowed
- '''
+ """
if self.private_resource:
# Anonymous user
response = self.client.delete(self.url)
@@ -553,9 +553,9 @@ class ApiDeleteTestCase(object):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_delete_special_endpoints(self):
- '''
+ """
Tests that it's not possible to delete to the special endpoints
- '''
+ """
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
@@ -584,9 +584,9 @@ class ApiBaseResourceTestCase(BaseTestCase,
ApiDeleteTestCase,
ApiPutTestCase,
ApiPatchTestCase):
- '''
+ """
Base test case for the REST API
All logic happens in the Api*TestCase classes
- '''
+ """
pass
diff --git a/wger/core/tests/base_testcase.py b/wger/core/tests/base_testcase.py
index ac8d9157d..55728366b 100644
--- a/wger/core/tests/base_testcase.py
+++ b/wger/core/tests/base_testcase.py
@@ -37,9 +37,9 @@ STATUS_CODES_FAIL = (302, 403, 404)
def get_reverse(url, kwargs={}):
- '''
+ """
Helper function to get the reverse URL
- '''
+ """
try:
url = reverse(url, kwargs=kwargs)
except NoReverseMatch:
@@ -51,9 +51,9 @@ def get_reverse(url, kwargs={}):
def get_user_list(users):
- '''
+ """
Helper function that returns a list with users to test
- '''
+ """
if isinstance(users, tuple):
return users
else:
@@ -61,7 +61,7 @@ def get_user_list(users):
def delete_testcase_add_methods(cls):
- '''
+ """
Helper function that dynamically adds test methods.
This is a bit of a hack, but it's the easiest way of making sure that
@@ -69,7 +69,7 @@ def delete_testcase_add_methods(cls):
most importantly for us, that the database is reseted every time).
This must be called if the testcase has more than one success user
- '''
+ """
for user in get_user_list(cls.user_fail):
def test_unauthorized(self):
@@ -85,12 +85,12 @@ def delete_testcase_add_methods(cls):
class BaseTestCase(object):
- '''
+ """
Base test case.
Generic base testcase that is used for both the regular tests and the
REST API tests
- '''
+ """
fixtures = ('days_of_week',
'gym_config',
@@ -123,9 +123,9 @@ class BaseTestCase(object):
is_mobile = False
def setUp(self):
- '''
+ """
Overwrite some of Django's settings here
- '''
+ """
# Don't check reCaptcha's entries
os.environ['RECAPTCHA_TESTING'] = 'True'
@@ -149,9 +149,9 @@ class BaseTestCase(object):
settings.MEDIA_ROOT = self.media_root
def tearDown(self):
- '''
+ """
Reset settings
- '''
+ """
del os.environ['RECAPTCHA_TESTING']
cache.clear()
@@ -160,35 +160,35 @@ class BaseTestCase(object):
class WorkoutManagerTestCase(BaseTestCase, TestCase):
- '''
+ """
Testcase to use with the regular website
- '''
+ """
user_success = 'admin'
- '''
+ """
A list of users to test for success. For convenience, a string can be used
as well if there is only one user.
- '''
+ """
user_fail = 'test'
- '''
+ """
A list of users to test for failure. For convenience, a string can be used
as well if there is only one user.
- '''
+ """
def user_login(self, user='admin'):
- '''
+ """
Login the user, by default as 'admin'
- '''
+ """
password = '{0}{0}'.format(user)
self.client.login(username=user, password=password)
self.current_user = user
self.current_password = password
def user_logout(self):
- '''
+ """
Visit the logout page
- '''
+ """
self.client.logout()
self.current_user = 'anonymous'
@@ -222,28 +222,28 @@ class WorkoutManagerTestCase(BaseTestCase, TestCase):
self.assertEqual(field.id, value)
def post_test_hook(self):
- '''
+ """
Hook to add some more specific tests after the basic add or delete
operations are finished
- '''
+ """
pass
class WorkoutManagerDeleteTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests deleting an object an authorized user, a different one and a logged out
one. This assumes the delete action is only triggered with a POST request and
GET will only show a confirmation dialog.
- '''
+ """
pk = None
url = ''
object_class = ''
def delete_object(self, fail=False):
- '''
+ """
Helper function to test deleting a workout
- '''
+ """
# Only perform the checks on derived classes
if self.__class__.__name__ == 'WorkoutManagerDeleteTestCase':
@@ -283,23 +283,23 @@ class WorkoutManagerDeleteTestCase(WorkoutManagerTestCase):
self.post_test_hook()
def test_delete_object_anonymous(self):
- '''
+ """
Tests deleting the object as an anonymous user
- '''
+ """
self.delete_object(fail=True)
def test_delete_object_authorized(self):
- '''
+ """
Tests deleting the object as the authorized user
- '''
+ """
if not isinstance(self.user_success, tuple):
self.user_login(self.user_success)
self.delete_object(fail=False)
def test_delete_object_other(self):
- '''
+ """
Tests deleting the object as the unauthorized, logged in users
- '''
+ """
if self.user_fail and not isinstance(self.user_success, tuple):
for user in get_user_list(self.user_fail):
self.user_login(user)
@@ -307,10 +307,10 @@ class WorkoutManagerDeleteTestCase(WorkoutManagerTestCase):
class WorkoutManagerEditTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests editing an object as an authorized user, a different one and a logged out
one.
- '''
+ """
object_class = ''
url = ''
@@ -318,17 +318,17 @@ class WorkoutManagerEditTestCase(WorkoutManagerTestCase):
data = {}
data_ignore = ()
fileupload = None
- '''
+ """
If the form requires a file upload, specify the field name and the file path
here in a list or tuple:
['fielname', 'path']
- '''
+ """
def edit_object(self, fail=False):
- '''
+ """
Helper function to test editing an object
- '''
+ """
# Only perform the checks on derived classes
if self.__class__.__name__ == 'WorkoutManagerEditTestCase':
@@ -381,23 +381,23 @@ class WorkoutManagerEditTestCase(WorkoutManagerTestCase):
self.post_test_hook()
def test_edit_object_anonymous(self):
- '''
+ """
Tests editing the object as an anonymous user
- '''
+ """
self.edit_object(fail=True)
def test_edit_object_authorized(self):
- '''
+ """
Tests editing the object as the authorized users
- '''
+ """
for user in get_user_list(self.user_success):
self.user_login(user)
self.edit_object(fail=False)
def test_edit_object_other(self):
- '''
+ """
Tests editing the object as the unauthorized, logged in users
- '''
+ """
if self.user_fail:
for user in get_user_list(self.user_fail):
self.user_login(user)
@@ -405,10 +405,10 @@ class WorkoutManagerEditTestCase(WorkoutManagerTestCase):
class WorkoutManagerAddTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests adding an object as an authorized user, a different one and a logged out
one.
- '''
+ """
object_class = ''
url = ''
@@ -418,17 +418,17 @@ class WorkoutManagerAddTestCase(WorkoutManagerTestCase):
data = {}
data_ignore = ()
fileupload = None
- '''
+ """
If the form requires a file upload, specify the field name and the file path
here in a list or tuple:
['fielname', 'path']
- '''
+ """
def add_object(self, fail=False):
- '''
+ """
Helper function to test adding an object
- '''
+ """
# Only perform the checks on derived classes
if self.__class__.__name__ == 'WorkoutManagerAddTestCase':
@@ -484,26 +484,26 @@ class WorkoutManagerAddTestCase(WorkoutManagerTestCase):
self.post_test_hook()
def test_add_object_anonymous(self):
- '''
+ """
Tests adding the object as an anonymous user
- '''
+ """
if self.user_fail:
self.add_object(fail=self.anonymous_fail)
def test_add_object_authorized(self):
- '''
+ """
Tests adding the object as the authorized users
- '''
+ """
for user in get_user_list(self.user_success):
self.user_login(user)
self.add_object(fail=False)
def test_add_object_other(self):
- '''
+ """
Tests adding the object as the unauthorized, logged in users
- '''
+ """
if self.user_fail:
for user in get_user_list(self.user_fail):
@@ -512,10 +512,10 @@ class WorkoutManagerAddTestCase(WorkoutManagerTestCase):
class WorkoutManagerAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests accessing a URL per GET as an authorized user, an unauthorized one and
a logged out one.
- '''
+ """
url = ''
anonymous_fail = True
@@ -541,26 +541,26 @@ class WorkoutManagerAccessTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_access_anonymous(self):
- '''
+ """
Tests accessing the URL as an anonymous user
- '''
+ """
self.user_logout()
self.access(fail=self.anonymous_fail)
def test_access_authorized(self):
- '''
+ """
Tests accessing the URL as the authorized users
- '''
+ """
for user in get_user_list(self.user_success):
self.user_login(user)
self.access(fail=False)
def test_access_other(self):
- '''
+ """
Tests accessing the URL as the unauthorized, logged in users
- '''
+ """
if self.user_fail:
for user in get_user_list(self.user_fail):
diff --git a/wger/core/tests/test_apikey.py b/wger/core/tests/test_apikey.py
index cd2222585..7b57cd1dd 100644
--- a/wger/core/tests/test_apikey.py
+++ b/wger/core/tests/test_apikey.py
@@ -30,14 +30,14 @@ logger = logging.getLogger(__name__)
class ApiKeyTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the API key page
- '''
+ """
def test_api_key_page(self):
- '''
+ """
Tests the API key generation page
- '''
+ """
self.user_login('test')
user = User.objects.get(username='test')
@@ -56,9 +56,9 @@ class ApiKeyTestCase(WorkoutManagerTestCase):
self.assertRaises(Token.DoesNotExist, Token.objects.get, user=user)
def test_api_key_page_generation(self):
- '''
+ """
User generates a new key
- '''
+ """
self.user_login('test')
user = User.objects.get(username='test')
diff --git a/wger/core/tests/test_change_password.py b/wger/core/tests/test_change_password.py
index c06f8ce8d..1db9c7897 100644
--- a/wger/core/tests/test_change_password.py
+++ b/wger/core/tests/test_change_password.py
@@ -27,9 +27,9 @@ logger = logging.getLogger(__name__)
class ChangePasswordTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests changing the password of a registered user
- '''
+ """
def change_password(self, fail=True):
@@ -57,16 +57,16 @@ class ChangePasswordTestCase(WorkoutManagerTestCase):
self.assertTrue(user.check_password('shuZoh2oGu7i'))
def test_change_password_anonymous(self):
- '''
+ """
Test changing a password as an anonymous user
- '''
+ """
self.change_password()
def test_copy_workout_logged_in(self, fail=True):
- '''
+ """
Test changing a password as a logged in user
- '''
+ """
self.user_login('test')
self.change_password(fail=False)
diff --git a/wger/core/tests/test_daysofweek.py b/wger/core/tests/test_daysofweek.py
index 2b23417f5..666924200 100644
--- a/wger/core/tests/test_daysofweek.py
+++ b/wger/core/tests/test_daysofweek.py
@@ -20,21 +20,21 @@ from wger.core.tests.base_testcase import WorkoutManagerTestCase
class DaysOfWeekRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(DaysOfWeek.objects.get(pk=1)), 'Monday')
class DaysOfWeekApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the days of week resource
- '''
+ """
pk = 1
resource = DaysOfWeek
private_resource = False
diff --git a/wger/core/tests/test_delete_user.py b/wger/core/tests/test_delete_user.py
index 735a2e632..51df870b1 100644
--- a/wger/core/tests/test_delete_user.py
+++ b/wger/core/tests/test_delete_user.py
@@ -27,14 +27,14 @@ logger = logging.getLogger(__name__)
class DeleteUserTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests deleting the user account and all his data
- '''
+ """
def delete_user(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('core:user:delete'))
self.assertEqual(User.objects.filter(username='test').count(), 1)
if fail:
@@ -58,28 +58,28 @@ class DeleteUserTestCase(WorkoutManagerTestCase):
self.assertEqual(User.objects.filter(username='test').count(), 0)
def test_delete_user_logged_in(self):
- '''
+ """
Tests deleting the own account as a logged in user
- '''
+ """
self.user_login('test')
self.delete_user(fail=False)
def test_delete_user_anonymous(self):
- '''
+ """
Tests deleting the own account as an anonymous user
- '''
+ """
self.delete_user(fail=True)
class DeleteUserByAdminTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests deleting a user account by a gym administrator
- '''
+ """
def delete_user(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('core:user:delete', kwargs={'user_pk': 2}))
self.assertEqual(User.objects.filter(username='test').count(), 1)
if fail:
@@ -107,84 +107,84 @@ class DeleteUserByAdminTestCase(WorkoutManagerTestCase):
self.assertEqual(User.objects.filter(username='test').count(), 0)
def test_delete_user_manager(self):
- '''
+ """
Tests deleting the user account as a gym manager
- '''
+ """
self.user_login('manager1')
self.delete_user(fail=False)
def test_delete_user_manager2(self):
- '''
+ """
Tests deleting the user account as a gym manager
- '''
+ """
self.user_login('manager2')
self.delete_user(fail=False)
def test_delete_user_general_manager(self):
- '''
+ """
Tests deleting the user account as a general manager
- '''
+ """
self.user_login('general_manager1')
self.delete_user(fail=False)
def test_delete_user_general_manager2(self):
- '''
+ """
Tests deleting the user account as a general manager
- '''
+ """
self.user_login('general_manager2')
self.delete_user(fail=False)
def test_delete_user(self):
- '''
+ """
Tests deleting the user account as a regular user
- '''
+ """
self.user_login('test')
self.delete_user(fail=True)
def test_delete_user_trainer(self):
- '''
+ """
Tests deleting the user account as a gym trainer
- '''
+ """
self.user_login('trainer1')
self.delete_user(fail=True)
def test_delete_user_trainer2(self):
- '''
+ """
Tests deleting the user account as a gym trainer
- '''
+ """
self.user_login('trainer4')
self.delete_user(fail=True)
def test_delete_user_trainer_other(self):
- '''
+ """
Tests deleting the user account as a gym trainer of another gym
- '''
+ """
self.user_login('trainer4')
self.delete_user(fail=True)
def test_delete_user_manager_other(self):
- '''
+ """
Tests deleting the user account as a gym manager of another gym
- '''
+ """
self.user_login('manager3')
self.delete_user(fail=True)
def test_delete_user_member(self):
- '''
+ """
Tests deleting the user account as a gym member
- '''
+ """
self.user_login('member1')
self.delete_user(fail=True)
def test_delete_user_member2(self):
- '''
+ """
Tests deleting the user account as a gym member
- '''
+ """
self.user_login('member4')
self.delete_user(fail=True)
def test_delete_user_anonymous(self):
- '''
+ """
Tests deleting the user account as an anonymous user
- '''
+ """
self.delete_user(fail=True)
diff --git a/wger/core/tests/test_feedback.py b/wger/core/tests/test_feedback.py
index 786df60e0..7c9134da1 100644
--- a/wger/core/tests/test_feedback.py
+++ b/wger/core/tests/test_feedback.py
@@ -24,14 +24,14 @@ from wger.core.tests.base_testcase import WorkoutManagerTestCase
class FeedbackTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the feedback form
- '''
+ """
def send_feedback(self, logged_in=True):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('core:feedback'))
self.assertEqual(response.status_code, 200)
response = self.client.post(reverse('core:feedback'),
@@ -62,25 +62,25 @@ class FeedbackTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_send_feedback_admin(self):
- '''
+ """
Tests the feedback form as an admin user
- '''
+ """
self.user_login('admin')
self.send_feedback()
def test_send_feedback_user(self):
- '''
+ """
Tests the feedback form as a regular user
- '''
+ """
self.user_login('test')
self.send_feedback()
@skip("Failing due to recaptcha issues")
def test_send_feedback_logged_out(self):
- '''
+ """
Tests the feedback form as a logged out user
- '''
+ """
self.send_feedback(logged_in=False)
diff --git a/wger/core/tests/test_index.py b/wger/core/tests/test_index.py
index 5e058a994..3a5569d59 100644
--- a/wger/core/tests/test_index.py
+++ b/wger/core/tests/test_index.py
@@ -24,14 +24,14 @@ from wger.weight.models import WeightEntry
class DashboardTestCase(WorkoutManagerTestCase):
- '''
+ """
Dashboard (landing page) test case
- '''
+ """
def dashboard(self):
- '''
+ """
Helper function to test the dashboard
- '''
+ """
response = self.client.get(reverse('core:index'))
@@ -90,17 +90,17 @@ class DashboardTestCase(WorkoutManagerTestCase):
self.assertTrue(response.context['weekdays'])
def test_dashboard_logged_in(self):
- '''
+ """
Test index page as a logged in user
- '''
+ """
self.user_login('admin')
self.dashboard()
def test_mobile_dashboard(self):
- '''
+ """
Test that a mobile request gets the mobile view
- '''
+ """
response = self.client.get(reverse('core:dashboard'))
self.assertEqual(response.status_code, 200)
diff --git a/wger/core/tests/test_language.py b/wger/core/tests/test_language.py
index 253f6c556..72de95a50 100644
--- a/wger/core/tests/test_language.py
+++ b/wger/core/tests/test_language.py
@@ -31,39 +31,39 @@ from wger.core.tests.base_testcase import (
class LanguageRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Language.objects.get(pk=1)), 'Deutsch (de)')
class LanguageOverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests accessing the system's languages
- '''
+ """
url = 'core:language:overview'
anonymous_fail = True
class LanguageDetailViewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests accessing a detail view of a language
- '''
+ """
url = reverse_lazy('core:language:view', kwargs={'pk': 1})
anonymous_fail = True
class CreateLanguageTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new language
- '''
+ """
object_class = Language
url = 'core:language:add'
@@ -72,9 +72,9 @@ class CreateLanguageTestCase(WorkoutManagerAddTestCase):
class EditLanguageTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests adding a new language
- '''
+ """
object_class = Language
url = 'core:language:edit'
@@ -84,9 +84,9 @@ class EditLanguageTestCase(WorkoutManagerEditTestCase):
class DeleteLanguageTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests adding a new language
- '''
+ """
object_class = Language
url = 'core:language:delete'
@@ -94,9 +94,9 @@ class DeleteLanguageTestCase(WorkoutManagerDeleteTestCase):
class LanguageApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the language overview resource
- '''
+ """
pk = 1
resource = Language
private_resource = False
diff --git a/wger/core/tests/test_license.py b/wger/core/tests/test_license.py
index 95500bfa3..1d9c09945 100644
--- a/wger/core/tests/test_license.py
+++ b/wger/core/tests/test_license.py
@@ -26,30 +26,30 @@ from wger.core.tests.base_testcase import (
class LicenseRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(License.objects.get(pk=1)),
'A cool and free license - Germany (ACAFL - DE)')
class LicenseOverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests the licese overview page
- '''
+ """
url = 'core:license:list'
class AddLicenseTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new license
- '''
+ """
object_class = License
url = 'core:license:add'
@@ -58,9 +58,9 @@ class AddLicenseTestCase(WorkoutManagerAddTestCase):
class DeleteLicenseTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a license
- '''
+ """
object_class = License
url = 'core:license:delete'
@@ -68,9 +68,9 @@ class DeleteLicenseTestCase(WorkoutManagerDeleteTestCase):
class EditLicenseTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a license
- '''
+ """
object_class = License
url = 'core:license:edit'
@@ -80,9 +80,9 @@ class EditLicenseTestCase(WorkoutManagerEditTestCase):
class LicenseApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the license resource
- '''
+ """
pk = 1
resource = License
private_resource = False
diff --git a/wger/core/tests/test_preferences.py b/wger/core/tests/test_preferences.py
index e02a3c693..e306b0155 100644
--- a/wger/core/tests/test_preferences.py
+++ b/wger/core/tests/test_preferences.py
@@ -31,14 +31,14 @@ logger = logging.getLogger(__name__)
class PreferencesTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the preferences page
- '''
+ """
def test_preferences(self):
- '''
+ """
Helper function to test the preferences page
- '''
+ """
self.user_login('test')
response = self.client.get(reverse('core:user:preferences'))
@@ -96,9 +96,9 @@ class PreferencesTestCase(WorkoutManagerTestCase):
self.assertEqual(response.context['user'].email, '')
def test_address(self):
- '''
+ """
Test that the address property works correctly
- '''
+ """
# Member2 has a contract
user = User.objects.get(username='member2')
@@ -118,14 +118,14 @@ class PreferencesTestCase(WorkoutManagerTestCase):
class UserBodyweightTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the body weight generation/update function
- '''
+ """
def test_bodyweight_new(self):
- '''
+ """
Tests that a new weight entry is created
- '''
+ """
user = User.objects.get(pk=2)
count_before = WeightEntry.objects.filter(user=user).count()
@@ -135,9 +135,9 @@ class UserBodyweightTestCase(WorkoutManagerTestCase):
self.assertEqual(entry.date, datetime.date.today())
def test_bodyweight_new_2(self):
- '''
+ """
Tests that a new weight entry is created
- '''
+ """
user = User.objects.get(pk=2)
count_before = WeightEntry.objects.filter(user=user).count()
last_entry = WeightEntry.objects.filter(user=user).latest()
@@ -150,9 +150,9 @@ class UserBodyweightTestCase(WorkoutManagerTestCase):
self.assertEqual(entry.date, datetime.date.today())
def test_bodyweight_no_entries(self):
- '''
+ """
Tests that a new weight entry is created if there are no weight entries
- '''
+ """
user = User.objects.get(pk=2)
WeightEntry.objects.filter(user=user).delete()
@@ -163,9 +163,9 @@ class UserBodyweightTestCase(WorkoutManagerTestCase):
self.assertEqual(entry.date, datetime.date.today())
def test_bodyweight_edit(self):
- '''
+ """
Tests that the last weight entry is edited
- '''
+ """
user = User.objects.get(pk=2)
last_entry = WeightEntry.objects.filter(user=user).latest()
last_entry.date = datetime.date.today() - datetime.timedelta(days=3)
@@ -180,9 +180,9 @@ class UserBodyweightTestCase(WorkoutManagerTestCase):
self.assertEqual(entry.weight, 100)
def test_bodyweight_edit_2(self):
- '''
+ """
Tests that the last weight entry is edited
- '''
+ """
user = User.objects.get(pk=2)
last_entry = WeightEntry.objects.filter(user=user).latest()
last_entry.date = datetime.date.today()
@@ -198,13 +198,13 @@ class UserBodyweightTestCase(WorkoutManagerTestCase):
class PreferencesCalculationsTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the different calculation method in the user profile
- '''
+ """
def test_last_weight_entry(self):
- '''
+ """
Tests that the last weight entry is correctly returned
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
entry = WeightEntry()
@@ -218,18 +218,18 @@ class PreferencesCalculationsTestCase(WorkoutManagerTestCase):
self.assertEqual(user.userprofile.weight, 150)
def test_last_weight_entry_empty(self):
- '''
+ """
Tests that the last weight entry is correctly returned if no matches
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
WeightEntry.objects.filter(user=user).delete()
self.assertEqual(user.userprofile.weight, 0)
def test_bmi(self):
- '''
+ """
Tests the BMI calculator
- '''
+ """
self.user_login('test')
@@ -240,9 +240,9 @@ class PreferencesCalculationsTestCase(WorkoutManagerTestCase):
decimal.Decimal(1.80 * 1.80).quantize(TWOPLACES))
def test_basal_metabolic_rate(self):
- '''
+ """
Tests the BMR calculator
- '''
+ """
self.user_login('test')
@@ -262,9 +262,9 @@ class PreferencesCalculationsTestCase(WorkoutManagerTestCase):
self.assertEqual(bmr, 0)
def test_calculate_activities(self):
- '''
+ """
Tests the calories calculator for physical activities
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
@@ -290,9 +290,9 @@ class PreferencesCalculationsTestCase(WorkoutManagerTestCase):
# TODO: the user can't delete or create new profiles
# class UserProfileApiTestCase(api_base_test.ApiBaseResourceTestCase):
-# '''
+# """
# Tests the user preferences overview resource
-# '''
+# """
# pk = 2
# resource = UserProfile
# private_resource = True
diff --git a/wger/core/tests/test_registration.py b/wger/core/tests/test_registration.py
index c048cc5ea..94b1b2686 100644
--- a/wger/core/tests/test_registration.py
+++ b/wger/core/tests/test_registration.py
@@ -31,15 +31,15 @@ logger = logging.getLogger(__name__)
class RegistrationTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests registering a new user
- '''
+ """
def test_registration_captcha(self):
- '''
+ """
Tests that the correct form is used depending on global
configuration settings
- '''
+ """
with self.settings(WGER_SETTINGS={'USE_RECAPTCHA': True,
'REMOVE_WHITESPACE': False,
'ALLOW_REGISTRATION': True,
@@ -99,9 +99,9 @@ class RegistrationTestCase(WorkoutManagerTestCase):
self.assertEqual(count_before + 1, count_after)
def test_registration_deactivated(self):
- '''
+ """
Test that with deactivated registration no users can register
- '''
+ """
with self.settings(WGER_SETTINGS={'USE_RECAPTCHA': False,
'REMOVE_WHITESPACE': False,
diff --git a/wger/core/tests/test_repetition_unit.py b/wger/core/tests/test_repetition_unit.py
index 6a3ef7f93..3a6aff1ad 100644
--- a/wger/core/tests/test_repetition_unit.py
+++ b/wger/core/tests/test_repetition_unit.py
@@ -26,30 +26,30 @@ from wger.core.tests.base_testcase import (
class RepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(RepetitionUnit.objects.get(pk=1)), 'Repetitions')
class OverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests the settings unit overview page
- '''
+ """
url = 'core:repetition-unit:list'
anonymous_fail = True
class AddTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new unit
- '''
+ """
object_class = RepetitionUnit
url = 'core:repetition-unit:add'
@@ -66,9 +66,9 @@ class AddTestCase(WorkoutManagerAddTestCase):
class DeleteTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a unit
- '''
+ """
pk = 1
object_class = RepetitionUnit
@@ -85,9 +85,9 @@ class DeleteTestCase(WorkoutManagerDeleteTestCase):
class EditTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a unit
- '''
+ """
pk = 1
object_class = RepetitionUnit
@@ -105,9 +105,9 @@ class EditTestCase(WorkoutManagerEditTestCase):
class ApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the unit resource
- '''
+ """
pk = 1
resource = RepetitionUnit
private_resource = False
diff --git a/wger/core/tests/test_robots_txt.py b/wger/core/tests/test_robots_txt.py
index c6073113d..f04e9b088 100644
--- a/wger/core/tests/test_robots_txt.py
+++ b/wger/core/tests/test_robots_txt.py
@@ -21,9 +21,9 @@ from wger.core.tests.base_testcase import WorkoutManagerTestCase
class RobotsTxtTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the generated robots.txt
- '''
+ """
def test_robots(self):
diff --git a/wger/core/tests/test_sitemap.py b/wger/core/tests/test_sitemap.py
index a1c5f5fc7..ee993a285 100644
--- a/wger/core/tests/test_sitemap.py
+++ b/wger/core/tests/test_sitemap.py
@@ -20,9 +20,9 @@ from wger.core.tests.base_testcase import WorkoutManagerTestCase
class SitemapTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the generated sitemap
- '''
+ """
def test_sitemap(self):
diff --git a/wger/core/tests/test_spaceless.py b/wger/core/tests/test_spaceless.py
index 20aa21ec4..46dfddc5c 100644
--- a/wger/core/tests/test_spaceless.py
+++ b/wger/core/tests/test_spaceless.py
@@ -29,14 +29,14 @@ logger = logging.getLogger(__name__)
class SpacelessTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the custom spaceless template tag
- '''
+ """
def test_spaceless(self):
- '''
+ """
Tests the custom spaceless template tag
- '''
+ """
t = Template('{% load wger_extras %}'
'{% spaceless_config %}<p>A text</p> <p>more</p>{% endspaceless_config %}')
context = Context()
diff --git a/wger/core/tests/test_temporary_users.py b/wger/core/tests/test_temporary_users.py
index 04d9579df..554bfa438 100644
--- a/wger/core/tests/test_temporary_users.py
+++ b/wger/core/tests/test_temporary_users.py
@@ -42,22 +42,22 @@ from wger.weight.models import WeightEntry
class DemoUserTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the demo user
- '''
+ """
@staticmethod
def count_temp_users():
- '''
+ """
Counts the number of temporary users
- '''
+ """
return User.objects.filter(userprofile__is_temporary=1).count()
def test_demo_data_no_guest_account(self):
- '''
+ """
Tests that the helper function creates demo data (workout, etc.)
for the demo users
- '''
+ """
with self.settings(WGER_SETTINGS={'USE_RECAPTCHA': True,
'REMOVE_WHITESPACE': False,
'ALLOW_REGISTRATION': True,
@@ -70,10 +70,10 @@ class DemoUserTestCase(WorkoutManagerTestCase):
self.assertEqual(self.count_temp_users(), 1)
def test_demo_data_guest_account(self):
- '''
+ """
Tests that the helper function creates demo data (workout, etc.)
for the demo users
- '''
+ """
self.client.get(reverse('core:dashboard'))
self.assertEqual(self.count_temp_users(), 2)
user = User.objects.get(pk=User.objects.latest('id').id)
@@ -98,10 +98,10 @@ class DemoUserTestCase(WorkoutManagerTestCase):
self.assertEqual(WeightEntry.objects.filter(user=user).count(), 19)
def test_demo_data_body_weight(self):
- '''
+ """
Tests that the helper function that creates demo data filters out
existing dates for the weight entries
- '''
+ """
self.client.get(reverse('core:dashboard'))
self.assertEqual(self.count_temp_users(), 2)
user = User.objects.get(pk=4)
@@ -120,10 +120,10 @@ class DemoUserTestCase(WorkoutManagerTestCase):
self.assertEqual(WeightEntry.objects.filter(user=user).count(), 19)
def test_demo_user(self):
- '''
+ """
Tests that temporary users are automatically created when visiting
URLs that need a user present
- '''
+ """
self.assertEqual(self.count_temp_users(), 1)
@@ -162,9 +162,9 @@ class DemoUserTestCase(WorkoutManagerTestCase):
self.assertEqual(self.count_temp_users(), 2)
def test_demo_user_notice(self):
- '''
+ """
Tests that demo users see a notice on every page
- '''
+ """
demo_notice_text = 'You are using a guest account'
self.user_login('demo')
self.assertContains(self.client.get(reverse('core:dashboard')), demo_notice_text)
@@ -179,9 +179,9 @@ class DemoUserTestCase(WorkoutManagerTestCase):
self.assertContains(self.client.get(reverse('software:license')), demo_notice_text)
def test_command_delete_old_users(self):
- '''
+ """
Tests that old demo users are deleted by the management command
- '''
+ """
# Create some new demo users
for i in range(0, 15):
diff --git a/wger/core/tests/test_user.py b/wger/core/tests/test_user.py
index ac8f0a56a..cfeaa7830 100644
--- a/wger/core/tests/test_user.py
+++ b/wger/core/tests/test_user.py
@@ -28,9 +28,9 @@ from wger.core.tests.base_testcase import (
class StatusUserTestCase(WorkoutManagerTestCase):
- '''
+ """
Test activating and deactivating users
- '''
+ """
user_success = ('general_manager1',
'general_manager2',
@@ -48,9 +48,9 @@ class StatusUserTestCase(WorkoutManagerTestCase):
'trainer4')
def activate(self, fail=False):
- '''
+ """
Helper function to test activating users
- '''
+ """
user = User.objects.get(pk=2)
user.is_active = False
user.save()
@@ -66,33 +66,33 @@ class StatusUserTestCase(WorkoutManagerTestCase):
self.assertTrue(user.is_active)
def test_activate_authorized(self):
- '''
+ """
Tests activating a user as an administrator
- '''
+ """
for username in self.user_success:
self.user_login(username)
self.activate()
self.user_logout()
def test_activate_unauthorized(self):
- '''
+ """
Tests activating a user as another logged in user
- '''
+ """
for username in self.user_fail:
self.user_login(username)
self.activate(fail=True)
self.user_logout()
def test_activate_logged_out(self):
- '''
+ """
Tests activating a user a logged out user
- '''
+ """
self.activate(fail=True)
def deactivate(self, fail=False):
- '''
+ """
Helper function to test deactivating users
- '''
+ """
user = User.objects.get(pk=2)
user.is_active = True
user.save()
@@ -108,34 +108,34 @@ class StatusUserTestCase(WorkoutManagerTestCase):
self.assertFalse(user.is_active)
def test_deactivate_authorized(self):
- '''
+ """
Tests deactivating a user as an administrator
- '''
+ """
for username in self.user_success:
self.user_login(username)
self.deactivate()
self.user_logout()
def test_deactivate_unauthorized(self):
- '''
+ """
Tests deactivating a user as another logged in user
- '''
+ """
for username in self.user_fail:
self.user_login(username)
self.deactivate(fail=True)
self.user_logout()
def test_deactivate_logged_out(self):
- '''
+ """
Tests deactivating a user a logged out user
- '''
+ """
self.deactivate(fail=True)
class EditUserTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Test editing a user
- '''
+ """
object_class = User
url = 'core:user:edit'
@@ -157,9 +157,9 @@ class EditUserTestCase(WorkoutManagerEditTestCase):
class EditUserTestCase2(WorkoutManagerEditTestCase):
- '''
+ """
Test editing a user
- '''
+ """
object_class = User
url = 'core:user:edit'
@@ -179,9 +179,9 @@ class EditUserTestCase2(WorkoutManagerEditTestCase):
class UserListTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the general user overview
- '''
+ """
url = 'core:user:list'
user_success = ('admin',
@@ -198,9 +198,9 @@ class UserListTestCase(WorkoutManagerAccessTestCase):
class UserDetailPageTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the user detail page
- '''
+ """
url = reverse_lazy('core:user:overview', kwargs={'pk': 2})
user_success = ('trainer1',
@@ -216,9 +216,9 @@ class UserDetailPageTestCase(WorkoutManagerAccessTestCase):
class UserDetailPageTestCase2(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the user detail page
- '''
+ """
url = reverse_lazy('core:user:overview', kwargs={'pk': 19})
user_success = ('trainer4',
diff --git a/wger/core/tests/test_weight_unit.py b/wger/core/tests/test_weight_unit.py
index 1d0105f99..11f65c4e9 100644
--- a/wger/core/tests/test_weight_unit.py
+++ b/wger/core/tests/test_weight_unit.py
@@ -26,30 +26,30 @@ from wger.core.tests.base_testcase import (
class RepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(WeightUnit.objects.get(pk=1)), 'kg')
class OverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests the weight unit overview page
- '''
+ """
url = 'core:weight-unit:list'
anonymous_fail = True
class AddTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new unit
- '''
+ """
object_class = WeightUnit
url = 'core:weight-unit:add'
@@ -66,9 +66,9 @@ class AddTestCase(WorkoutManagerAddTestCase):
class DeleteTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a unit
- '''
+ """
pk = 1
object_class = WeightUnit
@@ -85,9 +85,9 @@ class DeleteTestCase(WorkoutManagerDeleteTestCase):
class EditTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a unit
- '''
+ """
pk = 1
object_class = WeightUnit
@@ -105,9 +105,9 @@ class EditTestCase(WorkoutManagerEditTestCase):
class ApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the unit resource
- '''
+ """
pk = 1
resource = WeightUnit
private_resource = False
diff --git a/wger/core/views/languages.py b/wger/core/views/languages.py
index 813d7fdbd..6e5b61580 100644
--- a/wger/core/views/languages.py
+++ b/wger/core/views/languages.py
@@ -51,9 +51,9 @@ logger = logging.getLogger(__name__)
class LanguageListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Show an overview of all languages
- '''
+ """
model = Language
template_name = 'language/overview.html'
context_object_name = 'language_list'
@@ -68,9 +68,9 @@ class LanguageDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView
class LanguageCreateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
Generic view to add a new language
- '''
+ """
model = Language
fields = '__all__'
@@ -80,9 +80,9 @@ class LanguageCreateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMi
class LanguageDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
Generic view to delete an existing language
- '''
+ """
model = Language
fields = '__all__'
@@ -91,9 +91,9 @@ class LanguageDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequired
permission_required = 'core.delete_language'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(LanguageDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object.full_name)
@@ -103,9 +103,9 @@ class LanguageDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequired
class LanguageEditView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
Generic view to update an existing language
- '''
+ """
model = Language
fields = '__all__'
@@ -113,9 +113,9 @@ class LanguageEditView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixi
permission_required = 'core.change_language'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(LanguageEditView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object.full_name)
return context
diff --git a/wger/core/views/license.py b/wger/core/views/license.py
index 045f910e0..ba560170f 100644
--- a/wger/core/views/license.py
+++ b/wger/core/views/license.py
@@ -50,18 +50,18 @@ logger = logging.getLogger(__name__)
class LicenseListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available licenses
- '''
+ """
model = License
permission_required = 'core.add_license'
template_name = 'license/list.html'
class LicenseAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new license
- '''
+ """
model = License
fields = ['full_name', 'short_name', 'url']
@@ -72,9 +72,9 @@ class LicenseAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin,
class LicenseUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing license
- '''
+ """
model = License
fields = ['full_name', 'short_name', 'url']
@@ -82,9 +82,9 @@ class LicenseUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMix
permission_required = 'core.change_license'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(LicenseUpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('core:license:edit', kwargs={'pk': self.object.id})
context['title'] = _(u'Edit {0}').format(self.object)
@@ -92,9 +92,9 @@ class LicenseUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMix
class LicenseDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing license
- '''
+ """
model = License
fields = ['full_name', 'short_name', 'url']
@@ -102,9 +102,9 @@ class LicenseDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredM
permission_required = 'core.delete_license'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(LicenseDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
context['form_action'] = reverse('core:license:delete', kwargs={'pk': self.kwargs['pk']})
diff --git a/wger/core/views/misc.py b/wger/core/views/misc.py
index 31b4d0905..50a30d29c 100644
--- a/wger/core/views/misc.py
+++ b/wger/core/views/misc.py
@@ -59,9 +59,9 @@ logger = logging.getLogger(__name__)
# Misc functions
# ************************
def index(request):
- '''
+ """
Index page
- '''
+ """
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('core:dashboard'))
else:
@@ -69,9 +69,9 @@ def index(request):
def demo_entries(request):
- '''
+ """
Creates a set of sample entries for guest users
- '''
+ """
if not settings.WGER_SETTINGS['ALLOW_GUEST_USERS']:
return HttpResponseRedirect(reverse('software:features'))
@@ -96,10 +96,10 @@ def demo_entries(request):
@login_required
@vary_on_headers('User-Agent')
def dashboard(request):
- '''
+ """
Show the index page, in our case, the last workout and nutritional plan
and the current weight
- '''
+ """
template_data = {}
@@ -166,17 +166,17 @@ class FeedbackClass(FormView):
success_url = reverse_lazy('core:contact')
def get_initial(self):
- '''
+ """
Fill in the contact, if available
- '''
+ """
if self.request.user.is_authenticated:
return {'contact': self.request.user.email}
return {}
def get_context_data(self, **kwargs):
- '''
+ """
Set necessary template data to correctly render the form
- '''
+ """
context = super(FeedbackClass, self).get_context_data(**kwargs)
context['title'] = _('Feedback')
# TODO: change template so it iterates through form and not formfields
@@ -188,19 +188,19 @@ class FeedbackClass(FormView):
return context
def get_form_class(self):
- '''
+ """
Load the correct feedback form depending on the user
(either with reCaptcha field or not)
- '''
+ """
if self.request.user.is_anonymous or self.request.user.userprofile.is_temporary:
return FeedbackAnonymousForm
else:
return FeedbackRegisteredForm
def form_valid(self, form):
- '''
+ """
Send the feedback to the administrators
- '''
+ """
messages.success(self.request, _('Your feedback was successfully sent. Thank you!'))
context = {}
diff --git a/wger/core/views/repetition_units.py b/wger/core/views/repetition_units.py
index 58c0903c7..d725969da 100644
--- a/wger/core/views/repetition_units.py
+++ b/wger/core/views/repetition_units.py
@@ -48,18 +48,18 @@ logger = logging.getLogger(__name__)
class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available setting units
- '''
+ """
model = RepetitionUnit
permission_required = 'core.add_repetitionunit'
template_name = 'repetition_unit/list.html'
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new setting unit
- '''
+ """
model = RepetitionUnit
fields = ['name']
@@ -70,9 +70,9 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing setting unit
- '''
+ """
model = RepetitionUnit
fields = ['name']
@@ -81,18 +81,18 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
permission_required = 'core.change_repetitionunit'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing license
- '''
+ """
model = RepetitionUnit
success_url = reverse_lazy('core:repetition-unit:list')
@@ -100,20 +100,20 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
form_action_urlname = 'core:repetition-unit:delete'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Deleting the unit with ID 1 (repetitions) is not allowed
This is the default and is hard coded in a couple of places
- '''
+ """
if self.kwargs['pk'] == '1':
return HttpResponseForbidden()
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
return context
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
index 17b01123b..dab422db5 100644
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -94,9 +94,9 @@ logger = logging.getLogger(__name__)
def login(request):
- '''
+ """
Small wrapper around the django login view
- '''
+ """
context = {'active_tab': USER_TAB}
if request.GET.get('next'):
@@ -109,12 +109,12 @@ def login(request):
@login_required()
def delete(request, user_pk=None):
- '''
+ """
Delete a user account and all his data, requires password confirmation first
If no user_pk is present, the user visiting the URL will be deleted, otherwise
a gym administrator is deleting a different user
- '''
+ """
if user_pk:
user = get_object_or_404(User, pk=user_pk)
@@ -158,9 +158,9 @@ def delete(request, user_pk=None):
@login_required()
def trainer_login(request, user_pk):
- '''
+ """
Allows a trainer to 'log in' as the selected user
- '''
+ """
user = get_object_or_404(User, pk=user_pk)
orig_user_pk = request.user.pk
@@ -207,9 +207,9 @@ def trainer_login(request, user_pk):
def logout(request):
- '''
+ """
Logout the user. For temporary users, delete them.
- '''
+ """
user = request.user
django_logout(request)
if user.is_authenticated and user.userprofile.is_temporary:
@@ -218,9 +218,9 @@ def logout(request):
def registration(request):
- '''
+ """
A form to allow for registration of new users
- '''
+ """
# If global user registration is deactivated, redirect
if not settings.WGER_SETTINGS['ALLOW_REGISTRATION']:
@@ -290,9 +290,9 @@ def registration(request):
@login_required
def preferences(request):
- '''
+ """
An overview of all user preferences
- '''
+ """
template_data = {}
template_data.update(csrf(request))
redirect = False
@@ -335,17 +335,17 @@ def preferences(request):
class UserDeactivateView(LoginRequiredMixin,
WgerMultiplePermissionRequiredMixin,
RedirectView):
- '''
+ """
Deactivates a user
- '''
+ """
permanent = False
model = User
permission_required = ('gym.manage_gym', 'gym.manage_gyms', 'gym.gym_trainer')
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only managers and trainers for this gym can access the members
- '''
+ """
edit_user = get_object_or_404(User, pk=self.kwargs['pk'])
if not request.user.is_authenticated:
@@ -368,17 +368,17 @@ class UserDeactivateView(LoginRequiredMixin,
class UserActivateView(LoginRequiredMixin,
WgerMultiplePermissionRequiredMixin,
RedirectView):
- '''
+ """
Activates a previously deactivated user
- '''
+ """
permanent = False
model = User
permission_required = ('gym.manage_gym', 'gym.manage_gyms', 'gym.gym_trainer')
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only managers and trainers for this gym can access the members
- '''
+ """
edit_user = get_object_or_404(User, pk=self.kwargs['pk'])
if not request.user.is_authenticated:
@@ -402,9 +402,9 @@ class UserEditView(WgerFormMixin,
LoginRequiredMixin,
WgerMultiplePermissionRequiredMixin,
UpdateView):
- '''
+ """
View to update the personal information of an user by an admin
- '''
+ """
model = User
title = ugettext_lazy('Edit user')
@@ -412,12 +412,12 @@ class UserEditView(WgerFormMixin,
form_class = UserPersonalInformationForm
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Check permissions
- Managers can edit members of their own gym
- General managers can edit every member
- '''
+ """
user = request.user
if not user.is_authenticated:
return HttpResponseForbidden()
@@ -433,9 +433,9 @@ class UserEditView(WgerFormMixin,
return reverse('core:user:overview', kwargs={'pk': self.kwargs['pk']})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UserEditView, self).get_context_data(**kwargs)
context['form_action'] = reverse('core:user:edit', kwargs={'pk': self.object.id})
context['title'] = _('Edit {0}'.format(self.object))
@@ -444,9 +444,9 @@ class UserEditView(WgerFormMixin,
@login_required
def api_key(request):
- '''
+ """
Allows the user to generate an API key for the REST API
- '''
+ """
context = {}
context.update(csrf(request))
@@ -470,21 +470,21 @@ def api_key(request):
class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, DetailView):
- '''
+ """
User overview for gyms
- '''
+ """
model = User
permission_required = ('gym.manage_gym', 'gym.manage_gyms', 'gym.gym_trainer')
template_name = 'user/overview.html'
context_object_name = 'current_user'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Check permissions
- Only managers for this gym can access the members
- General managers can access the detail page of all users
- '''
+ """
user = request.user
if not user.is_authenticated:
@@ -498,9 +498,9 @@ class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, De
return super(UserDetailView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UserDetailView, self).get_context_data(**kwargs)
out = []
workouts = Workout.objects.filter(user=self.object).all()
@@ -521,17 +521,17 @@ class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, De
class UserListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all users in the instance
- '''
+ """
model = User
permission_required = ('gym.manage_gyms',)
template_name = 'user/list.html'
def get_queryset(self):
- '''
+ """
Return a list with the users, not really a queryset.
- '''
+ """
out = {'admins': [],
'members': []}
@@ -542,9 +542,9 @@ class UserListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin
return out
def get_context_data(self, **kwargs):
- '''
+ """
Pass other info to the template
- '''
+ """
context = super(UserListView, self).get_context_data(**kwargs)
context['show_gym'] = True
context['user_table'] = {'keys': [_('ID'),
diff --git a/wger/core/views/weight_units.py b/wger/core/views/weight_units.py
index 8a30a9ca8..a299e3c30 100644
--- a/wger/core/views/weight_units.py
+++ b/wger/core/views/weight_units.py
@@ -48,18 +48,18 @@ logger = logging.getLogger(__name__)
class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available weight units
- '''
+ """
model = WeightUnit
permission_required = 'core.add_weightunit'
template_name = 'weight_unit/list.html'
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new weight unit
- '''
+ """
model = WeightUnit
fields = ['name']
@@ -70,9 +70,9 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing weight unit
- '''
+ """
model = WeightUnit
fields = ['name']
@@ -81,18 +81,18 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
permission_required = 'core.change_weightunit'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing license
- '''
+ """
model = WeightUnit
success_url = reverse_lazy('core:weight-unit:list')
@@ -100,20 +100,20 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
form_action_urlname = 'core:weight-unit:delete'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Deleting the unit with ID 1 (repetitions) is not allowed
This is the default and is hard coded in a couple of places
- '''
+ """
if self.kwargs['pk'] == '1':
return HttpResponseForbidden()
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
return context
diff --git a/wger/email/forms.py b/wger/email/forms.py
index 3f977d3f7..c704c3130 100644
--- a/wger/email/forms.py
+++ b/wger/email/forms.py
@@ -25,9 +25,9 @@ from django.utils.translation import pgettext
class EmailListForm(Form):
- '''
+ """
Small form to send emails
- '''
+ """
subject = CharField(label=pgettext('As in "email subject"', 'Subject'))
body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
diff --git a/wger/email/management/commands/send-mass-emails.py b/wger/email/management/commands/send-mass-emails.py
index 5a6959548..017172c77 100644
--- a/wger/email/management/commands/send-mass-emails.py
+++ b/wger/email/management/commands/send-mass-emails.py
@@ -24,14 +24,14 @@ from wger.email.models import CronEntry
class Command(BaseCommand):
- '''
+ """
Sends the prepared mass emails
- '''
+ """
def handle(self, **options):
- '''
+ """
Send some mails and remove them from the list
- '''
+ """
if CronEntry.objects.count():
for email in CronEntry.objects.all()[:100]:
mail.send_mail(email.log.subject,
diff --git a/wger/email/models.py b/wger/email/models.py
index e073b244c..5349b997d 100644
--- a/wger/email/models.py
+++ b/wger/email/models.py
@@ -23,69 +23,69 @@ from wger.gym.models import Gym
class Log(models.Model):
- '''
+ """
A log of a sent email
- '''
+ """
class Meta:
ordering = ["-date", ]
date = models.DateField(auto_now=True)
- '''
+ """
Date when the log was created
- '''
+ """
user = models.ForeignKey(User,
editable=False,
on_delete=models.CASCADE)
- '''
+ """
The user that created the email
- '''
+ """
gym = models.ForeignKey(Gym,
editable=False,
related_name='email_log',
on_delete=models.CASCADE)
- '''
+ """
Gym this log belongs to
- '''
+ """
subject = models.CharField(max_length=100)
- '''
+ """
The email subject
- '''
+ """
body = models.TextField()
- '''
+ """
The email body
- '''
+ """
def __unicode__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.subject
class CronEntry(models.Model):
- '''
+ """
Simple list of emails to be sent by a cron job
- '''
+ """
log = models.ForeignKey(Log,
editable=False,
on_delete=models.CASCADE)
- '''
+ """
Foreign key to email log with subject and body
- '''
+ """
email = models.EmailField()
- '''
+ """
The email address
- '''
+ """
def __unicode__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.email
diff --git a/wger/email/tests/test_gym_emails.py b/wger/email/tests/test_gym_emails.py
index 92d552593..6b3c0dcd4 100644
--- a/wger/email/tests/test_gym_emails.py
+++ b/wger/email/tests/test_gym_emails.py
@@ -20,9 +20,9 @@ from wger.core.tests.base_testcase import WorkoutManagerAccessTestCase
class AccessContractTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the detail page of a contract
- '''
+ """
url = reverse('email:email:overview', kwargs={'gym_pk': 1})
user_success = ('manager1',
'manager2')
diff --git a/wger/email/views/gym.py b/wger/email/views/gym.py
index 8fc68a645..1d0617809 100644
--- a/wger/email/views/gym.py
+++ b/wger/email/views/gym.py
@@ -39,9 +39,9 @@ from wger.utils.generic_views import UAAwareViewMixin
class EmailLogListView(PermissionRequiredMixin, UAAwareViewMixin, generic.ListView):
- '''
+ """
Shows a list with all sent emails
- '''
+ """
model = Log
context_object_name = "email_list"
@@ -50,16 +50,16 @@ class EmailLogListView(PermissionRequiredMixin, UAAwareViewMixin, generic.ListVi
gym = None
def get_queryset(self):
- '''
+ """
Can only view emails for own gym
- '''
+ """
self.gym = get_object_or_404(Gym, pk=self.kwargs['gym_pk'])
return Log.objects.filter(gym=self.gym)
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only view email list for own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -69,9 +69,9 @@ class EmailLogListView(PermissionRequiredMixin, UAAwareViewMixin, generic.ListVi
return super(EmailLogListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Pass additional data to the template
- '''
+ """
context = super(EmailLogListView, self).get_context_data(**kwargs)
context['gym'] = self.gym
return context
@@ -84,18 +84,18 @@ class EmailListFormPreview(FormPreview):
gym = None
def parse_params(self, *args, **kwargs):
- '''
+ """
Save the current recipient type
- '''
+ """
self.gym = get_object_or_404(Gym, pk=int(kwargs['gym_pk']))
def get_context(self, request, form):
- '''
+ """
Context for template rendering
Also, check for permissions here. While it is ugly and doesn't really
belong here, it seems it's the best way to do it in a FormPreview
- '''
+ """
if not request.user.is_authenticated or\
request.user.userprofile.gym_id != self.gym.id or \
not request.user.has_perms('core.change_emailcron'):
@@ -109,9 +109,9 @@ class EmailListFormPreview(FormPreview):
return context
def process_preview(self, request, form, context):
- '''
+ """
Send an email to the managers with the current content
- '''
+ """
for admin in Gym.objects.get_admins(self.gym.pk):
if admin.email:
mail.send_mail(form.cleaned_data['subject'],
@@ -122,9 +122,9 @@ class EmailListFormPreview(FormPreview):
return context
def done(self, request, cleaned_data):
- '''
+ """
Collect appropriate emails and save to database to send for later
- '''
+ """
emails = []
# Select all users in the gym
diff --git a/wger/exercises/api/resources.py b/wger/exercises/api/resources.py
index 27e41283c..e20488057 100644
--- a/wger/exercises/api/resources.py
+++ b/wger/exercises/api/resources.py
@@ -101,9 +101,9 @@ class ExerciseImageResource(ModelResource):
"license_author": ALL}
def dehydrate(self, bundle):
- '''
+ """
Also send the URLs for the thumbnailed pictures
- '''
+ """
thumbnails = {}
for alias in aliases.all():
t = get_thumbnailer(bundle.obj.image)
diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py
index 7e09ed25c..e0ac47dc1 100644
--- a/wger/exercises/api/serializers.py
+++ b/wger/exercises/api/serializers.py
@@ -29,27 +29,27 @@ from wger.exercises.models import (
class ExerciseSerializer(serializers.ModelSerializer):
- '''
+ """
Exercise serializer
- '''
+ """
class Meta:
model = Exercise
fields = '__all__'
class EquipmentSerializer(serializers.ModelSerializer):
- '''
+ """
Equipment serializer
- '''
+ """
class Meta:
model = Equipment
fields = '__all__'
class ExerciseInfoSerializer(serializers.ModelSerializer):
- '''
+ """
Equipment serializer
- '''
+ """
class Meta:
model = Exercise
depth = 3
@@ -57,36 +57,36 @@ class ExerciseInfoSerializer(serializers.ModelSerializer):
class ExerciseCategorySerializer(serializers.ModelSerializer):
- '''
+ """
ExerciseCategory serializer
- '''
+ """
class Meta:
model = ExerciseCategory
fields = '__all__'
class ExerciseImageSerializer(serializers.ModelSerializer):
- '''
+ """
ExerciseImage serializer
- '''
+ """
class Meta:
model = ExerciseImage
fields = '__all__'
class ExerciseCommentSerializer(serializers.ModelSerializer):
- '''
+ """
ExerciseComment serializer
- '''
+ """
class Meta:
model = ExerciseComment
fields = '__all__'
class MuscleSerializer(serializers.ModelSerializer):
- '''
+ """
Muscle serializer
- '''
+ """
class Meta:
model = Muscle
fields = '__all__'
diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.py
index e270a43df..00d2112f1 100644
--- a/wger/exercises/api/views.py
+++ b/wger/exercises/api/views.py
@@ -56,9 +56,9 @@ from wger.utils.permissions import CreateOnlyPermission
class ExerciseViewSet(viewsets.ModelViewSet):
- '''
+ """
API endpoint for exercise objects
- '''
+ """
queryset = Exercise.objects.all()
serializer_class = ExerciseSerializer
permission_classes = (IsAuthenticatedOrReadOnly, CreateOnlyPermission)
@@ -76,9 +76,9 @@ class ExerciseViewSet(viewsets.ModelViewSet):
'license_author')
def perform_create(self, serializer):
- '''
+ """
Set author and status
- '''
+ """
language = load_language()
obj = serializer.save(language=language)
# Todo is it right to call set author after save?
@@ -88,11 +88,11 @@ class ExerciseViewSet(viewsets.ModelViewSet):
@api_view(['GET'])
def search(request):
- '''
+ """
Searches for exercises.
This format is currently used by the exercise search autocompleter
- '''
+ """
q = request.GET.get('term', None)
results = []
json_response = {}
@@ -133,9 +133,9 @@ def search(request):
class ExerciseInfoViewset(viewsets.ModelViewSet):
- '''
+ """
API endpoint for exercise objects
- '''
+ """
queryset = Exercise.objects.all()
serializer_class = ExerciseInfoSerializer
permission_classes = (IsAuthenticatedOrReadOnly, CreateOnlyPermission)
@@ -154,9 +154,9 @@ class ExerciseInfoViewset(viewsets.ModelViewSet):
class EquipmentViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for equipment objects
- '''
+ """
queryset = Equipment.objects.all()
serializer_class = EquipmentSerializer
ordering_fields = '__all__'
@@ -164,9 +164,9 @@ class EquipmentViewSet(viewsets.ReadOnlyModelViewSet):
class ExerciseCategoryViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for exercise categories objects
- '''
+ """
queryset = ExerciseCategory.objects.all()
serializer_class = ExerciseCategorySerializer
ordering_fields = '__all__'
@@ -174,9 +174,9 @@ class ExerciseCategoryViewSet(viewsets.ReadOnlyModelViewSet):
class ExerciseImageViewSet(viewsets.ModelViewSet):
- '''
+ """
API endpoint for exercise image objects
- '''
+ """
queryset = ExerciseImage.objects.all()
serializer_class = ExerciseImageSerializer
permission_classes = (IsAuthenticatedOrReadOnly, CreateOnlyPermission)
@@ -189,9 +189,9 @@ class ExerciseImageViewSet(viewsets.ModelViewSet):
@action(detail=True)
def thumbnails(self, request, pk):
- '''
+ """
Return a list of the image's thumbnails
- '''
+ """
try:
image = ExerciseImage.objects.get(pk=pk)
except ExerciseImage.DoesNotExist:
@@ -208,9 +208,9 @@ class ExerciseImageViewSet(viewsets.ModelViewSet):
return Response(thumbnails)
def perform_create(self, serializer):
- '''
+ """
Set the license data
- '''
+ """
obj = serializer.save()
# Todo is it right to call set author after save?
obj.set_author(self.request)
@@ -218,9 +218,9 @@ class ExerciseImageViewSet(viewsets.ModelViewSet):
class ExerciseCommentViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for exercise comment objects
- '''
+ """
queryset = ExerciseComment.objects.all()
serializer_class = ExerciseCommentSerializer
ordering_fields = '__all__'
@@ -229,9 +229,9 @@ class ExerciseCommentViewSet(viewsets.ReadOnlyModelViewSet):
class MuscleViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for muscle objects
- '''
+ """
queryset = Muscle.objects.all()
serializer_class = MuscleSerializer
ordering_fields = '__all__'
diff --git a/wger/exercises/management/commands/download-exercise-images.py b/wger/exercises/management/commands/download-exercise-images.py
index 373476d04..9fa985539 100644
--- a/wger/exercises/management/commands/download-exercise-images.py
+++ b/wger/exercises/management/commands/download-exercise-images.py
@@ -44,13 +44,13 @@ from wger.exercises.models import (
class Command(BaseCommand):
- '''
+ """
Download exercise images from wger.de and updates the local database
The script assumes that the local IDs correspond to the remote ones, which
is the case if the user installed the exercises from the JSON fixtures.
Otherwise, the exercise is simply skipped
- '''
+ """
help = ('Download exercise images from wger.de and update the local database\n'
'\n'
diff --git a/wger/exercises/management/commands/redo-capitalize-names.py b/wger/exercises/management/commands/redo-capitalize-names.py
index 224c8ab75..f3f0369e1 100644
--- a/wger/exercises/management/commands/redo-capitalize-names.py
+++ b/wger/exercises/management/commands/redo-capitalize-names.py
@@ -23,12 +23,12 @@ from wger.utils.helpers import smart_capitalize
class Command(BaseCommand):
- '''
+ """
Re-calculates the capitalized exercise names
This is a safe operation, since the original names (as entered by the user)
are still available.
- '''
+ """
help = 'Re-calculates the capitalized exercise names'
diff --git a/wger/exercises/management/commands/submitted-exercises.py b/wger/exercises/management/commands/submitted-exercises.py
index 8b3b29a34..4bd07ce08 100644
--- a/wger/exercises/management/commands/submitted-exercises.py
+++ b/wger/exercises/management/commands/submitted-exercises.py
@@ -22,11 +22,11 @@ from wger.exercises.models import Exercise
class Command(BaseCommand):
- '''
+ """
Read out the user submitted exercise.
Used to generate the AUTHORS file for a release
- '''
+ """
help = 'Read out the user submitted exercise'
diff --git a/wger/exercises/migrations/0002_auto_20150307_1841.py b/wger/exercises/migrations/0002_auto_20150307_1841.py
index 4a4a1d342..4a95fab49 100644
--- a/wger/exercises/migrations/0002_auto_20150307_1841.py
+++ b/wger/exercises/migrations/0002_auto_20150307_1841.py
@@ -5,12 +5,12 @@ from django.db import models, migrations
import uuid
def generate_uuids(apps, schema_editor):
- '''
+ """
Generate new UUIDs for each exercise
:param apps:
:param schema_editor:
:return:
- '''
+ """
Excercise = apps.get_model("exercises", "Exercise")
for exercise in Excercise.objects.all():
exercise.uuid = uuid.uuid4()
diff --git a/wger/exercises/migrations/0003_auto_20160921_2000.py b/wger/exercises/migrations/0003_auto_20160921_2000.py
index e7d6a28e6..93109b79d 100644
--- a/wger/exercises/migrations/0003_auto_20160921_2000.py
+++ b/wger/exercises/migrations/0003_auto_20160921_2000.py
@@ -6,9 +6,9 @@ from django.db import migrations, models
def copy_name(apps, schema_editor):
- '''
+ """
Copies the exercise name to the original name field
- '''
+ """
Excercise = apps.get_model("exercises", "Exercise")
for exercise in Excercise.objects.all():
exercise.name_original = exercise.name
@@ -16,12 +16,12 @@ def copy_name(apps, schema_editor):
def capitalize_name(apps, schema_editor):
- '''
+ """
Capitalizes the name of the exercises
The algorithm is copied here as it was implemented on the day the migration
was written.
- '''
+ """
def capitalize(input):
out = []
for word in input.split(' '):
diff --git a/wger/exercises/models.py b/wger/exercises/models.py
index 51c4c9b8a..e594e6d46 100644
--- a/wger/exercises/models.py
+++ b/wger/exercises/models.py
@@ -55,9 +55,9 @@ logger = logging.getLogger(__name__)
class Muscle(models.Model):
- '''
+ """
Muscle an exercise works out
- '''
+ """
name = models.CharField(max_length=50,
verbose_name=_('Name'),
@@ -71,49 +71,49 @@ class Muscle(models.Model):
ordering = ["name", ]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
def get_owner_object(self):
- '''
+ """
Muscle has no owner information
- '''
+ """
return False
class Equipment(models.Model):
- '''
+ """
Equipment used or needed by an exercise
- '''
+ """
name = models.CharField(max_length=50,
verbose_name=_('Name'))
class Meta:
- '''
+ """
Set default ordering
- '''
+ """
ordering = ["name", ]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
def get_owner_object(self):
- '''
+ """
Equipment has no owner information
- '''
+ """
return False
class ExerciseCategory(models.Model):
- '''
+ """
Model for an exercise category
- '''
+ """
name = models.CharField(max_length=100,
verbose_name=_('Name'),)
@@ -123,21 +123,21 @@ class ExerciseCategory(models.Model):
ordering = ["name", ]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
def get_owner_object(self):
- '''
+ """
Category has no owner information
- '''
+ """
return False
def save(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
super(ExerciseCategory, self).save(*args, **kwargs)
@@ -147,9 +147,9 @@ class ExerciseCategory(models.Model):
delete_template_fragment_cache('exercise-overview-mobile', language.id)
def delete(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
for language in Language.objects.all():
delete_template_fragment_cache('exercise-overview', language.id)
delete_template_fragment_cache('exercise-overview-mobile', language.id)
@@ -158,12 +158,12 @@ class ExerciseCategory(models.Model):
class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
- '''
+ """
Model for an exercise
- '''
+ """
objects = SubmissionManager()
- '''Custom manager'''
+ """Custom manager"""
category = models.ForeignKey(ExerciseCategory,
verbose_name=_('Category'),
@@ -171,49 +171,49 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
description = models.TextField(max_length=2000,
verbose_name=_('Description'),
validators=[MinLengthValidator(40)])
- '''Description on how to perform the exercise'''
+ """Description on how to perform the exercise"""
name = models.CharField(max_length=200,
verbose_name=_('Name'))
- '''The exercise's name, with correct upercase'''
+ """The exercise's name, with correct upercase"""
name_original = models.CharField(max_length=200,
verbose_name=_('Name'),
default='')
- '''The exercise's name, as entered by the user'''
+ """The exercise's name, as entered by the user"""
muscles = models.ManyToManyField(Muscle,
blank=True,
verbose_name=_('Primary muscles'))
- '''Main muscles trained by the exercise'''
+ """Main muscles trained by the exercise"""
muscles_secondary = models.ManyToManyField(Muscle,
verbose_name=_('Secondary muscles'),
related_name='secondary_muscles',
blank=True)
- '''Secondary muscles trained by the exercise'''
+ """Secondary muscles trained by the exercise"""
equipment = models.ManyToManyField(Equipment,
verbose_name=_('Equipment'),
blank=True)
- '''Equipment needed by this exercise'''
+ """Equipment needed by this exercise"""
creation_date = models.DateField(_('Date'),
auto_now_add=True,
null=True,
blank=True)
- '''The submission date'''
+ """The submission date"""
language = models.ForeignKey(Language,
verbose_name=_('Language'),
on_delete=models.CASCADE)
- '''The exercise's language'''
+ """The exercise's language"""
uuid = models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')
- '''
+ """
Globally unique ID, to identify the exercise across installations
- '''
+ """
#
# Django methods
@@ -223,15 +223,15 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
ordering = ["name", ]
def get_absolute_url(self):
- '''
+ """
Returns the canonical URL to view an exercise
- '''
+ """
return reverse('exercise:exercise:view', kwargs={'id': self.id, 'slug': slugify(self.name)})
def save(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
self.name = smart_capitalize(self.name_original)
super(Exercise, self).save(*args, **kwargs)
@@ -250,9 +250,9 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
reset_workout_canonical_form(set.exerciseday.training_id)
def delete(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
# Cached objects
cache.delete(cache_mapper.get_exercise_muscle_bg_key(self))
@@ -271,9 +271,9 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
super(Exercise, self).delete(*args, **kwargs)
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
#
@@ -282,29 +282,29 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
@property
def main_image(self):
- '''
+ """
Return the main image for the exercise or None if nothing is found
- '''
+ """
return self.exerciseimage_set.accepted().filter(is_main=True).first()
@property
def description_clean(self):
- '''
+ """
Return the exercise description with all markup removed
- '''
+ """
return bleach.clean(self.description, strip=True)
def get_owner_object(self):
- '''
+ """
Exercise has no owner information
- '''
+ """
return False
def send_email(self, request):
- '''
+ """
Sends an email after being successfully added to the database (for user
submitted exercises only)
- '''
+ """
try:
user = User.objects.get(username=self.license_author)
except User.DoesNotExist:
@@ -326,11 +326,11 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
fail_silently=True)
def set_author(self, request):
- '''
+ """
Set author and status
This is only used when creating exercises (via web or API)
- '''
+ """
if request.user.has_perm('exercises.add_exercise'):
self.status = self.STATUS_ACCEPTED
if not self.license_author:
@@ -348,29 +348,29 @@ class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
def exercise_image_upload_dir(instance, filename):
- '''
+ """
Returns the upload target for exercise images
- '''
+ """
return "exercise-images/{0}/{1}".format(instance.exercise.id, filename)
class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
- '''
+ """
Model for an exercise image
- '''
+ """
objects = SubmissionManager()
- '''Custom manager'''
+ """Custom manager"""
exercise = models.ForeignKey(Exercise,
verbose_name=_('Exercise'),
on_delete=models.CASCADE)
- '''The exercise the image belongs to'''
+ """The exercise the image belongs to"""
image = models.ImageField(verbose_name=_('Image'),
help_text=_('Only PNG and JPEG formats are supported'),
upload_to=exercise_image_upload_dir)
- '''Uploaded image'''
+ """Uploaded image"""
is_main = models.BooleanField(verbose_name=_('Main picture'),
default=False,
@@ -378,19 +378,19 @@ class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model)
"main one for the exercise (will be shown e.g. in "
"the search). The first image is automatically "
"marked by the system."))
- '''A flag indicating whether the image is the exercise's main image'''
+ """A flag indicating whether the image is the exercise's main image"""
class Meta:
- '''
+ """
Set default ordering
- '''
+ """
ordering = ['-is_main', 'id']
base_manager_name = 'objects'
def save(self, *args, **kwargs):
- '''
+ """
Only one image can be marked as main picture at a time
- '''
+ """
if self.is_main:
ExerciseImage.objects.filter(exercise=self.exercise).update(is_main=False)
self.is_main = True
@@ -414,9 +414,9 @@ class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model)
super(ExerciseImage, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
super(ExerciseImage, self).delete(*args, **kwargs)
for language in Language.objects.all():
@@ -439,17 +439,17 @@ class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model)
image.save()
def get_owner_object(self):
- '''
+ """
Image has no owner information
- '''
+ """
return False
def set_author(self, request):
- '''
+ """
Set author and status
This is only used when creating images (via web or API)
- '''
+ """
if request.user.has_perm('exercises.add_exerciseimage'):
self.status = self.STATUS_ACCEPTED
if not self.license_author:
@@ -470,9 +470,9 @@ class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model)
class ExerciseComment(models.Model):
- '''
+ """
Model for an exercise comment
- '''
+ """
exercise = models.ForeignKey(Exercise,
verbose_name=_('Exercise'),
editable=False,
@@ -482,31 +482,31 @@ class ExerciseComment(models.Model):
help_text=_('A comment about how to correctly do this exercise.'))
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.comment
def save(self, *args, **kwargs):
- '''
+ """
Reset cached workouts
- '''
+ """
for set in self.exercise.set_set.all():
reset_workout_canonical_form(set.exerciseday.training_id)
super(ExerciseComment, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset cached workouts
- '''
+ """
for set in self.exercise.set_set.all():
reset_workout_canonical_form(set.exerciseday.training.pk)
super(ExerciseComment, self).delete(*args, **kwargs)
def get_owner_object(self):
- '''
+ """
Comment has no owner information
- '''
+ """
return False
diff --git a/wger/exercises/signals.py b/wger/exercises/signals.py
index dd0b6673e..6f40cc1b5 100644
--- a/wger/exercises/signals.py
+++ b/wger/exercises/signals.py
@@ -33,9 +33,9 @@ from wger.exercises.models import ExerciseImage
@receiver(post_delete, sender=ExerciseImage)
def delete_exercise_image_on_delete(sender, instance, **kwargs):
- '''
+ """
Delete the image, along with its thumbnails, from the disk
- '''
+ """
thumbnailer = get_thumbnailer(instance.image)
thumbnailer.delete_thumbnails()
@@ -44,10 +44,10 @@ def delete_exercise_image_on_delete(sender, instance, **kwargs):
@receiver(pre_save, sender=ExerciseImage)
def delete_exercise_image_on_update(sender, instance, **kwargs):
- '''
+ """
Delete the corresponding image from the filesystem when the an ExerciseImage
object was changed
- '''
+ """
if not instance.pk:
return False
diff --git a/wger/exercises/tests/test_categories.py b/wger/exercises/tests/test_categories.py
index f1891d8bd..5f50aab1d 100644
--- a/wger/exercises/tests/test_categories.py
+++ b/wger/exercises/tests/test_categories.py
@@ -30,21 +30,21 @@ from wger.utils.cache import get_template_cache_name
class ExerciseCategoryRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(ExerciseCategory.objects.get(pk=1)), 'Category')
class CategoryOverviewTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test that only admins see the edit links
- '''
+ """
url = 'exercise:category:list'
anonymous_fail = True
user_success = 'admin'
@@ -62,9 +62,9 @@ class CategoryOverviewTestCase(WorkoutManagerAccessTestCase):
class DeleteExerciseCategoryTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Exercise category delete test case
- '''
+ """
object_class = ExerciseCategory
url = 'exercise:category:delete'
@@ -74,9 +74,9 @@ class DeleteExerciseCategoryTestCase(WorkoutManagerDeleteTestCase):
class EditExerciseCategoryTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing an exercise category
- '''
+ """
object_class = ExerciseCategory
url = 'exercise:category:edit'
@@ -85,9 +85,9 @@ class EditExerciseCategoryTestCase(WorkoutManagerEditTestCase):
class AddExerciseCategoryTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding an exercise category
- '''
+ """
object_class = ExerciseCategory
url = 'exercise:category:add'
@@ -95,15 +95,15 @@ class AddExerciseCategoryTestCase(WorkoutManagerAddTestCase):
class ExerciseCategoryCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Cache test case
- '''
+ """
def test_overview_cache_update(self):
- '''
+ """
Test that the template cache for the overview is correctly reseted when
performing certain operations
- '''
+ """
self.client.get(reverse('exercise:exercise:overview'))
self.client.get(reverse('exercise:exercise:view', kwargs={'id': 2}))
@@ -134,9 +134,9 @@ class ExerciseCategoryCacheTestCase(WorkoutManagerTestCase):
class ExerciseCategoryApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the exercise category overview resource
- '''
+ """
pk = 2
resource = ExerciseCategory
private_resource = False
diff --git a/wger/exercises/tests/test_corrected_exercise.py b/wger/exercises/tests/test_corrected_exercise.py
index 5c2923f65..90a277f34 100644
--- a/wger/exercises/tests/test_corrected_exercise.py
+++ b/wger/exercises/tests/test_corrected_exercise.py
@@ -22,14 +22,14 @@ from wger.exercises.models import Exercise
class ExercisesCorrectionTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests correcting an existing exercise
- '''
+ """
def correct_exercise(self, fail=True):
- '''
+ """
Helper function
- '''
+ """
description = 'a nice, long and accurate description for the exercise'
response = self.client.post(reverse('exercise:exercise:correct', kwargs={'pk': 1}),
{'category': 3,
@@ -62,21 +62,21 @@ class ExercisesCorrectionTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 1)
def test_correct_exercise_logged_in_user(self):
- '''
+ """
Tests correcting an existing exercise as a logged in user
- '''
+ """
self.user_login('test')
self.correct_exercise(fail=False)
def test_correct_exercise_guest_user(self):
- '''
+ """
Tests correcting an existing exercise as a guest user
- '''
+ """
self.user_login('demo')
self.correct_exercise(fail=True)
def test_correct_exercise_anonymous(self):
- '''
+ """
Tests correcting an existing exercise as an anonymous user
- '''
+ """
self.correct_exercise(fail=True)
diff --git a/wger/exercises/tests/test_equipment.py b/wger/exercises/tests/test_equipment.py
index 8dfa2c2fb..a1196f7be 100644
--- a/wger/exercises/tests/test_equipment.py
+++ b/wger/exercises/tests/test_equipment.py
@@ -34,21 +34,21 @@ from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE
class EquipmentRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Equipment.objects.get(pk=1)), 'Dumbbells')
class EquipmentShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
url = reverse('exercise:equipment:overview')
@@ -66,9 +66,9 @@ class EquipmentShareButtonTestCase(WorkoutManagerTestCase):
class AddEquipmentTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new equipment
- '''
+ """
object_class = Equipment
url = 'exercise:equipment:add'
@@ -76,9 +76,9 @@ class AddEquipmentTestCase(WorkoutManagerAddTestCase):
class DeleteEquipmentTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting an equipment
- '''
+ """
object_class = Equipment
url = 'exercise:equipment:delete'
@@ -86,9 +86,9 @@ class DeleteEquipmentTestCase(WorkoutManagerDeleteTestCase):
class EditEquipmentTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing an equipment
- '''
+ """
object_class = Equipment
url = 'exercise:equipment:edit'
@@ -97,9 +97,9 @@ class EditEquipmentTestCase(WorkoutManagerEditTestCase):
class EquipmentListTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the equipment list page (admin view)
- '''
+ """
def test_overview(self):
@@ -136,14 +136,14 @@ class EquipmentListTestCase(WorkoutManagerTestCase):
class EquipmentCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Equipment cache test case
- '''
+ """
def test_equipment_overview(self):
- '''
+ """
Test the equipment overview cache is correctly generated on visit
- '''
+ """
if self.is_mobile:
self.client.get(reverse('exercise:equipment:overview'))
else:
@@ -152,10 +152,10 @@ class EquipmentCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(get_template_cache_name('equipment-overview', 2)))
def test_equipmet_cache_update(self):
- '''
+ """
Test that the template cache for the overview is correctly reseted when
performing certain operations
- '''
+ """
self.assertFalse(cache.get(get_template_cache_name('equipment-overview', 2)))
@@ -181,9 +181,9 @@ class EquipmentCacheTestCase(WorkoutManagerTestCase):
class EquipmentApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the equipment overview resource
- '''
+ """
pk = 1
resource = Equipment
private_resource = False
diff --git a/wger/exercises/tests/test_exercise.py b/wger/exercises/tests/test_exercise.py
index be824602d..d48f56c3d 100644
--- a/wger/exercises/tests/test_exercise.py
+++ b/wger/exercises/tests/test_exercise.py
@@ -38,21 +38,21 @@ from wger.utils.cache import (
class ExerciseRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Exercise.objects.get(pk=1)), 'An exercise')
class ExerciseShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
exercise = Exercise.objects.get(pk=1)
@@ -73,9 +73,9 @@ class ExerciseShareButtonTestCase(WorkoutManagerTestCase):
class ExerciseIndexTestCase(WorkoutManagerTestCase):
def exercise_index(self, logged_in=True, demo=False, admin=False):
- '''
+ """
Tests the exercise overview page
- '''
+ """
response = self.client.get(reverse('exercise:exercise:overview'))
@@ -117,40 +117,40 @@ class ExerciseIndexTestCase(WorkoutManagerTestCase):
self.assertContains(response, 'Only registered users can do this')
def test_exercise_index_editor(self):
- '''
+ """
Tests the exercise overview page as a logged in user with editor rights
- '''
+ """
self.user_login('admin')
self.exercise_index(admin=True)
def test_exercise_index_non_editor(self):
- '''
+ """
Tests the exercise overview page as a logged in user without editor rights
- '''
+ """
self.user_login('test')
self.exercise_index()
def test_exercise_index_demo_user(self):
- '''
+ """
Tests the exercise overview page as a logged in demo user
- '''
+ """
self.user_login('demo')
self.exercise_index(demo=True)
def test_exercise_index_logged_out(self):
- '''
+ """
Tests the exercise overview page as an anonymous (logged out) user
- '''
+ """
self.exercise_index(logged_in=False)
def test_empty_exercise_index(self):
- '''
+ """
Test the index when there are no categories
- '''
+ """
self.user_login('admin')
ExerciseCategory.objects.all().delete()
response = self.client.get(reverse('exercise:exercise:overview'))
@@ -159,14 +159,14 @@ class ExerciseIndexTestCase(WorkoutManagerTestCase):
class ExerciseDetailTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the exercise details page
- '''
+ """
def exercise_detail(self, editor=False):
- '''
+ """
Tests the exercise details page
- '''
+ """
response = self.client.get(reverse('exercise:exercise:view', kwargs={'id': 1}))
self.assertEqual(response.status_code, 200)
@@ -202,38 +202,38 @@ class ExerciseDetailTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 404)
def test_exercise_detail_editor(self):
- '''
+ """
Tests the exercise details page as a logged in user with editor rights
- '''
+ """
self.user_login('admin')
self.exercise_detail(editor=True)
def test_exercise_detail_non_editor(self):
- '''
+ """
Tests the exercise details page as a logged in user without editor rights
- '''
+ """
self.user_login('test')
self.exercise_detail(editor=False)
def test_exercise_detail_logged_out(self):
- '''
+ """
Tests the exercise details page as an anonymous (logged out) user
- '''
+ """
self.exercise_detail(editor=False)
class ExercisesTestCase(WorkoutManagerTestCase):
- '''
+ """
Exercise test case
- '''
+ """
def add_exercise_user_fail(self):
- '''
+ """
Helper function to test adding exercises by users that aren't authorized
- '''
+ """
# Add an exercise
count_before = Exercise.objects.count()
@@ -249,26 +249,26 @@ class ExercisesTestCase(WorkoutManagerTestCase):
self.assertEqual(count_before, count_after)
def test_add_exercise_temp_user(self):
- '''
+ """
Tests adding an exercise with a logged in demo user
- '''
+ """
self.user_login('demo')
self.add_exercise_user_fail()
def test_add_exercise_no_user(self):
- '''
+ """
Tests adding an exercise with a logged out (anonymous) user
- '''
+ """
self.user_logout()
self.add_exercise_user_fail()
self.user_logout()
def add_exercise_success(self, admin=False):
- '''
+ """
Tests adding/editing an exercise with a user with enough rights to do this
- '''
+ """
# Add an exercise
count_before = Exercise.objects.count()
@@ -344,24 +344,24 @@ class ExercisesTestCase(WorkoutManagerTestCase):
self.assertIn(response.status_code, STATUS_CODES_FAIL)
def test_add_exercise_success(self):
- '''
+ """
Tests adding/editing an exercise with a user with enough rights to do this
- '''
+ """
self.user_login('admin')
self.add_exercise_success(admin=True)
def test_add_exercise_user_no_rights(self):
- '''
+ """
Tests adding an exercise with a user without enough rights to do this
- '''
+ """
self.user_login('test')
self.add_exercise_success(admin=False)
self.assertEqual(len(mail.outbox), 1)
def search_exercise(self, fail=True):
- '''
+ """
Helper function to test searching for exercises
- '''
+ """
# 1 hit, "Very cool exercise"
response = self.client.get(reverse('exercise-search'),
@@ -383,25 +383,25 @@ class ExercisesTestCase(WorkoutManagerTestCase):
self.assertEqual(len(result['suggestions']), 0)
def test_search_exercise_anonymous(self):
- '''
+ """
Test deleting an exercise by an anonymous user
- '''
+ """
self.search_exercise()
def test_search_exercise_logged_in(self):
- '''
+ """
Test deleting an exercise by a logged in user
- '''
+ """
self.user_login('test')
self.search_exercise()
class DeleteExercisesTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Exercise test case
- '''
+ """
object_class = Exercise
url = 'exercise:exercise:delete'
@@ -411,14 +411,14 @@ class DeleteExercisesTestCase(WorkoutManagerDeleteTestCase):
class ExercisesCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Exercise cache test case
- '''
+ """
def test_exercise_overview(self):
- '''
+ """
Test the exercise overview cache is correctly generated on visit
- '''
+ """
if self.is_mobile:
self.assertFalse(cache.get(get_template_cache_name('exercise-overview-mobile', 2)))
self.client.get(reverse('exercise:exercise:overview'))
@@ -429,15 +429,15 @@ class ExercisesCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(get_template_cache_name('exercise-overview', 2)))
def test_exercise_detail(self):
- '''
+ """
Test that the exercise detail cache is correctly generated on visit
- '''
+ """
def test_overview_cache_update(self):
- '''
+ """
Test that the template cache for the overview is correctly reseted when
performing certain operations
- '''
+ """
self.assertFalse(cache.get(cache_mapper.get_exercise_muscle_bg_key(2)))
self.assertFalse(cache.get(get_template_cache_name('muscle-overview', 2)))
self.assertFalse(cache.get(get_template_cache_name('muscle-overview-mobile', 2)))
@@ -482,10 +482,10 @@ class ExercisesCacheTestCase(WorkoutManagerTestCase):
self.assertNotEqual(old_exercise_overview_mobile, new_exercise_overview_mobile)
def test_muscles_cache_update_on_delete(self):
- '''
+ """
Test that the template cache for the overview is correctly reset when
performing certain operations
- '''
+ """
self.assertFalse(cache.get(get_template_cache_name('exercise-detail-muscles', 2, 2)))
self.client.get(reverse('exercise:exercise:view', kwargs={'id': 2}))
self.assertTrue(cache.get(get_template_cache_name('exercise-detail-muscles', 2, 2)))
@@ -495,10 +495,10 @@ class ExercisesCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(get_template_cache_name('exercise-detail-muscles', 2, 2)))
def test_muscles_cache_update_on_update(self):
- '''
+ """
Test that the template cache for the overview is correctly reset when
performing certain operations
- '''
+ """
self.assertFalse(cache.get(get_template_cache_name('exercise-detail-muscles', 2, 2)))
self.client.get(reverse('exercise:exercise:view', kwargs={'id': 2}))
self.assertTrue(cache.get(get_template_cache_name('exercise-detail-muscles', 2, 2)))
@@ -510,14 +510,14 @@ class ExercisesCacheTestCase(WorkoutManagerTestCase):
class WorkoutCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Workout cache test case
- '''
+ """
def test_canonical_form_cache_save(self):
- '''
+ """
Tests the workout cache when saving
- '''
+ """
exercise = Exercise.objects.get(pk=2)
for set in exercise.set_set.all():
set.exerciseday.training.canonical_representation
@@ -528,9 +528,9 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_canonical(workout_id)))
def test_canonical_form_cache_delete(self):
- '''
+ """
Tests the workout cache when deleting
- '''
+ """
exercise = Exercise.objects.get(pk=2)
workout_ids = []
@@ -547,9 +547,9 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
# TODO: fix test, all registered users can upload exercises
# class ExerciseApiTestCase(api_base_test.ApiBaseResourceTestCase):
-# '''
+# """
# Tests the exercise overview resource
-# '''
+# """
# pk = 1
# resource = Exercise
# private_resource = False
diff --git a/wger/exercises/tests/test_exercise_comments.py b/wger/exercises/tests/test_exercise_comments.py
index a96dd18c8..3f5573c08 100644
--- a/wger/exercises/tests/test_exercise_comments.py
+++ b/wger/exercises/tests/test_exercise_comments.py
@@ -32,21 +32,21 @@ from wger.utils.cache import cache_mapper
class ExerciseCommentRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(ExerciseComment.objects.get(pk=1)), 'test 123')
class AddExerciseCommentTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a comment to an exercise
- '''
+ """
object_class = ExerciseComment
url = reverse('exercise:comment:add', kwargs={'exercise_pk': 1})
@@ -55,9 +55,9 @@ class AddExerciseCommentTestCase(WorkoutManagerAddTestCase):
class EditExerciseCommentTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a comment to an exercise
- '''
+ """
object_class = ExerciseComment
url = 'exercise:comment:edit'
@@ -68,9 +68,9 @@ class EditExerciseCommentTestCase(WorkoutManagerEditTestCase):
class ExercisecommentsTestCase(WorkoutManagerTestCase):
def exercise_delete_comment(self, fail=True):
- '''
+ """
Tests the deletion of exercise comments
- '''
+ """
# Load the exercise
exercise_1 = Exercise.objects.get(pk=1)
@@ -95,39 +95,39 @@ class ExercisecommentsTestCase(WorkoutManagerTestCase):
self.assertEqual(len(comments), 0)
def test_exercise_delete_comment_no_authorized(self):
- '''
+ """
Tests the exercise comments
- '''
+ """
self.user_login('test')
self.exercise_delete_comment(fail=True)
self.user_logout()
def test_exercise_delete_comment_not_logged_in(self):
- '''
+ """
Tests the exercise comments
- '''
+ """
self.exercise_delete_comment(fail=True)
def test_exercise_delete_comment_authorized(self):
- '''
+ """
Tests the exercise comments
- '''
+ """
self.user_login()
self.exercise_delete_comment(fail=False)
class WorkoutCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Workout cache test case
- '''
+ """
def test_canonical_form_cache_save(self):
- '''
+ """
Tests the workout cache when saving
- '''
+ """
comment = ExerciseComment.objects.get(pk=1)
for set in comment.exercise.set_set.all():
set.exerciseday.training.canonical_representation
@@ -138,9 +138,9 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_canonical(workout_id)))
def test_canonical_form_cache_delete(self):
- '''
+ """
Tests the workout cache when deleting
- '''
+ """
comment = ExerciseComment.objects.get(pk=1)
workout_ids = []
@@ -156,9 +156,9 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
class ExerciseCommentApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the exercise comment overview resource
- '''
+ """
pk = 1
resource = ExerciseComment
private_resource = False
diff --git a/wger/exercises/tests/test_exercise_images.py b/wger/exercises/tests/test_exercise_images.py
index 5b481c7f9..8cfe69eb9 100644
--- a/wger/exercises/tests/test_exercise_images.py
+++ b/wger/exercises/tests/test_exercise_images.py
@@ -30,14 +30,14 @@ from wger.exercises.models import (
class MainImageTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the methods to make sure there is always a main image per picture
- '''
+ """
def save_image(self, exercise, filename, db_filename=None):
- '''
+ """
Helper function to save an image to an exercise
- '''
+ """
with open('wger/exercises/tests/{0}'.format(filename), 'rb') as inFile:
if not db_filename:
db_filename = filename
@@ -52,9 +52,9 @@ class MainImageTestCase(WorkoutManagerTestCase):
return(image.pk)
def test_auto_main_image(self):
- '''
+ """
Tests that the first uploaded image is automatically a main image
- '''
+ """
exercise = Exercise.objects.get(pk=2)
pk = self.save_image(exercise, 'protestschwein.jpg')
@@ -63,9 +63,9 @@ class MainImageTestCase(WorkoutManagerTestCase):
self.assertTrue(image.is_main)
def test_auto_main_image_multiple(self):
- '''
+ """
Tests that there is always a main image after deleting one
- '''
+ """
exercise = Exercise.objects.get(pk=2)
pk1 = self.save_image(exercise, 'protestschwein.jpg')
@@ -78,9 +78,9 @@ class MainImageTestCase(WorkoutManagerTestCase):
self.assertFalse(image.is_main)
def test_delete_main_image(self):
- '''
+ """
Tests that there is always a main image after deleting one
- '''
+ """
exercise = Exercise.objects.get(pk=2)
pk1 = self.save_image(exercise, 'protestschwein.jpg')
@@ -108,9 +108,9 @@ class MainImageTestCase(WorkoutManagerTestCase):
class AddExerciseImageTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding an image to an exercise
- '''
+ """
object_class = ExerciseImage
url = reverse('exercise:image:add', kwargs={'exercise_pk': 1})
@@ -121,9 +121,9 @@ class AddExerciseImageTestCase(WorkoutManagerAddTestCase):
class EditExerciseImageTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing an image to an exercise
- '''
+ """
object_class = ExerciseImage
url = 'exercise:image:edit'
@@ -133,9 +133,9 @@ class EditExerciseImageTestCase(WorkoutManagerEditTestCase):
class DeleteExerciseImageTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting an image to an exercise
- '''
+ """
object_class = ExerciseImage
url = reverse('exercise:image:delete', kwargs={'exercise_pk': 1, 'pk': 1})
@@ -144,9 +144,9 @@ class DeleteExerciseImageTestCase(WorkoutManagerDeleteTestCase):
# TODO: fix test
# class ExerciseImagesApiTestCase(api_base_test.ApiBaseResourceTestCase):
-# '''
+# """
# Tests the exercise image overview resource
-# '''
+# """
# pk = 1
# resource = ExerciseImage
# private_resource = False
diff --git a/wger/exercises/tests/test_muscles.py b/wger/exercises/tests/test_muscles.py
index d6a4b6198..76ad1aefa 100644
--- a/wger/exercises/tests/test_muscles.py
+++ b/wger/exercises/tests/test_muscles.py
@@ -31,21 +31,21 @@ from wger.utils.cache import get_template_cache_name
class MuscleRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Muscle.objects.get(pk=1)), 'Anterior testoid')
class MuscleAdminOverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests the admin muscle overview page
- '''
+ """
url = 'exercise:muscle:admin-list'
anonymous_fail = True
user_success = 'admin'
@@ -63,9 +63,9 @@ class MuscleAdminOverviewTest(WorkoutManagerAccessTestCase):
class MusclesShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
url = reverse('exercise:muscle:overview')
@@ -83,9 +83,9 @@ class MusclesShareButtonTestCase(WorkoutManagerTestCase):
class AddMuscleTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a muscle
- '''
+ """
object_class = Muscle
url = 'exercise:muscle:add'
@@ -94,9 +94,9 @@ class AddMuscleTestCase(WorkoutManagerAddTestCase):
class EditMuscleTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a muscle
- '''
+ """
object_class = Muscle
url = 'exercise:muscle:edit'
@@ -106,9 +106,9 @@ class EditMuscleTestCase(WorkoutManagerEditTestCase):
class DeleteMuscleTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a muscle
- '''
+ """
object_class = Muscle
url = 'exercise:muscle:delete'
@@ -116,14 +116,14 @@ class DeleteMuscleTestCase(WorkoutManagerDeleteTestCase):
class MuscleCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Muscle cache test case
- '''
+ """
def test_overview(self):
- '''
+ """
Test the muscle overview cache is correctly generated on visit
- '''
+ """
if not self.is_mobile:
self.assertFalse(cache.get(get_template_cache_name('muscle-overview', 2)))
@@ -132,18 +132,18 @@ class MuscleCacheTestCase(WorkoutManagerTestCase):
class MuscleOverviewTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test that only admins see the edit links
- '''
+ """
url = 'exercise:muscle:overview'
anonymous_fail = False
user_fail = []
class MuscleApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the muscle overview resource
- '''
+ """
pk = 1
resource = Muscle
private_resource = False
diff --git a/wger/exercises/tests/test_submitted_exercise.py b/wger/exercises/tests/test_submitted_exercise.py
index f650ff913..ec33cc5b4 100644
--- a/wger/exercises/tests/test_submitted_exercise.py
+++ b/wger/exercises/tests/test_submitted_exercise.py
@@ -25,14 +25,14 @@ from wger.exercises.models import Exercise
class ExercisesPendingTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the pending exercises overview page
- '''
+ """
def pending_overview(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('exercise:exercise:pending'))
if not fail:
self.assertEqual(response.status_code, 200)
@@ -41,38 +41,38 @@ class ExercisesPendingTestCase(WorkoutManagerTestCase):
self.assertIn(response.status_code, STATUS_CODES_FAIL)
def test_pending_overview_admin(self):
- '''
+ """
Tests the pending exercises overview page as an admin user
- '''
+ """
self.user_login('admin')
self.pending_overview()
def test_pending_overview_user(self):
- '''
+ """
Tests the pending exercises overview page as a regular user
- '''
+ """
self.user_login('test')
self.pending_overview(fail=True)
def test_pending_overview_logged_out(self):
- '''
+ """
Tests the pending exercises overview page as a logged out user
- '''
+ """
self.pending_overview(fail=True)
class ExercisesPendingDetailTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the detail page of a pending exercise
- '''
+ """
def pending_view(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('exercise:exercise:view', kwargs={'id': 4}))
self.assertContains(response, 'Exercise is pending review')
@@ -87,38 +87,38 @@ class ExercisesPendingDetailTestCase(WorkoutManagerTestCase):
self.assertNotContains(response, 'Decline')
def test_pending_view_admin(self):
- '''
+ """
Tests the detail page of a pending exercise as an admin user
- '''
+ """
self.user_login('admin')
self.pending_view()
def test_pending_view_user(self):
- '''
+ """
Tests the detail page of a pending exercise as a regular user
- '''
+ """
self.user_login('test')
self.pending_view(fail=True)
def test_pending_view_logged_out(self):
- '''
+ """
Tests the detail page of a pending exercise as a logged out user
- '''
+ """
self.pending_view(fail=True)
class ExerciseAcceptTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests accepting a user submitted exercise
- '''
+ """
def accept(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
exercise = Exercise.objects.get(pk=4)
self.assertEqual(exercise.status, Exercise.STATUS_PENDING)
response = self.client.get(reverse('exercise:exercise:accept', kwargs={'pk': 4}))
@@ -136,38 +136,38 @@ class ExerciseAcceptTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_accept_admin(self):
- '''
+ """
Tests accepting a user submitted exercise as an admin user
- '''
+ """
self.user_login('admin')
self.accept()
def test_accept_user(self):
- '''
+ """
Tests accepting a user submitted exercise as a regular user
- '''
+ """
self.user_login('test')
self.accept(fail=True)
def test_accept_logged_out(self):
- '''
+ """
Tests accepting a user submitted exercise as a logged out user
- '''
+ """
self.accept(fail=True)
class ExerciseRejectTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests rejecting a user submitted exercise
- '''
+ """
def reject(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
exercise = Exercise.objects.get(pk=4)
self.assertEqual(exercise.status, Exercise.STATUS_PENDING)
response = self.client.get(reverse('exercise:exercise:decline', kwargs={'pk': 4}))
@@ -183,24 +183,24 @@ class ExerciseRejectTestCase(WorkoutManagerTestCase):
self.assertEqual(exercise.status, Exercise.STATUS_PENDING)
def test_reject_admin(self):
- '''
+ """
Tests rejecting a user submitted exercise as an admin user
- '''
+ """
self.user_login('admin')
self.reject()
def test_reject_user(self):
- '''
+ """
Tests rejecting a user submitted exercise as a regular user
- '''
+ """
self.user_login('test')
self.reject(fail=True)
def test_reject_logged_out(self):
- '''
+ """
Tests rejecting a user submitted exercise as a logged out user
- '''
+ """
self.reject(fail=True)
diff --git a/wger/exercises/tests/test_submitted_image.py b/wger/exercises/tests/test_submitted_image.py
index 53eb568e5..6ea0f14d0 100644
--- a/wger/exercises/tests/test_submitted_image.py
+++ b/wger/exercises/tests/test_submitted_image.py
@@ -22,14 +22,14 @@ from wger.exercises.models import ExerciseImage
class ImagePendingDetailTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the detail page of an exercise with a pending image
- '''
+ """
def pending_view(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('exercise:exercise:view', kwargs={'id': 2}))
self.assertEqual(response.status_code, 200)
@@ -43,38 +43,38 @@ class ImagePendingDetailTestCase(WorkoutManagerTestCase):
self.assertNotContains(response, 'Decline')
def test_pending_view_admin(self):
- '''
+ """
Tests the detail page of an exercise with a pending image as an admin user
- '''
+ """
self.user_login('admin')
self.pending_view()
def test_pending_view_user(self):
- '''
+ """
Tests the detail page of an exercise with a pending image as a regular user
- '''
+ """
self.user_login('test')
self.pending_view(fail=True)
def test_pending_view_logged_out(self):
- '''
+ """
Tests the detail page of an exercise with a pending image as a logged out user
- '''
+ """
self.pending_view(fail=True)
class ImageAcceptTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests accepting a user submitted exercise image
- '''
+ """
def accept(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
image = ExerciseImage.objects.get(pk=3)
self.assertEqual(image.status, ExerciseImage.STATUS_PENDING)
response = self.client.get(reverse('exercise:image:accept', kwargs={'pk': 3}))
@@ -91,38 +91,38 @@ class ImageAcceptTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_accept_admin(self):
- '''
+ """
Tests accepting a user submitted exercise image as an admin user
- '''
+ """
self.user_login('admin')
self.accept()
def test_accept_user(self):
- '''
+ """
Tests accepting a user submitted exercise image as a regular user
- '''
+ """
self.user_login('test')
self.accept(fail=True)
def test_accept_logged_out(self):
- '''
+ """
Tests accepting a user submitted exercise as a logged out user
- '''
+ """
self.accept(fail=True)
class ImageRejectTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests rejecting a user submitted exercise image
- '''
+ """
def reject(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
image = ExerciseImage.objects.get(pk=3)
self.assertEqual(image.status, ExerciseImage.STATUS_PENDING)
response = self.client.get(reverse('exercise:image:decline', kwargs={'pk': 3}))
@@ -138,24 +138,24 @@ class ImageRejectTestCase(WorkoutManagerTestCase):
self.assertEqual(image.status, ExerciseImage.STATUS_PENDING)
def test_reject_admin(self):
- '''
+ """
Tests rejecting a user submitted exercise image as an admin user
- '''
+ """
self.user_login('admin')
self.reject()
def test_reject_user(self):
- '''
+ """
Tests rejecting a user submitted exercise image as a regular user
- '''
+ """
self.user_login('test')
self.reject(fail=True)
def test_reject_logged_out(self):
- '''
+ """
Tests rejecting a user submitted exercise image as a logged out user
- '''
+ """
self.reject(fail=True)
diff --git a/wger/exercises/views/categories.py b/wger/exercises/views/categories.py
index ecebd051b..3d8bf9a34 100644
--- a/wger/exercises/views/categories.py
+++ b/wger/exercises/views/categories.py
@@ -52,9 +52,9 @@ logger = logging.getLogger(__name__)
class ExerciseCategoryListView(LoginRequiredMixin, PermissionRequiredMixin,
UAAwareViewMixin, ListView):
- '''
+ """
Overview of all categories, for administration purposes
- '''
+ """
model = ExerciseCategory
permission_required = 'exercises.change_exercisecategory'
template_name = 'categories/admin-overview.html'
@@ -64,9 +64,9 @@ class ExerciseCategoryAddView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
CreateView):
- '''
+ """
Generic view to add a new exercise category
- '''
+ """
model = ExerciseCategory
fields = '__all__'
@@ -84,9 +84,9 @@ class ExerciseCategoryUpdateView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
UpdateView):
- '''
+ """
Generic view to update an existing exercise category
- '''
+ """
model = ExerciseCategory
fields = '__all__'
@@ -111,9 +111,9 @@ class ExerciseCategoryDeleteView(WgerDeleteMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
DeleteView):
- '''
+ """
Generic view to delete an existing exercise category
- '''
+ """
model = ExerciseCategory
fields = ('name',)
diff --git a/wger/exercises/views/comments.py b/wger/exercises/views/comments.py
index b66d5261c..844c28865 100644
--- a/wger/exercises/views/comments.py
+++ b/wger/exercises/views/comments.py
@@ -53,9 +53,9 @@ class ExerciseCommentEditView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
UpdateView):
- '''
+ """
Generic view to update an existing exercise comment
- '''
+ """
model = ExerciseComment
form_class = CommentForm
@@ -78,9 +78,9 @@ class ExerciseCommentAddView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
CreateView):
- '''
+ """
Generic view to add a new exercise comment
- '''
+ """
model = ExerciseComment
form_class = CommentForm
@@ -95,9 +95,9 @@ class ExerciseCommentAddView(WgerFormMixin,
return reverse('exercise:exercise:view', kwargs={'id': self.object.exercise.id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ExerciseCommentAddView, self).get_context_data(**kwargs)
context['form_action'] = reverse('exercise:comment:add',
kwargs={'exercise_pk': self.kwargs['exercise_pk']})
diff --git a/wger/exercises/views/equipment.py b/wger/exercises/views/equipment.py
index aff554757..d2dd813d4 100644
--- a/wger/exercises/views/equipment.py
+++ b/wger/exercises/views/equipment.py
@@ -51,15 +51,15 @@ from wger.utils.language import load_item_languages
logger = logging.getLogger(__name__)
-'''
+"""
Exercise equipment
-'''
+"""
class EquipmentListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Generic view to list all equipments
- '''
+ """
model = Equipment
fields = '__all__'
@@ -70,9 +70,9 @@ class EquipmentListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareView
class EquipmentEditView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
Generic view to update an existing equipment item
- '''
+ """
model = Equipment
fields = ['name']
@@ -90,9 +90,9 @@ class EquipmentEditView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMix
class EquipmentAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
Generic view to add a new equipment item
- '''
+ """
model = Equipment
fields = ['name']
@@ -101,9 +101,9 @@ class EquipmentAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixi
success_url = reverse_lazy('exercise:equipment:list')
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(EquipmentAddView, self).get_context_data(**kwargs)
context['form_action'] = reverse('exercise:equipment:add')
@@ -111,9 +111,9 @@ class EquipmentAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixi
class EquipmentDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
Generic view to delete an existing exercise image
- '''
+ """
model = Equipment
fields = ('name',)
@@ -122,9 +122,9 @@ class EquipmentDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequire
success_url = reverse_lazy('exercise:equipment:list')
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
pk = self.kwargs['pk']
context = super(EquipmentDeleteView, self).get_context_data(**kwargs)
@@ -136,18 +136,18 @@ class EquipmentDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequire
class EquipmentOverviewView(UAAwareViewMixin, ListView):
- '''
+ """
Overview with all exercises, group by equipment
- '''
+ """
model = Equipment
template_name = 'equipment/overview.html'
context_object_name = 'equipment_list'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(EquipmentOverviewView, self).get_context_data(**kwargs)
context['exercise_languages'] = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)
for equipment in context['equipment_list']:
diff --git a/wger/exercises/views/exercises.py b/wger/exercises/views/exercises.py
index 4ab5fbc70..3fce4aa99 100644
--- a/wger/exercises/views/exercises.py
+++ b/wger/exercises/views/exercises.py
@@ -85,9 +85,9 @@ logger = logging.getLogger(__name__)
class ExerciseListView(UAAwareViewMixin, ListView):
- '''
+ """
Generic view to list all exercises
- '''
+ """
model = Exercise
template_name = 'exercise/overview.html'
@@ -99,9 +99,9 @@ class ExerciseListView(UAAwareViewMixin, ListView):
return response
def get_queryset(self):
- '''
+ """
Filter to only active exercises in the configured languages
- '''
+ """
languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)
return Exercise.objects.accepted() \
.filter(language__in=languages) \
@@ -109,18 +109,18 @@ class ExerciseListView(UAAwareViewMixin, ListView):
.select_related()
def get_context_data(self, **kwargs):
- '''
+ """
Pass additional data to the template
- '''
+ """
context = super(ExerciseListView, self).get_context_data(**kwargs)
context['show_shariff'] = True
return context
def view(request, id, slug=None):
- '''
+ """
Detail view for an exercise
- '''
+ """
template_data = {}
template_data['comment_edit'] = False
@@ -176,10 +176,10 @@ def view(request, id, slug=None):
class ExercisesEditAddView(WgerFormMixin):
- '''
+ """
Generic view to subclass from for exercise adding and editing, since they
share all this settings
- '''
+ """
model = Exercise
sidebar = 'exercise/form.html'
title = ugettext_lazy('Add exercise')
@@ -224,9 +224,9 @@ class ExerciseUpdateView(ExercisesEditAddView,
LoginRequiredMixin,
PermissionRequiredMixin,
UpdateView):
- '''
+ """
Generic view to update an existing exercise
- '''
+ """
permission_required = 'exercises.change_exercise'
def get_context_data(self, **kwargs):
@@ -238,24 +238,24 @@ class ExerciseUpdateView(ExercisesEditAddView,
class ExerciseAddView(ExercisesEditAddView, LoginRequiredMixin, CreateView):
- '''
+ """
Generic view to add a new exercise
- '''
+ """
form_action = reverse_lazy('exercise:exercise:add')
def form_valid(self, form):
- '''
+ """
Set language, author and status
- '''
+ """
form.instance.language = load_language()
form.instance.set_author(self.request)
return super(ExerciseAddView, self).form_valid(form)
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Demo users can't submit exercises
- '''
+ """
if request.user.userprofile.is_temporary:
return HttpResponseForbidden()
@@ -263,16 +263,16 @@ class ExerciseAddView(ExercisesEditAddView, LoginRequiredMixin, CreateView):
class ExerciseCorrectView(ExercisesEditAddView, LoginRequiredMixin, UpdateView):
- '''
+ """
Generic view to update an existing exercise
- '''
+ """
sidebar = 'exercise/form_correct.html'
messages = _('Thank you. Once the changes are reviewed the exercise will be updated.')
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only registered users can correct exercises
- '''
+ """
if not request.user.is_authenticated or request.user.userprofile.is_temporary:
return HttpResponseForbidden()
@@ -285,12 +285,12 @@ class ExerciseCorrectView(ExercisesEditAddView, LoginRequiredMixin, UpdateView):
return context
def form_valid(self, form):
- '''
+ """
If the form is valid send email notifications to the site administrators.
We don't return the super().form_valid because we don't want the data
to be saved.
- '''
+ """
subject = 'Correction submitted for exercise #{0}'.format(self.get_object().pk)
context = {
'exercise': self.get_object(),
@@ -311,9 +311,9 @@ class ExerciseDeleteView(WgerDeleteMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
DeleteView):
- '''
+ """
Generic view to delete an existing exercise
- '''
+ """
model = Exercise
fields = ('category',
@@ -328,9 +328,9 @@ class ExerciseDeleteView(WgerDeleteMixin,
permission_required = 'exercises.delete_exercise'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ExerciseDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object.name)
context['form_action'] = reverse('exercise:exercise:delete',
@@ -341,9 +341,9 @@ class ExerciseDeleteView(WgerDeleteMixin,
class PendingExerciseListView(LoginRequiredMixin, PermissionRequiredMixin,
UAAwareViewMixin, ListView):
- '''
+ """
Generic view to list all weight units
- '''
+ """
model = Exercise
template_name = 'exercise/pending.html'
@@ -351,17 +351,17 @@ class PendingExerciseListView(LoginRequiredMixin, PermissionRequiredMixin,
permission_required = 'exercises.change_exercise'
def get_queryset(self):
- '''
+ """
Only show pending exercises
- '''
+ """
return Exercise.objects.pending().order_by('-creation_date')
@permission_required('exercises.add_exercise')
def accept(request, pk):
- '''
+ """
Accepts a pending user submitted exercise and emails the user, if possible
- '''
+ """
exercise = get_object_or_404(Exercise, pk=pk)
exercise.status = Exercise.STATUS_ACCEPTED
exercise.save()
@@ -373,9 +373,9 @@ def accept(request, pk):
@permission_required('exercises.add_exercise')
def decline(request, pk):
- '''
+ """
Declines and deletes a pending user submitted exercise
- '''
+ """
exercise = get_object_or_404(Exercise, pk=pk)
exercise.status = Exercise.STATUS_DECLINED
exercise.save()
diff --git a/wger/exercises/views/images.py b/wger/exercises/views/images.py
index d7bdcc6a9..43a240026 100644
--- a/wger/exercises/views/images.py
+++ b/wger/exercises/views/images.py
@@ -50,18 +50,18 @@ from wger.utils.generic_views import (
logger = logging.getLogger(__name__)
-'''
+"""
Exercise images
-'''
+"""
class ExerciseImageEditView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
UpdateView):
- '''
+ """
Generic view to update an existing exercise image
- '''
+ """
model = ExerciseImage
title = ugettext_lazy('Edit exercise image')
@@ -85,9 +85,9 @@ class ExerciseImageAddView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
CreateView):
- '''
+ """
Generic view to add a new exercise image
- '''
+ """
model = ExerciseImage
title = ugettext_lazy('Add new image')
@@ -103,9 +103,9 @@ class ExerciseImageAddView(WgerFormMixin,
return reverse('exercise:exercise:view', kwargs={'id': self.object.exercise.id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ExerciseImageAddView, self).get_context_data(**kwargs)
context['enctype'] = 'multipart/form-data'
context['form_action'] = reverse('exercise:image:add',
@@ -118,9 +118,9 @@ class ExerciseImageDeleteView(WgerDeleteMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
DeleteView):
- '''
+ """
Generic view to delete an existing exercise image
- '''
+ """
model = ExerciseImage
fields = ('image', 'is_main')
@@ -128,15 +128,15 @@ class ExerciseImageDeleteView(WgerDeleteMixin,
permission_required = 'exercises.delete_exerciseimage'
def get_success_url(self):
- '''
+ """
Return to exercise image
- '''
+ """
return reverse('exercise:exercise:view', kwargs={'id': self.kwargs['exercise_pk']})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
pk = self.kwargs['pk']
exercise_pk = self.kwargs['exercise_pk']
context = super(ExerciseImageDeleteView, self).get_context_data(**kwargs)
@@ -150,9 +150,9 @@ class ExerciseImageDeleteView(WgerDeleteMixin,
@permission_required('exercises.change_exerciseimage')
def accept(request, pk):
- '''
+ """
Accepts a pending user submitted image and emails the user, if possible
- '''
+ """
image = get_object_or_404(ExerciseImage, pk=pk)
image.status = ExerciseImage.STATUS_ACCEPTED
image.save()
@@ -163,9 +163,9 @@ def accept(request, pk):
@permission_required('exercises.change_exerciseimage')
def decline(request, pk):
- '''
+ """
Declines and deletes a pending user submitted image
- '''
+ """
image = get_object_or_404(ExerciseImage, pk=pk)
image.status = ExerciseImage.STATUS_DECLINED
image.save()
diff --git a/wger/exercises/views/muscles.py b/wger/exercises/views/muscles.py
index 879e5aea1..276ae12c0 100644
--- a/wger/exercises/views/muscles.py
+++ b/wger/exercises/views/muscles.py
@@ -52,18 +52,18 @@ logger = logging.getLogger(__name__)
class MuscleListView(UAAwareViewMixin, ListView):
- '''
+ """
Overview of all muscles and their exercises
- '''
+ """
model = Muscle
queryset = Muscle.objects.all().order_by('-is_front', 'name'),
context_object_name = 'muscle_list'
template_name = 'muscles/overview.html'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(MuscleListView, self).get_context_data(**kwargs)
context['active_languages'] = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)
context['show_shariff'] = True
@@ -71,18 +71,18 @@ class MuscleListView(UAAwareViewMixin, ListView):
class MuscleAdminListView(LoginRequiredMixin, PermissionRequiredMixin, MuscleListView):
- '''
+ """
Overview of all muscles, for administration purposes
- '''
+ """
permission_required = 'exercises.change_muscle'
queryset = Muscle.objects.order_by('name')
template_name = 'muscles/admin-overview.html'
class MuscleAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
Generic view to add a new muscle
- '''
+ """
model = Muscle
fields = '__all__'
@@ -93,9 +93,9 @@ class MuscleAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin,
class MuscleUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
Generic view to update an existing muscle
- '''
+ """
model = Muscle
fields = '__all__'
@@ -103,9 +103,9 @@ class MuscleUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixi
permission_required = 'exercises.change_muscle'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(MuscleUpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('exercise:muscle:edit', kwargs={'pk': self.object.id})
context['title'] = _(u'Edit {0}').format(self.object.name)
@@ -113,9 +113,9 @@ class MuscleUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixi
class MuscleDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
Generic view to delete an existing muscle
- '''
+ """
model = Muscle
fields = ('name', 'is_front')
@@ -124,9 +124,9 @@ class MuscleDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMi
messages = ugettext_lazy('Successfully deleted')
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(MuscleDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object.name)
context['form_action'] = reverse('exercise:muscle:delete', kwargs={'pk': self.kwargs['pk']})
diff --git a/wger/gym/forms.py b/wger/gym/forms.py
index 196786392..ae20fef6f 100644
--- a/wger/gym/forms.py
+++ b/wger/gym/forms.py
@@ -25,9 +25,9 @@ from wger.utils.widgets import BootstrapSelectMultiple
class GymUserPermissionForm(forms.ModelForm):
- '''
+ """
Form used to set the permission group of a gym member
- '''
+ """
USER = 'user'
GYM_ADMIN = 'admin'
TRAINER = 'trainer'
@@ -44,9 +44,9 @@ class GymUserPermissionForm(forms.ModelForm):
initial=USER)
def __init__(self, available_roles=None, *args, **kwargs):
- '''
+ """
Custom logic to reduce the available permissions
- '''
+ """
super(GymUserPermissionForm, self).__init__(*args, **kwargs)
if available_roles is None:
@@ -65,9 +65,9 @@ class GymUserPermissionForm(forms.ModelForm):
class GymUserAddForm(GymUserPermissionForm, UserPersonalInformationForm):
- '''
+ """
Form used when adding a user to a gym
- '''
+ """
birthdate = forms.DateField(required=False)
@@ -86,10 +86,10 @@ class GymUserAddForm(GymUserPermissionForm, UserPersonalInformationForm):
"@/.//-/_ characters.")})
def clean_username(self):
- '''
+ """
Since User.username is unique, this check is redundant,
but it sets a nicer error message than the ORM. See #13147.
- '''
+ """
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
diff --git a/wger/gym/helpers.py b/wger/gym/helpers.py
index 896e25a48..8f667e0bb 100644
--- a/wger/gym/helpers.py
+++ b/wger/gym/helpers.py
@@ -22,13 +22,13 @@ from wger.manager.models import (
def get_user_last_activity(user):
- '''
+ """
Find out when the user was last active. "Active" means in this context logging
a weight, or saving a workout session.
:param user: user object
:return: a date or None if nothing was found
- '''
+ """
last_activity = None
@@ -54,17 +54,17 @@ def get_user_last_activity(user):
def is_any_gym_admin(user):
- '''
+ """
Small utility that checks that the user object has any administrator
permissions
- '''
+ """
return user.has_perm('gym.manage_gym')\
or user.has_perm('gym.manage_gyms')\
or user.has_perm('gym.gym_trainer')
def get_permission_list(user):
- '''
+ """
Calculate available user permissions
This is needed because a user shouldn't be able to create or give another
@@ -72,7 +72,7 @@ def get_permission_list(user):
:param user: the user creating the account
:return: a list of permissions
- '''
+ """
form_group_permission = ['user', 'trainer']
diff --git a/wger/gym/management/commands/gym-user-config.py b/wger/gym/management/commands/gym-user-config.py
index 05ffc3e24..eaaeea1aa 100644
--- a/wger/gym/management/commands/gym-user-config.py
+++ b/wger/gym/management/commands/gym-user-config.py
@@ -28,15 +28,15 @@ from wger.gym.models import (
class Command(BaseCommand):
- '''
+ """
Check that all gym trainers and users have configurations
- '''
+ """
help = 'Check that all gym trainers and users have configurations'
def handle(self, **options):
- '''
+ """
Process all users
- '''
+ """
for user in User.objects.all():
if is_any_gym_admin(user):
diff --git a/wger/gym/management/commands/inactive-members.py b/wger/gym/management/commands/inactive-members.py
index f6303a77f..5df5b6db2 100644
--- a/wger/gym/management/commands/inactive-members.py
+++ b/wger/gym/management/commands/inactive-members.py
@@ -31,15 +31,15 @@ from wger.gym.models import Gym
class Command(BaseCommand):
- '''
+ """
Sends overviews of inactive users to gym trainers
- '''
+ """
help = 'Send out emails to trainers with users that have not shown recent activity'
def handle(self, **options):
- '''
+ """
Process gyms and send emails
- '''
+ """
today = datetime.date.today()
diff --git a/wger/gym/managers.py b/wger/gym/managers.py
index 8caf3996f..b7479fb3a 100644
--- a/wger/gym/managers.py
+++ b/wger/gym/managers.py
@@ -24,13 +24,13 @@ from django.db.models import Q
class GymManager(models.Manager):
- '''
+ """
Custom query manager for Gyms
- '''
+ """
def get_members(self, gym_pk):
- '''
+ """
Returns all members for this gym (i.e non-admin ones)
- '''
+ """
perm_gym = Permission.objects.get(codename='manage_gym')
perm_gyms = Permission.objects.get(codename='manage_gyms')
perm_trainer = Permission.objects.get(codename='gym_trainer')
@@ -41,9 +41,9 @@ class GymManager(models.Manager):
Q(groups__permissions=perm_trainer)).distinct()
def get_admins(self, gym_pk):
- '''
+ """
Returns all admins for this gym (i.e trainers, managers, etc.)
- '''
+ """
perm_gym = Permission.objects.get(codename='manage_gym')
perm_gyms = Permission.objects.get(codename='manage_gyms')
perm_trainer = Permission.objects.get(codename='gym_trainer')
diff --git a/wger/gym/migrations/0006_auto_20160214_1013.py b/wger/gym/migrations/0006_auto_20160214_1013.py
index 18ecf5de3..5a68e6163 100644
--- a/wger/gym/migrations/0006_auto_20160214_1013.py
+++ b/wger/gym/migrations/0006_auto_20160214_1013.py
@@ -6,9 +6,9 @@ from django.db import migrations, models
def update_permission_names(apps, schema_editor):
- '''
+ """
Updates the wording of our three custom gym permissions
- '''
+ """
Permission = apps.get_model("auth", "Permission")
for name in ['Trainer, can see the users for a gym',
diff --git a/wger/gym/models.py b/wger/gym/models.py
index fdb96891f..35fba7e32 100644
--- a/wger/gym/models.py
+++ b/wger/gym/models.py
@@ -32,9 +32,9 @@ from wger.gym.managers import GymManager
class Gym(m.Model):
- '''
+ """
Model for a gym
- '''
+ """
class Meta:
permissions = (
@@ -45,113 +45,113 @@ class Gym(m.Model):
ordering = ["name", ]
objects = GymManager()
- '''
+ """
Custom Gym Query Manager
- '''
+ """
name = m.CharField(max_length=60,
verbose_name=_('Name'))
- '''Gym name'''
+ """Gym name"""
phone = m.CharField(verbose_name=_('Phone'),
max_length=20,
blank=True,
null=True)
- '''Phone number'''
+ """Phone number"""
email = m.EmailField(verbose_name=_('Email'),
blank=True,
null=True)
- '''Email'''
+ """Email"""
owner = m.CharField(verbose_name=_('Owner'),
max_length=100,
blank=True,
null=True)
- '''Gym owner'''
+ """Gym owner"""
zip_code = m.CharField(_(u'ZIP code'),
max_length=10,
blank=True,
null=True)
- '''ZIP code'''
+ """ZIP code"""
city = m.CharField(_(u'City'),
max_length=30,
blank=True,
null=True)
- '''City'''
+ """City"""
street = m.CharField(_(u'Street'),
max_length=30,
blank=True,
null=True)
- '''Street'''
+ """Street"""
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
def get_absolute_url(self):
- '''
+ """
Return the URL for this object
- '''
+ """
return reverse('gym:gym:user-list', kwargs={'pk': self.pk})
def get_owner_object(self):
- '''
+ """
Gym has no owner information
- '''
+ """
return None
class GymConfig(m.Model):
- '''
+ """
Configuration options for a gym
- '''
+ """
gym = m.OneToOneField(Gym,
related_name='config',
editable=False,
on_delete=m.CASCADE)
- '''
+ """
Gym this configuration belongs to
- '''
+ """
weeks_inactive = m.PositiveIntegerField(verbose_name=_('Reminder of inactive members'),
help_text=_('Number of weeks since the last time a '
'user logged his presence to be considered inactive'),
default=4)
- '''
+ """
Reminder of inactive members
- '''
+ """
show_name = m.BooleanField(verbose_name=_('Show name in header'),
help_text=_('Show the name of the gym in the site header'),
default=False)
- '''
+ """
Show name of the current user's gym in the header, instead of 'wger'
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return ugettext(u'Configuration for {}'.format(self.gym.name))
def get_owner_object(self):
- '''
+ """
Config has no user owner
- '''
+ """
return None
class AbstractGymUserConfigModel(m.Model):
- '''
+ """
Abstract class for member and admin gym configuration models
- '''
+ """
class Meta:
abstract = True
@@ -159,310 +159,310 @@ class AbstractGymUserConfigModel(m.Model):
gym = m.ForeignKey(Gym,
editable=False,
on_delete=m.CASCADE)
- '''
+ """
Gym this configuration belongs to
- '''
+ """
user = m.OneToOneField(User,
editable=False,
on_delete=m.CASCADE)
- '''
+ """
User this configuration belongs to
- '''
+ """
class GymAdminConfig(AbstractGymUserConfigModel, m.Model):
- '''
+ """
Administrator/trainer configuration options for a specific gym
- '''
+ """
class Meta:
unique_together = ('gym', 'user')
- '''
+ """
Only one entry per user and gym
- '''
+ """
overview_inactive = m.BooleanField(verbose_name=_('Overview of inactive members'),
help_text=_('Receive email overviews of inactive members'),
default=True)
- '''
+ """
Reminder of inactive members
- '''
+ """
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self
class GymUserConfig(AbstractGymUserConfigModel, m.Model):
- '''
+ """
Gym member configuration options for a specific gym
- '''
+ """
class Meta:
unique_together = ('gym', 'user')
- '''
+ """
Only one entry per user and gym
- '''
+ """
include_inactive = m.BooleanField(verbose_name=_('Include in inactive overview'),
help_text=_('Include this user in the email list with '
'inactive members'),
default=True)
- '''
+ """
Include user in inactive overview
- '''
+ """
def get_owner_object(self):
- '''
+ """
While the model has a user foreign key, this is editable by all
trainers in the gym.
- '''
+ """
return None
class AdminUserNote(m.Model):
- '''
+ """
Administrator notes about a member
- '''
+ """
class Meta:
- '''
+ """
Order by time
- '''
+ """
ordering = ["-timestamp_created", ]
user = m.ForeignKey(User,
editable=False,
related_name='adminusernote_user',
on_delete=m.CASCADE)
- '''
+ """
User this note belongs to
- '''
+ """
member = m.ForeignKey(User,
editable=False,
related_name='adminusernote_member',
on_delete=m.CASCADE)
- '''
+ """
Gym member this note refers to
- '''
+ """
timestamp_created = m.DateTimeField(auto_now_add=True)
- '''
+ """
Time when this note was created
- '''
+ """
timestamp_edited = m.DateTimeField(auto_now=True)
- '''
+ """
Last time when this note was edited
- '''
+ """
note = m.TextField(verbose_name=_('Note'))
- '''
+ """
Actual note
- '''
+ """
def get_owner_object(self):
- '''
+ """
While the model has a user foreign key, this is editable by all
trainers in the gym.
- '''
+ """
return None
def gym_document_upload_dir(instance, filename):
- '''
+ """
Returns the upload target for documents
- '''
+ """
return "gym/documents/{0}/{1}/{2}".format(instance.member.userprofile.gym.id,
instance.member.id,
uuid.uuid4())
class UserDocument(m.Model):
- '''
+ """
Model for a document
- '''
+ """
class Meta:
- '''
+ """
Order by time
- '''
+ """
ordering = ["-timestamp_created", ]
user = m.ForeignKey(User,
editable=False,
related_name='userdocument_user',
on_delete=m.CASCADE)
- '''
+ """
User this note belongs to
- '''
+ """
member = m.ForeignKey(User,
editable=False,
related_name='userdocument_member',
on_delete=m.CASCADE)
- '''
+ """
Gym member this note refers to
- '''
+ """
timestamp_created = m.DateTimeField(auto_now_add=True)
- '''
+ """
Time when this document was created
- '''
+ """
timestamp_edited = m.DateTimeField(auto_now=True)
- '''
+ """
Last time when this document was edited
- '''
+ """
document = m.FileField(verbose_name=_('Document'),
upload_to=gym_document_upload_dir)
- '''
+ """
Uploaded document
- '''
+ """
original_name = m.CharField(max_length=128,
editable=False)
- '''
+ """
Original document name when uploaded
- '''
+ """
name = m.CharField(max_length=60,
verbose_name=_('Name'),
help_text=_('Will use file name if nothing provided'),
blank=True)
- '''
+ """
Name or description
- '''
+ """
note = m.TextField(verbose_name=_('Note'),
blank=True,
null=True)
- '''
+ """
Note with additional information
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
if self.name != self.original_name:
return "{} ({})".format(self.name, self.original_name)
else:
return "{}".format(self.name)
def get_owner_object(self):
- '''
+ """
While the model has a user foreign key, this is editable by all
trainers in the gym.
- '''
+ """
return None
class ContractType(m.Model):
- '''
+ """
Model for a contract's type
A contract type is a user-editable way of enhancing the contract to
specify types, such as e.g. 'with personal trainer', 'regular', etc.
- '''
+ """
class Meta:
- '''
+ """
Order by name
- '''
+ """
ordering = ["name", ]
gym = m.ForeignKey(Gym,
editable=False,
on_delete=m.CASCADE)
- '''
+ """
The gym this contract type belongs to
- '''
+ """
name = m.CharField(verbose_name=_('Name'),
max_length=25)
- '''
+ """
The contract type's short name
- '''
+ """
description = m.TextField(verbose_name=_('Description'),
blank=True,
null=True)
- '''
+ """
Free text field for additional information
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{}".format(self.name)
def get_owner_object(self):
- '''
+ """
Contract type has no owner information
- '''
+ """
return None
class ContractOption(m.Model):
- '''
+ """
Model for a contract Option
A contract option is a user-editable way of enhancing the contract to
specify options, such as e.g. 'cash', 'bank withdrawal', etc. The
difference with a contract type is that a contract can only be of one
type but can have different options.
- '''
+ """
class Meta:
- '''
+ """
Order by name
- '''
+ """
ordering = ["name", ]
gym = m.ForeignKey(Gym,
editable=False,
on_delete=m.CASCADE)
- '''
+ """
The gym this contract option belongs to
- '''
+ """
name = m.CharField(verbose_name=_('Name'),
max_length=25)
- '''
+ """
The contract options short name
- '''
+ """
description = m.TextField(verbose_name=_('Description'),
blank=True,
null=True)
- '''
+ """
Free text field for additional information
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{}".format(self.name)
def get_owner_object(self):
- '''
+ """
Contract type has no owner information
- '''
+ """
return None
class Contract(m.Model):
- '''
+ """
Model for a member's contract in a gym
- '''
+ """
AMOUNT_TYPE_YEARLY = '1'
AMOUNT_TYPE_HALFYEARLY = '2'
@@ -481,150 +481,150 @@ class Contract(m.Model):
)
class Meta:
- '''
+ """
Order by time
- '''
+ """
ordering = ["-date_start", ]
user = m.ForeignKey(User,
editable=False,
related_name='contract_user',
on_delete=m.CASCADE)
- '''
+ """
User that originally created the contract
- '''
+ """
member = m.ForeignKey(User,
editable=False,
related_name='contract_member',
on_delete=m.CASCADE)
- '''
+ """
Gym member this contract refers to
- '''
+ """
timestamp_created = m.DateTimeField(auto_now_add=True)
- '''
+ """
Time when the contract was created
- '''
+ """
timestamp_edited = m.DateTimeField(auto_now=True)
- '''
+ """
Last time when the contract was edited
- '''
+ """
contract_type = m.ForeignKey(ContractType,
blank=True,
null=True,
verbose_name=_('Contract type'),
on_delete=m.CASCADE)
- '''
+ """
Optional type of contract
- '''
+ """
options = m.ManyToManyField(ContractOption,
verbose_name=_('Options'),
blank=True)
- '''
+ """
Options for the contract
- '''
+ """
amount = m.DecimalField(verbose_name=_('Amount'),
decimal_places=2,
max_digits=12,
default=0)
- '''
+ """
The amount to pay
- '''
+ """
payment = m.CharField(verbose_name=_('Payment type'),
max_length=2,
choices=AMOUNT_TYPE,
default=AMOUNT_TYPE_MONTHLY,
help_text=_('How often the amount will be charged to the member'))
- '''
+ """
How often the amount will be charged to the member
- '''
+ """
is_active = m.BooleanField(verbose_name=_('Contract is active'),
default=True)
- '''
+ """
Flag showing whether the contract is currently active
- '''
+ """
date_start = m.DateField(verbose_name=_('Start date'),
default=datetime.date.today,
blank=True,
null=True)
- '''
+ """
The date when the contract starts
- '''
+ """
date_end = m.DateField(verbose_name=_('End date'),
blank=True,
null=True)
- '''
+ """
The date when the contract ends
- '''
+ """
email = m.EmailField(verbose_name=_('Email'),
blank=True,
null=True)
- '''The member's email'''
+ """The member's email"""
zip_code = m.CharField(_(u'ZIP code'),
max_length=10,
blank=True,
null=True)
- '''ZIP code'''
+ """ZIP code"""
city = m.CharField(_(u'City'),
max_length=30,
blank=True,
null=True)
- '''City'''
+ """City"""
street = m.CharField(_(u'Street'),
max_length=30,
blank=True,
null=True)
- '''Street'''
+ """Street"""
phone = m.CharField(verbose_name=_('Phone'),
max_length=20,
blank=True,
null=True)
- '''Phone number'''
+ """Phone number"""
profession = m.CharField(verbose_name=_('Profession'),
max_length=50,
blank=True,
null=True)
- '''
+ """
The member's profession
- '''
+ """
note = m.TextField(verbose_name=_('Note'),
blank=True,
null=True)
- '''
+ """
Free text note with additional information
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return "#{}".format(self.id)
def get_absolute_url(self):
- '''
+ """
Return the URL for this object
- '''
+ """
return reverse('gym:contract:view', kwargs={'pk': self.pk})
def get_owner_object(self):
- '''
+ """
While the model has a user foreign key, this is editable by all
managers in the gym.
- '''
+ """
return None
diff --git a/wger/gym/signals.py b/wger/gym/signals.py
index f51c0389b..dd8e903e0 100644
--- a/wger/gym/signals.py
+++ b/wger/gym/signals.py
@@ -32,9 +32,9 @@ from wger.gym.models import (
@receiver(post_save, sender=Gym)
def gym_config(sender, instance, created, **kwargs):
- '''
+ """
Creates a configuration entry for newly added gyms
- '''
+ """
if not created or kwargs['raw']:
return
@@ -45,8 +45,8 @@ def gym_config(sender, instance, created, **kwargs):
@receiver(post_delete, sender=UserDocument)
def delete_user_document_on_delete(sender, instance, **kwargs):
- '''
+ """
Deletes the document from the disk as well
- '''
+ """
instance.document.delete(save=False)
diff --git a/wger/gym/tests/test_admin_config.py b/wger/gym/tests/test_admin_config.py
index 624d88843..21a8fbc02 100644
--- a/wger/gym/tests/test_admin_config.py
+++ b/wger/gym/tests/test_admin_config.py
@@ -18,9 +18,9 @@ from wger.gym.models import GymAdminConfig
class EditConfigTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing an admin config
- '''
+ """
object_class = GymAdminConfig
url = 'gym:admin_config:edit'
diff --git a/wger/gym/tests/test_admin_user_notes.py b/wger/gym/tests/test_admin_user_notes.py
index 27e8fb45f..d5aaeabd0 100644
--- a/wger/gym/tests/test_admin_user_notes.py
+++ b/wger/gym/tests/test_admin_user_notes.py
@@ -27,9 +27,9 @@ from wger.gym.models import AdminUserNote
class AdminNoteOverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests accessing the admin notes overview page
- '''
+ """
url = reverse_lazy('gym:admin_note:list', kwargs={'user_pk': 14})
anonymous_fail = True
user_success = ('trainer1',
@@ -44,9 +44,9 @@ class AdminNoteOverviewTest(WorkoutManagerAccessTestCase):
class AddAdminNoteTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new admin note
- '''
+ """
object_class = AdminUserNote
url = reverse_lazy('gym:admin_note:add', kwargs={'user_pk': 14})
data = {'note': 'The note text goes here'}
@@ -62,9 +62,9 @@ class AddAdminNoteTestCase(WorkoutManagerAddTestCase):
class EditAdminNoteTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing an admin note
- '''
+ """
object_class = AdminUserNote
url = 'gym:admin_note:edit'
@@ -82,9 +82,9 @@ class EditAdminNoteTestCase(WorkoutManagerEditTestCase):
class DeleteAdminNoteTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting an admin note
- '''
+ """
pk = 2
object_class = AdminUserNote
diff --git a/wger/gym/tests/test_config.py b/wger/gym/tests/test_config.py
index 8be29fbf5..4e21ed7b0 100644
--- a/wger/gym/tests/test_config.py
+++ b/wger/gym/tests/test_config.py
@@ -19,9 +19,9 @@ from wger.gym.models import GymConfig
class EditGymConfigTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Test editing a gym configuration
- '''
+ """
pk = 1
object_class = GymConfig
diff --git a/wger/gym/tests/test_contract_options.py b/wger/gym/tests/test_contract_options.py
index 0c1f05472..bd0e50cbd 100644
--- a/wger/gym/tests/test_contract_options.py
+++ b/wger/gym/tests/test_contract_options.py
@@ -27,9 +27,9 @@ from wger.gym.models import ContractOption
class AddContractOptionTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests creating a new contract option
- '''
+ """
object_class = ContractOption
url = reverse('gym:contract-option:add', kwargs={'gym_pk': 1})
@@ -49,9 +49,9 @@ class AddContractOptionTestCase(WorkoutManagerAddTestCase):
class EditContractOptionTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a contract option
- '''
+ """
pk = 1
object_class = ContractOption
@@ -72,9 +72,9 @@ class EditContractOptionTestCase(WorkoutManagerEditTestCase):
class DeleteContractOptionTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a contract option
- '''
+ """
pk = 1
object_class = ContractOption
@@ -97,9 +97,9 @@ delete_testcase_add_methods(DeleteContractOptionTestCase)
class AccessContractOptionOverviewTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the contract option page
- '''
+ """
url = reverse('gym:contract-option:list', kwargs={'gym_pk': 1})
user_success = ('manager1',
'manager2')
diff --git a/wger/gym/tests/test_contract_types.py b/wger/gym/tests/test_contract_types.py
index ca1bf6a05..98d9d2024 100644
--- a/wger/gym/tests/test_contract_types.py
+++ b/wger/gym/tests/test_contract_types.py
@@ -27,9 +27,9 @@ from wger.gym.models import ContractType
class AddContractTypeTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests creating a new contract
- '''
+ """
object_class = ContractType
url = reverse('gym:contract_type:add', kwargs={'gym_pk': 1})
@@ -49,9 +49,9 @@ class AddContractTypeTestCase(WorkoutManagerAddTestCase):
class EditContractTypeTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a contract type
- '''
+ """
pk = 1
object_class = ContractType
@@ -72,9 +72,9 @@ class EditContractTypeTestCase(WorkoutManagerEditTestCase):
class DeleteContractTypeTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a contract type
- '''
+ """
pk = 1
object_class = ContractType
@@ -97,9 +97,9 @@ delete_testcase_add_methods(DeleteContractTypeTestCase)
class AccessContractTypeOverviewTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the contract list page
- '''
+ """
url = reverse('gym:contract_type:list', kwargs={'gym_pk': 1})
user_success = ('manager1',
'manager2')
diff --git a/wger/gym/tests/test_contracts.py b/wger/gym/tests/test_contracts.py
index 216cc76c9..90f8be95d 100644
--- a/wger/gym/tests/test_contracts.py
+++ b/wger/gym/tests/test_contracts.py
@@ -25,9 +25,9 @@ from wger.gym.models import Contract
class AddContractTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests creating a new contract
- '''
+ """
object_class = Contract
url = reverse('gym:contract:add', kwargs={'user_pk': 14})
@@ -48,9 +48,9 @@ class AddContractTestCase(WorkoutManagerAddTestCase):
class AccessContractTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the detail page of a contract
- '''
+ """
url = reverse('gym:contract:view', kwargs={'pk': 1})
user_success = ('manager1',
'manager2')
@@ -67,9 +67,9 @@ class AccessContractTestCase(WorkoutManagerAccessTestCase):
class AccessContractOverviewTestCase(WorkoutManagerAccessTestCase):
- '''
+ """
Test accessing the contract list page
- '''
+ """
url = reverse('gym:contract:list', kwargs={'user_pk': 4})
user_success = ('manager1',
'manager2')
@@ -86,9 +86,9 @@ class AccessContractOverviewTestCase(WorkoutManagerAccessTestCase):
class EditContractTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a contract
- '''
+ """
pk = 1
object_class = Contract
diff --git a/wger/gym/tests/test_export.py b/wger/gym/tests/test_export.py
index 4768b7159..45bb6bd27 100644
--- a/wger/gym/tests/test_export.py
+++ b/wger/gym/tests/test_export.py
@@ -24,14 +24,14 @@ from wger.gym.models import Gym
class GymMembersCsvExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Test case for the CSV export of gym members
- '''
+ """
def export_csv(self, fail=True):
- '''
+ """
Helper function to test the CSV export
- '''
+ """
response = self.client.get(reverse('gym:export:users', kwargs={'gym_pk': 1}))
gym = Gym.objects.get(pk=1)
@@ -50,18 +50,18 @@ class GymMembersCsvExportTestCase(WorkoutManagerTestCase):
self.assertLessEqual(len(response.content), 1300)
def test_export_csv_authorized(self):
- '''
+ """
Test the CSV export by authorized users
- '''
+ """
for username in ('manager1', 'manager2', 'general_manager1'):
self.user_login(username)
self.export_csv(fail=False)
def test_export_csv_unauthorized(self):
- '''
+ """
Test the CSV export by unauthorized users
- '''
+ """
for username in ('manager3',
'manager4',
@@ -75,8 +75,8 @@ class GymMembersCsvExportTestCase(WorkoutManagerTestCase):
self.export_csv(fail=True)
def test_export_csv_logged_out(self):
- '''
+ """
Test the CSV export by a logged out user
- '''
+ """
self.user_logout()
self.export_csv(fail=True)
diff --git a/wger/gym/tests/test_gym.py b/wger/gym/tests/test_gym.py
index 2e14d364f..cbb356784 100644
--- a/wger/gym/tests/test_gym.py
+++ b/wger/gym/tests/test_gym.py
@@ -30,21 +30,21 @@ from wger.gym.models import Gym
class GymRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Gym.objects.get(pk=1)), 'Test 123')
class GymOverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests accessing the gym overview page
- '''
+ """
url = 'gym:gym:list'
anonymous_fail = True
user_success = ('admin',
@@ -59,9 +59,9 @@ class GymOverviewTest(WorkoutManagerAccessTestCase):
class GymUserOverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests accessing the gym user overview page
- '''
+ """
url = reverse_lazy('gym:gym:user-list', kwargs={'pk': 1})
anonymous_fail = True
user_success = ('admin',
@@ -77,9 +77,9 @@ class GymUserOverviewTest(WorkoutManagerAccessTestCase):
class AddGymTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new gym
- '''
+ """
object_class = Gym
url = 'gym:gym:add'
data = {'name': 'The name here'}
@@ -95,9 +95,9 @@ class AddGymTestCase(WorkoutManagerAddTestCase):
class DeleteGymTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a gym
- '''
+ """
pk = 2
object_class = Gym
@@ -118,9 +118,9 @@ delete_testcase_add_methods(DeleteGymTestCase)
class EditGymTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a gym
- '''
+ """
object_class = Gym
url = 'gym:gym:edit'
@@ -139,14 +139,14 @@ class EditGymTestCase(WorkoutManagerEditTestCase):
class GymTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests other gym methods
- '''
+ """
def test_delete_gym(self):
- '''
+ """
Tests that deleting a gym also removes it from all user profiles
- '''
+ """
gym = Gym.objects.get(pk=1)
self.assertEqual(UserProfile.objects.filter(gym=gym).count(), 17)
diff --git a/wger/gym/tests/test_inactive_members.py b/wger/gym/tests/test_inactive_members.py
index 538d7b006..a20240833 100644
--- a/wger/gym/tests/test_inactive_members.py
+++ b/wger/gym/tests/test_inactive_members.py
@@ -21,14 +21,14 @@ from wger.core.tests.base_testcase import WorkoutManagerTestCase
class EmailInactiveUserTestCase(WorkoutManagerTestCase):
- '''
+ """
Test email reminders for inactive users
- '''
+ """
def test_reminder(self, fail=False):
- '''
+ """
Test email reminders for inactive users
- '''
+ """
call_command('inactive-members')
self.assertEqual(len(mail.outbox), 6)
diff --git a/wger/gym/tests/test_user.py b/wger/gym/tests/test_user.py
index 7191f2343..b2cdd82c1 100644
--- a/wger/gym/tests/test_user.py
+++ b/wger/gym/tests/test_user.py
@@ -33,14 +33,14 @@ from wger.gym.models import (
class GymAddUserTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests admin adding users to gyms
- '''
+ """
def add_user(self, fail=False):
- '''
+ """
Helper function to add users
- '''
+ """
count_before = User.objects.all().count()
GymAdminConfig.objects.all().delete()
response = self.client.get(reverse('gym:gym:add-user', kwargs={'gym_pk': 1}))
@@ -72,50 +72,50 @@ class GymAddUserTestCase(WorkoutManagerTestCase):
self.assertEqual(new_user.userprofile.gym_id, 1)
def test_add_user_authorized(self):
- '''
+ """
Tests adding a user as authorized user
- '''
+ """
self.user_login('admin')
self.add_user()
def test_add_user_authorized2(self):
- '''
+ """
Tests adding a user as authorized user
- '''
+ """
self.user_login('general_manager1')
self.add_user()
def test_add_user_unauthorized(self):
- '''
+ """
Tests adding a user an unauthorized user
- '''
+ """
self.user_login('test')
self.add_user(fail=True)
def test_add_user_unauthorized2(self):
- '''
+ """
Tests adding a user an unauthorized user
- '''
+ """
self.user_login('trainer1')
self.add_user(fail=True)
def test_add_user_unauthorized3(self):
- '''
+ """
Tests adding a user an unauthorized user
- '''
+ """
self.user_login('manager3')
self.add_user(fail=True)
def test_add_user_logged_out(self):
- '''
+ """
Tests adding a user a logged out user
- '''
+ """
self.add_user(fail=True)
def new_user_data_export(self, fail=False):
- '''
+ """
Helper function to test exporting the data of a newly created user
- '''
+ """
response = self.client.get(reverse('gym:gym:new-user-data-export'))
if fail:
self.assertIn(response.status_code, (302, 403))
@@ -130,9 +130,9 @@ class GymAddUserTestCase(WorkoutManagerTestCase):
self.assertLessEqual(len(response.content), 120)
def test_new_user_data_export(self):
- '''
+ """
Test exporting the data of a newly created user
- '''
+ """
self.user_login('admin')
self.add_user()
self.new_user_data_export(fail=False)
@@ -146,40 +146,40 @@ class GymAddUserTestCase(WorkoutManagerTestCase):
class TrainerLoginTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the trainer login view (switching to user ID)
- '''
+ """
def test_anonymous(self):
- '''
+ """
Test the trainer login as an anonymous user
- '''
+ """
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 1}))
self.assertEqual(response.status_code, 302)
self.assertFalse(self.client.session.get('trainer.identity'))
def test_user(self):
- '''
+ """
Test the trainer login as a logged in user without rights
- '''
+ """
self.user_login('test')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 1}))
self.assertEqual(response.status_code, 403)
self.assertFalse(self.client.session.get('trainer.identity'))
def test_trainer(self):
- '''
+ """
Test the trainer login as a logged in user with enough rights
- '''
+ """
self.user_login('admin')
response = self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertEqual(response.status_code, 302)
self.assertTrue(self.client.session.get('trainer.identity'))
def test_wrong_gym(self):
- '''
+ """
Test changing the identity to a user in a different gym
- '''
+ """
profile = UserProfile.objects.get(user_id=2)
profile.gym_id = 2
profile.save()
@@ -189,9 +189,9 @@ class TrainerLoginTestCase(WorkoutManagerTestCase):
self.assertFalse(self.client.session.get('trainer.identity'))
def test_gym_trainer(self):
- '''
+ """
Test changing the identity to a user with trainer rights
- '''
+ """
user = User.objects.get(pk=2)
content_type = ContentType.objects.get_for_model(Gym)
permission = Permission.objects.get(content_type=content_type, codename='gym_trainer')
@@ -203,9 +203,9 @@ class TrainerLoginTestCase(WorkoutManagerTestCase):
self.assertFalse(self.client.session.get('trainer.identity'))
def test_gym_manager(self):
- '''
+ """
Test changing the identity to a user with gym management rights
- '''
+ """
user = User.objects.get(pk=2)
content_type = ContentType.objects.get_for_model(Gym)
permission = Permission.objects.get(content_type=content_type, codename='manage_gym')
@@ -217,9 +217,9 @@ class TrainerLoginTestCase(WorkoutManagerTestCase):
self.assertFalse(self.client.session.get('trainer.identity'))
def test_gyms_manager(self):
- '''
+ """
Test changing the identity to a user with gyms management rights
- '''
+ """
user = User.objects.get(pk=2)
content_type = ContentType.objects.get_for_model(Gym)
permission = Permission.objects.get(content_type=content_type, codename='manage_gyms')
@@ -232,14 +232,14 @@ class TrainerLoginTestCase(WorkoutManagerTestCase):
class TrainerLogoutTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the trainer logout view (switching back to trainer ID)
- '''
+ """
def test_logout(self):
- '''
+ """
Test the trainer login as an anonymous user
- '''
+ """
self.user_login('admin')
self.client.get(reverse('core:user:trainer-login', kwargs={'user_pk': 2}))
self.assertTrue(self.client.session.get('trainer.identity'))
diff --git a/wger/gym/tests/test_user_config.py b/wger/gym/tests/test_user_config.py
index 86bb00552..7d26cfd5c 100644
--- a/wger/gym/tests/test_user_config.py
+++ b/wger/gym/tests/test_user_config.py
@@ -18,9 +18,9 @@ from wger.gym.models import GymUserConfig
class EditConfigTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a user config
- '''
+ """
pk = 1
object_class = GymUserConfig
diff --git a/wger/gym/tests/test_user_documents.py b/wger/gym/tests/test_user_documents.py
index 992f9dea6..5acd4ef67 100644
--- a/wger/gym/tests/test_user_documents.py
+++ b/wger/gym/tests/test_user_documents.py
@@ -27,9 +27,9 @@ from wger.gym.models import UserDocument
class UserDocumentOverviewTest(WorkoutManagerAccessTestCase):
- '''
+ """
Tests accessing the user document overview page
- '''
+ """
url = reverse('gym:document:list', kwargs={'user_pk': 14})
anonymous_fail = True
user_success = ('trainer1',
@@ -44,9 +44,9 @@ class UserDocumentOverviewTest(WorkoutManagerAccessTestCase):
class AddDocumentTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests uploading a new user document
- '''
+ """
object_class = UserDocument
url = reverse('gym:document:add', kwargs={'user_pk': 14})
@@ -64,9 +64,9 @@ class AddDocumentTestCase(WorkoutManagerAddTestCase):
class EditDocumentTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a user document
- '''
+ """
pk = 2
object_class = UserDocument
@@ -83,9 +83,9 @@ class EditDocumentTestCase(WorkoutManagerEditTestCase):
class DeleteDocumentTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a user document
- '''
+ """
pk = 1
object_class = UserDocument
diff --git a/wger/gym/tests/test_user_last_activity.py b/wger/gym/tests/test_user_last_activity.py
index c142cbafa..009bb3b36 100644
--- a/wger/gym/tests/test_user_last_activity.py
+++ b/wger/gym/tests/test_user_last_activity.py
@@ -28,14 +28,14 @@ from wger.manager.models import (
class UserLastActivityTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the helper function for last user activity
- '''
+ """
def test_user_last_activity(self):
- '''
+ """
Test the helper function for last user activity
- '''
+ """
self.user_login('admin')
user = User.objects.get(username='admin')
log = WorkoutLog.objects.get(pk=1)
diff --git a/wger/gym/views/admin_config.py b/wger/gym/views/admin_config.py
index 795880ba0..542432c0a 100644
--- a/wger/gym/views/admin_config.py
+++ b/wger/gym/views/admin_config.py
@@ -31,24 +31,24 @@ logger = logging.getLogger(__name__)
class ConfigUpdateView(WgerFormMixin, UpdateView):
- '''
+ """
View to update an existing admin gym configuration
- '''
+ """
model = GymAdminConfig
fields = '__all__'
permission_required = 'gym.change_gymadminconfig'
def get_success_url(self):
- '''
+ """
Return to the gym user overview
- '''
+ """
return reverse('gym:gym:user-list', kwargs={'pk': self.object.gym.pk})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ConfigUpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:admin_config:edit', kwargs={'pk': self.object.id})
context['title'] = _('Configuration')
diff --git a/wger/gym/views/admin_notes.py b/wger/gym/views/admin_notes.py
index 57544a376..9e6e99ba2 100644
--- a/wger/gym/views/admin_notes.py
+++ b/wger/gym/views/admin_notes.py
@@ -49,24 +49,24 @@ logger = logging.getLogger(__name__)
class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available admin notes
- '''
+ """
model = AdminUserNote
permission_required = 'gym.add_adminusernote'
template_name = 'admin_notes/list.html'
member = None
def get_queryset(self):
- '''
+ """
Only notes for current user
- '''
+ """
return AdminUserNote.objects.filter(member_id=self.kwargs['user_pk'])
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add notes to users in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -77,9 +77,9 @@ class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, Li
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ListView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:admin_note:add',
kwargs={'user_pk': self.kwargs['user_pk']})
@@ -88,9 +88,9 @@ class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, Li
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new admin note
- '''
+ """
model = AdminUserNote
fields = '__all__'
@@ -99,15 +99,15 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
member = None
def get_success_url(self):
- '''
+ """
Redirect back to user page
- '''
+ """
return reverse('gym:admin_note:list', kwargs={'user_pk': self.member.pk})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add notes to users in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -119,17 +119,17 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
- '''
+ """
Set user instances
- '''
+ """
form.instance.member = self.member
form.instance.user = self.request.user
return super(AddView, self).form_valid(form)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(AddView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:admin_note:add',
kwargs={'user_pk': self.kwargs['user_pk']})
@@ -137,25 +137,25 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing admin note
- '''
+ """
model = AdminUserNote
fields = '__all__'
permission_required = 'gym.change_adminusernote'
def get_success_url(self):
- '''
+ """
Redirect back to user page
- '''
+ """
return reverse('gym:admin_note:list', kwargs={'user_pk':
self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only trainers for this gym can edit user notes
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -166,9 +166,9 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:admin_note:edit', kwargs={'pk': self.object.id})
context['title'] = _(u'Edit {0}').format(self.object)
@@ -176,24 +176,24 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing admin note
- '''
+ """
model = AdminUserNote
fields = ('note', )
permission_required = 'gym.delete_adminusernote'
def get_success_url(self):
- '''
+ """
Redirect back to user page
- '''
+ """
return reverse('gym:admin_note:list', kwargs={'user_pk': self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only trainers for this gym can delete user notes
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -203,9 +203,9 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
context['form_action'] = reverse('gym:admin_note:delete', kwargs={'pk': self.kwargs['pk']})
diff --git a/wger/gym/views/config.py b/wger/gym/views/config.py
index 14d73862f..2a28c5196 100644
--- a/wger/gym/views/config.py
+++ b/wger/gym/views/config.py
@@ -36,18 +36,18 @@ logger = logging.getLogger(__name__)
class GymConfigUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing gym configuration
- '''
+ """
model = GymConfig
fields = '__all__'
permission_required = 'gym.change_gymconfig'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only managers for this gym can add new members
- '''
+ """
if request.user.has_perm('gym.change_gymconfig'):
gym_id = request.user.userprofile.gym_id
if gym_id != int(self.kwargs['pk']):
@@ -55,15 +55,15 @@ class GymConfigUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredM
return super(GymConfigUpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
- '''
+ """
Return to the gym user overview
- '''
+ """
return reverse('gym:gym:user-list', kwargs={'pk': self.object.gym.pk})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(GymConfigUpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:config:edit', kwargs={'pk': self.object.id})
context['title'] = _(u'Edit {0}').format(self.object)
diff --git a/wger/gym/views/contract.py b/wger/gym/views/contract.py
index 8e1ed7f00..175807b35 100644
--- a/wger/gym/views/contract.py
+++ b/wger/gym/views/contract.py
@@ -49,9 +49,9 @@ logger = logging.getLogger(__name__)
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new contract
- '''
+ """
model = Contract
fields = '__all__'
@@ -60,13 +60,13 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
member = None
def get_initial(self):
- '''
+ """
Get the initial data for new contracts
Since the user's data probably didn't change between one contract and the
next, try to fill in as much data as possible from previous ones or the
user's profile
- '''
+ """
out = {}
if Contract.objects.filter(member=self.member).exists():
last_contract = Contract.objects.filter(member=self.member).first()
@@ -85,9 +85,9 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
return out
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add documents to users in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -98,17 +98,17 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
- '''
+ """
Set user instances
- '''
+ """
form.instance.member = self.member
form.instance.user = self.request.user
return super(AddView, self).form_valid(form)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(AddView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:contract:add',
kwargs={'user_pk': self.kwargs['user_pk']})
@@ -116,18 +116,18 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
class DetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView):
- '''
+ """
Detail view of a member's contract
- '''
+ """
model = Contract
template_name = 'contract/view.html'
permission_required = 'gym.add_contract'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only see contracts for own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -138,9 +138,9 @@ class DetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView):
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing contract
- '''
+ """
model = Contract
fields = '__all__'
@@ -148,9 +148,9 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
form_action_urlname = 'gym:contract:edit'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only trainers for this gym can edit user notes
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -161,33 +161,33 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available admin notes
- '''
+ """
model = Contract
permission_required = 'gym.add_contract'
template_name = 'contract/list.html'
member = None
def get_queryset(self):
- '''
+ """
Only documents for current user
- '''
+ """
return Contract.objects.filter(member=self.member)
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only list contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -198,9 +198,9 @@ class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, Li
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ListView, self).get_context_data(**kwargs)
context['member'] = self.member
return context
diff --git a/wger/gym/views/contract_option.py b/wger/gym/views/contract_option.py
index 772dedd81..5ef0e8dd5 100644
--- a/wger/gym/views/contract_option.py
+++ b/wger/gym/views/contract_option.py
@@ -52,9 +52,9 @@ logger = logging.getLogger(__name__)
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new contract option
- '''
+ """
model = ContractOption
fields = ('name', 'description')
@@ -63,15 +63,15 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
member = None
def get_success_url(self):
- '''
+ """
Redirect back to overview page
- '''
+ """
return reverse('gym:contract-option:list', kwargs={'gym_pk': self.object.gym_id})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -81,16 +81,16 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
- '''
+ """
Set the foreign key to the gym object
- '''
+ """
form.instance.gym_id = self.kwargs['gym_pk']
return super(AddView, self).form_valid(form)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(AddView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:contract-option:add',
kwargs={'gym_pk': self.kwargs['gym_pk']})
@@ -98,9 +98,9 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing contract option
- '''
+ """
model = ContractOption
fields = ('name', 'description')
@@ -108,9 +108,9 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
form_action_urlname = 'gym:contract-option:edit'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -121,24 +121,24 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
- '''
+ """
Redirect back to overview page
- '''
+ """
return reverse('gym:contract-option:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing contract option
- '''
+ """
model = ContractOption
fields = ('name', 'description')
@@ -146,9 +146,9 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
form_action_urlname = 'gym:contract-option:delete'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add contract option in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -159,39 +159,39 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
- '''
+ """
Redirect back to overview page
- '''
+ """
return reverse('gym:contract-option:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}').format(self.object)
return context
class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available contract options
- '''
+ """
model = ContractOption
permission_required = 'gym.add_contractoption'
template_name = 'contract_option/list.html'
gym = None
def get_queryset(self):
- '''
+ """
Only documents for current user
- '''
+ """
return ContractOption.objects.filter(gym=self.gym)
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only list contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -202,9 +202,9 @@ class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, Li
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ListView, self).get_context_data(**kwargs)
context['gym'] = self.gym
return context
diff --git a/wger/gym/views/contract_type.py b/wger/gym/views/contract_type.py
index ee89a947e..b37516dc2 100644
--- a/wger/gym/views/contract_type.py
+++ b/wger/gym/views/contract_type.py
@@ -52,9 +52,9 @@ logger = logging.getLogger(__name__)
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new contract type
- '''
+ """
model = ContractType
fields = ('name', 'description')
@@ -63,15 +63,15 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
member = None
def get_success_url(self):
- '''
+ """
Redirect back to overview page
- '''
+ """
return reverse('gym:contract_type:list', kwargs={'gym_pk': self.object.gym_id})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -81,16 +81,16 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
- '''
+ """
Set the foreign key to the gym object
- '''
+ """
form.instance.gym_id = self.kwargs['gym_pk']
return super(AddView, self).form_valid(form)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(AddView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:contract_type:add',
kwargs={'gym_pk': self.kwargs['gym_pk']})
@@ -98,9 +98,9 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing contract option
- '''
+ """
model = ContractType
fields = ('name', 'description')
@@ -108,9 +108,9 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
form_action_urlname = 'gym:contract_type:edit'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -121,24 +121,24 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
- '''
+ """
Redirect back to overview page
- '''
+ """
return reverse('gym:contract_type:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UpdateView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing contract type
- '''
+ """
model = ContractType
fields = ('name', 'description')
@@ -146,9 +146,9 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
form_action_urlname = 'gym:contract_type:delete'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -159,39 +159,39 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
- '''
+ """
Redirect back to overview page
- '''
+ """
return reverse('gym:contract_type:list', kwargs={'gym_pk': self.object.gym_id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}').format(self.object)
return context
class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available contract options
- '''
+ """
model = ContractType
permission_required = 'gym.add_contracttype'
template_name = 'contract_type/list.html'
gym = None
def get_queryset(self):
- '''
+ """
Only contract types for current gym
- '''
+ """
return ContractType.objects.filter(gym=self.gym)
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only list contract types in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -202,9 +202,9 @@ class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, Li
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ListView, self).get_context_data(**kwargs)
context['gym'] = self.gym
return context
diff --git a/wger/gym/views/document.py b/wger/gym/views/document.py
index aa8ef60a7..b13e4bf91 100644
--- a/wger/gym/views/document.py
+++ b/wger/gym/views/document.py
@@ -49,24 +49,24 @@ logger = logging.getLogger(__name__)
class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available admin notes
- '''
+ """
model = UserDocument
permission_required = 'gym.add_userdocument'
template_name = 'document/list.html'
member = None
def get_queryset(self):
- '''
+ """
Only documents for current user
- '''
+ """
return UserDocument.objects.filter(member_id=self.kwargs['user_pk'])
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add notes to users in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -77,9 +77,9 @@ class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, Li
return super(ListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ListView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:document:add',
kwargs={'user_pk': self.kwargs['user_pk']})
@@ -88,9 +88,9 @@ class ListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, Li
class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new document
- '''
+ """
model = UserDocument
fields = '__all__'
@@ -99,15 +99,15 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
member = None
def get_success_url(self):
- '''
+ """
Redirect back to user page
- '''
+ """
return reverse('gym:document:list', kwargs={'user_pk': self.member.pk})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Can only add documents to users in own gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -118,9 +118,9 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
return super(AddView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
- '''
+ """
Set user instances
- '''
+ """
form.instance.original_name = form.cleaned_data['document'].name
if not form.cleaned_data['name']:
form.instance.name = form.cleaned_data['document'].name
@@ -129,9 +129,9 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
return super(AddView, self).form_valid(form)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(AddView, self).get_context_data(**kwargs)
context['enctype'] = 'multipart/form-data'
context['form_action'] = reverse('gym:document:add',
@@ -140,25 +140,25 @@ class AddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Create
class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing document
- '''
+ """
fields = '__all__'
model = UserDocument
permission_required = 'gym.change_userdocument'
def get_success_url(self):
- '''
+ """
Redirect back to user page
- '''
+ """
return reverse('gym:document:list', kwargs={'user_pk':
self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only trainers for this gym can edit user notes
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -169,9 +169,9 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(UpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:document:edit', kwargs={'pk': self.object.id})
context['title'] = _(u'Edit {0}').format(self.object)
@@ -179,24 +179,24 @@ class UpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Upd
class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing document
- '''
+ """
model = UserDocument
fields = ('document', 'name', 'note')
permission_required = 'gym.delete_userdocument'
def get_success_url(self):
- '''
+ """
Redirect back to user page
- '''
+ """
return reverse('gym:document:list', kwargs={'user_pk': self.object.member.pk})
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only trainers for this gym can delete documents
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -206,9 +206,9 @@ class DeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, D
return super(DeleteView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(DeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
context['form_action'] = reverse('gym:document:delete', kwargs={'pk': self.kwargs['pk']})
diff --git a/wger/gym/views/export.py b/wger/gym/views/export.py
index 55165050b..2f9bb1b8c 100644
--- a/wger/gym/views/export.py
+++ b/wger/gym/views/export.py
@@ -37,9 +37,9 @@ logger = logging.getLogger(__name__)
@login_required
def users(request, gym_pk):
- '''
+ """
Exports all members in selected gym
- '''
+ """
gym = get_object_or_404(Gym, pk=gym_pk)
if not request.user.has_perm('gym.manage_gyms') \
diff --git a/wger/gym/views/gym.py b/wger/gym/views/gym.py
index 97cf80c44..11a64cfdf 100644
--- a/wger/gym/views/gym.py
+++ b/wger/gym/views/gym.py
@@ -82,17 +82,17 @@ logger = logging.getLogger(__name__)
class GymListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Overview of all available gyms
- '''
+ """
model = Gym
permission_required = 'gym.manage_gyms'
template_name = 'gym/list.html'
def get_context_data(self, **kwargs):
- '''
+ """
Pass other info to the template
- '''
+ """
context = super(GymListView, self).get_context_data(**kwargs)
context['global_gym_config'] = GlobalGymConfig.objects.all().first()
return context
@@ -100,17 +100,17 @@ class GymListView(LoginRequiredMixin, PermissionRequiredMixin, UAAwareViewMixin,
class GymUserListView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin,
UAAwareViewMixin, ListView):
- '''
+ """
Overview of all users for a specific gym
- '''
+ """
model = User
permission_required = ('gym.manage_gym', 'gym.gym_trainer', 'gym.manage_gyms')
template_name = 'gym/member_list.html'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only managers and trainers for this gym can access the members
- '''
+ """
if request.user.has_perm('gym.manage_gyms') \
or ((request.user.has_perm('gym.manage_gym')
or request.user.has_perm('gym.gym_trainer'))
@@ -119,9 +119,9 @@ class GymUserListView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin,
return HttpResponseForbidden()
def get_queryset(self):
- '''
+ """
Return a list with the users, not really a queryset.
- '''
+ """
out = {'admins': [],
'members': []}
@@ -140,9 +140,9 @@ class GymUserListView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin,
return out
def get_context_data(self, **kwargs):
- '''
+ """
Pass other info to the template
- '''
+ """
context = super(GymUserListView, self).get_context_data(**kwargs)
context['gym'] = Gym.objects.get(pk=self.kwargs['pk'])
context['admin_count'] = len(context['object_list']['admins'])
@@ -153,9 +153,9 @@ class GymUserListView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin,
class GymAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView):
- '''
+ """
View to add a new gym
- '''
+ """
model = Gym
fields = '__all__'
@@ -166,9 +166,9 @@ class GymAddView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, Cre
@login_required
def gym_new_user_info(request):
- '''
+ """
Shows info about a newly created user
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -186,9 +186,9 @@ def gym_new_user_info(request):
@login_required
def gym_new_user_info_export(request):
- '''
+ """
Exports the info of newly created user
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -223,9 +223,9 @@ def gym_new_user_info_export(request):
def reset_user_password(request, user_pk):
- '''
+ """
Resets the password of the selected user to random password
- '''
+ """
user = get_object_or_404(User, pk=user_pk)
@@ -250,9 +250,9 @@ def reset_user_password(request, user_pk):
def gym_permissions_user_edit(request, user_pk):
- '''
+ """
Edits the permissions of a gym member
- '''
+ """
member = get_object_or_404(User, pk=user_pk)
user = request.user
@@ -323,9 +323,9 @@ class GymAddUserView(WgerFormMixin,
LoginRequiredMixin,
WgerMultiplePermissionRequiredMixin,
CreateView):
- '''
+ """
View to add a user to a new gym
- '''
+ """
model = User
title = ugettext_lazy('Add user to gym')
@@ -334,15 +334,15 @@ class GymAddUserView(WgerFormMixin,
form_class = GymUserAddForm
def get_initial(self):
- '''
+ """
Pre-select the 'user' role
- '''
+ """
return {'role': ['user']}
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only managers for this gym can add new members
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -360,16 +360,16 @@ class GymAddUserView(WgerFormMixin,
return super(GymAddUserView, self).dispatch(request, *args, **kwargs)
def get_form(self):
- '''
+ """
Set available user permissions
- '''
+ """
return self.form_class(available_roles=get_permission_list(self.request.user),
**self.get_form_kwargs())
def form_valid(self, form):
- '''
+ """
Create the user, set the user permissions and gym
- '''
+ """
gym = Gym.objects.get(pk=self.kwargs['gym_pk'])
password = password_generator()
user = User.objects.create_user(form.cleaned_data['username'],
@@ -410,9 +410,9 @@ class GymAddUserView(WgerFormMixin,
return super(GymAddUserView, self).form_valid(form)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(GymAddUserView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:gym:add-user',
kwargs={'gym_pk': self.kwargs['gym_pk']})
@@ -420,9 +420,9 @@ class GymAddUserView(WgerFormMixin,
class GymUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing gym
- '''
+ """
model = Gym
fields = '__all__'
@@ -430,9 +430,9 @@ class GymUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin,
permission_required = 'gym.change_gym'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only managers for this gym and general managers can edit the gym
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -443,9 +443,9 @@ class GymUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin,
return super(GymUpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(GymUpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:gym:edit', kwargs={'pk': self.object.id})
context['title'] = _(u'Edit {0}').format(self.object)
@@ -453,9 +453,9 @@ class GymUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin,
class GymDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
- '''
+ """
View to delete an existing gym
- '''
+ """
model = Gym
fields = ('name',
@@ -469,9 +469,9 @@ class GymDeleteView(WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin
permission_required = 'gym.delete_gym'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(GymDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
context['form_action'] = reverse('gym:gym:delete', kwargs={'pk': self.kwargs['pk']})
diff --git a/wger/gym/views/user_config.py b/wger/gym/views/user_config.py
index 09fdc7bbf..f1efb2ba9 100644
--- a/wger/gym/views/user_config.py
+++ b/wger/gym/views/user_config.py
@@ -36,18 +36,18 @@ logger = logging.getLogger(__name__)
class ConfigUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
View to update an existing user gym configuration
- '''
+ """
model = GymUserConfig
fields = '__all__'
permission_required = 'gym.change_gymuserconfig'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Only managers for this gym can edit the user settings
- '''
+ """
if not request.user.is_authenticated:
return HttpResponseForbidden()
@@ -59,15 +59,15 @@ class ConfigUpdateView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixi
return super(ConfigUpdateView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
- '''
+ """
Return to the gym user overview
- '''
+ """
return reverse('gym:gym:user-list', kwargs={'pk': self.object.gym.pk})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ConfigUpdateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('gym:user_config:edit', kwargs={'pk': self.object.id})
context['title'] = _('Configuration')
diff --git a/wger/manager/api/resources.py b/wger/manager/api/resources.py
index d3336a9f0..066e10cc9 100644
--- a/wger/manager/api/resources.py
+++ b/wger/manager/api/resources.py
@@ -44,16 +44,16 @@ from wger.utils.resources import UserObjectsOnlyAuthorization
class WorkoutResource(ModelResource):
- '''
+ """
Resource for workouts
- '''
+ """
days = fields.ToManyField('wger.manager.api.resources.DayResource', 'day_set')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(user=bundle.request.user)
class Meta:
@@ -66,16 +66,16 @@ class WorkoutResource(ModelResource):
class WorkoutSessionResource(ModelResource):
- '''
+ """
Resource for workout sessions
- '''
+ """
workout = fields.ToOneField('wger.manager.api.resources.WorkoutResource', 'workout')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(user=bundle.request.user)
class Meta:
@@ -89,17 +89,17 @@ class WorkoutSessionResource(ModelResource):
class ScheduleStepResource(ModelResource):
- '''
+ """
Resource for schedule steps
- '''
+ """
workout = fields.ToOneField(WorkoutResource, 'workout')
schedule = fields.ToOneField('wger.manager.api.resources.ScheduleResource', 'schedule')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(schedule__user=bundle.request.user)
class Meta:
@@ -112,16 +112,16 @@ class ScheduleStepResource(ModelResource):
class ScheduleResource(ModelResource):
- '''
+ """
Resource for schedules
- '''
+ """
steps = fields.ToManyField(ScheduleStepResource, 'schedulestep_set')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(user=bundle.request.user)
class Meta:
@@ -135,17 +135,17 @@ class ScheduleResource(ModelResource):
class DayResource(ModelResource):
- '''
+ """
Resource for training days
- '''
+ """
workout = fields.ToOneField(WorkoutResource, 'training')
days_of_week = fields.ToManyField(DaysOfWeekResource, 'day')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(training__user=bundle.request.user)
class Meta:
@@ -158,17 +158,17 @@ class DayResource(ModelResource):
class SetResource(ModelResource):
- '''
+ """
Resource for training sets
- '''
+ """
day = fields.ToOneField(DayResource, 'exerciseday')
exercises = fields.ToManyField(ExerciseResource, 'exercises')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(exerciseday__training__user=bundle.request.user)
class Meta:
@@ -182,17 +182,17 @@ class SetResource(ModelResource):
class SettingResource(ModelResource):
- '''
+ """
Resource for training settings
- '''
+ """
set = fields.ToOneField(SetResource, 'set')
exercise = fields.ToOneField(ExerciseResource, 'exercise')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(set__exerciseday__training__user=bundle.request.user)
class Meta:
@@ -207,17 +207,17 @@ class SettingResource(ModelResource):
class WorkoutLogResource(ModelResource):
- '''
+ """
Resource for a workout log
- '''
+ """
exercise = fields.ToOneField(ExerciseResource, 'exercise')
workout = fields.ToOneField(WorkoutResource, 'workout')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(user=bundle.request.user)
class Meta:
diff --git a/wger/manager/api/serializers.py b/wger/manager/api/serializers.py
index 6601b824e..a084aa79a 100644
--- a/wger/manager/api/serializers.py
+++ b/wger/manager/api/serializers.py
@@ -38,9 +38,9 @@ from wger.manager.models import (
class WorkoutSerializer(serializers.ModelSerializer):
- '''
+ """
Workout serializer
- '''
+ """
class Meta:
model = Workout
@@ -48,45 +48,45 @@ class WorkoutSerializer(serializers.ModelSerializer):
class WorkoutSessionSerializer(serializers.ModelSerializer):
- '''
+ """
Workout session serializer
- '''
+ """
class Meta:
model = WorkoutSession
exclude = ('user',)
class WorkoutLogSerializer(serializers.ModelSerializer):
- '''
+ """
Workout session serializer
- '''
+ """
class Meta:
model = WorkoutLog
exclude = ('user',)
class ScheduleStepSerializer(serializers.ModelSerializer):
- '''
+ """
ScheduleStep serializer
- '''
+ """
class Meta:
model = ScheduleStep
fields = '__all__'
class ScheduleSerializer(serializers.ModelSerializer):
- '''
+ """
Schedule serializer
- '''
+ """
class Meta:
model = Schedule
exclude = ('user',)
class DaySerializer(serializers.ModelSerializer):
- '''
+ """
Workout day serializer
- '''
+ """
class Meta:
model = Day
@@ -94,9 +94,9 @@ class DaySerializer(serializers.ModelSerializer):
class SetSerializer(serializers.ModelSerializer):
- '''
+ """
Workout setting serializer
- '''
+ """
class Meta:
model = Set
@@ -104,9 +104,9 @@ class SetSerializer(serializers.ModelSerializer):
class SettingSerializer(serializers.ModelSerializer):
- '''
+ """
Workout setting serializer
- '''
+ """
class Meta:
model = Setting
fields = '__all__'
@@ -116,9 +116,9 @@ class SettingSerializer(serializers.ModelSerializer):
# Custom helper serializers for the canonical form of a workout
#
class WorkoutCanonicalFormExerciseListSerializer(serializers.Serializer):
- '''
+ """
Serializer for settings in the canonical form of a workout
- '''
+ """
setting_obj_list = SettingSerializer(many=True)
setting_list = serializers.ReadOnlyField()
reps_list = serializers.ReadOnlyField()
@@ -132,9 +132,9 @@ class WorkoutCanonicalFormExerciseListSerializer(serializers.Serializer):
class WorkoutCanonicalFormExerciseSerializer(serializers.Serializer):
- '''
+ """
Serializer for an exercise in the canonical form of a workout
- '''
+ """
obj = SetSerializer()
exercise_list = WorkoutCanonicalFormExerciseListSerializer(many=True)
has_settings = serializers.BooleanField()
@@ -143,9 +143,9 @@ class WorkoutCanonicalFormExerciseSerializer(serializers.Serializer):
class DaysOfWeekCanonicalFormSerializer(serializers.Serializer):
- '''
+ """
Serializer for a days of week in the canonical form of a workout
- '''
+ """
text = serializers.ReadOnlyField()
day_list = serializers.ListField(
child=DaysOfWeekSerializer()
@@ -153,9 +153,9 @@ class DaysOfWeekCanonicalFormSerializer(serializers.Serializer):
class DayCanonicalFormSerializer(serializers.Serializer):
- '''
+ """
Serializer for a day in the canonical form of a workout
- '''
+ """
obj = DaySerializer()
set_list = WorkoutCanonicalFormExerciseSerializer(many=True)
days_of_week = DaysOfWeekCanonicalFormSerializer()
@@ -163,9 +163,9 @@ class DayCanonicalFormSerializer(serializers.Serializer):
class WorkoutCanonicalFormSerializer(serializers.Serializer):
- '''
+ """
Serializer for the canonical form of a workout
- '''
+ """
obj = WorkoutSerializer()
muscles = serializers.ReadOnlyField()
day_list = DayCanonicalFormSerializer(many=True)
diff --git a/wger/manager/api/views.py b/wger/manager/api/views.py
index e936f139d..f0d244b5c 100644
--- a/wger/manager/api/views.py
+++ b/wger/manager/api/views.py
@@ -49,9 +49,9 @@ from wger.utils.viewsets import WgerOwnerObjectModelViewSet
class WorkoutViewSet(viewsets.ModelViewSet):
- '''
+ """
API endpoint for workout objects
- '''
+ """
serializer_class = WorkoutSerializer
is_private = True
ordering_fields = '__all__'
@@ -59,33 +59,33 @@ class WorkoutViewSet(viewsets.ModelViewSet):
'creation_date')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return Workout.objects.filter(user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the owner
- '''
+ """
serializer.save(user=self.request.user)
@action(detail=True)
def canonical_representation(self, request, pk):
- '''
+ """
Output the canonical representation of a workout
This is basically the same form as used in the application
- '''
+ """
out = WorkoutCanonicalFormSerializer(self.get_object().canonical_representation).data
return Response(out)
class WorkoutSessionViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for workout sessions objects
- '''
+ """
serializer_class = WorkoutSessionSerializer
is_private = True
ordering_fields = '__all__'
@@ -97,29 +97,29 @@ class WorkoutSessionViewSet(WgerOwnerObjectModelViewSet):
'time_end')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return WorkoutSession.objects.filter(user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the owner
- '''
+ """
today = datetime.date.today()
serializer.save(date=today, user=self.request.user)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(Workout, 'workout')]
class ScheduleStepViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for schedule step objects
- '''
+ """
serializer_class = ScheduleStepSerializer
is_private = True
ordering_fields = '__all__'
@@ -129,23 +129,23 @@ class ScheduleStepViewSet(WgerOwnerObjectModelViewSet):
'order')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return ScheduleStep.objects.filter(schedule__user=self.request.user)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(Workout, 'workout'),
(Schedule, 'schedule')]
class ScheduleViewSet(viewsets.ModelViewSet):
- '''
+ """
API endpoint for schedule objects
- '''
+ """
serializer_class = ScheduleSerializer
is_private = True
ordering_fields = '__all__'
@@ -155,22 +155,22 @@ class ScheduleViewSet(viewsets.ModelViewSet):
'name')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return Schedule.objects.filter(user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the owner
- '''
+ """
serializer.save(user=self.request.user)
class DayViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for training day objects
- '''
+ """
serializer_class = DaySerializer
is_private = True
ordering_fields = '__all__'
@@ -179,22 +179,22 @@ class DayViewSet(WgerOwnerObjectModelViewSet):
'day')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return Day.objects.filter(training__user=self.request.user)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(Workout, 'training')]
class SetViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for workout set objects
- '''
+ """
serializer_class = SetSerializer
is_private = True
ordering_fields = '__all__'
@@ -204,22 +204,22 @@ class SetViewSet(WgerOwnerObjectModelViewSet):
'exercises')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return Set.objects.filter(exerciseday__training__user=self.request.user)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(Day, 'exerciseday')]
class SettingViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for repetition setting objects
- '''
+ """
serializer_class = SettingSerializer
is_private = True
ordering_fields = '__all__'
@@ -231,28 +231,28 @@ class SettingViewSet(WgerOwnerObjectModelViewSet):
'order')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return Setting.objects.filter(set__exerciseday__training__user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the order
- '''
+ """
serializer.save(order=1)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(Set, 'set')]
class WorkoutLogViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for workout log objects
- '''
+ """
serializer_class = WorkoutLogSerializer
is_private = True
ordering_fields = '__all__'
@@ -263,20 +263,20 @@ class WorkoutLogViewSet(WgerOwnerObjectModelViewSet):
'workout')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return WorkoutLog.objects.filter(user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the owner
- '''
+ """
serializer.save(user=self.request.user)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(Workout, 'workout')]
diff --git a/wger/manager/forms.py b/wger/manager/forms.py
index d6544af06..dcef77d6e 100644
--- a/wger/manager/forms.py
+++ b/wger/manager/forms.py
@@ -14,9 +14,9 @@
#
# You should have received a copy of the GNU Affero General Public License
-'''
+"""
This file contains forms used in the application
-'''
+"""
# Django
from django.forms import (
@@ -101,9 +101,9 @@ class SetForm(ModelForm):
class SetFormMobile(ModelForm):
- '''
+ """
Don't use the auto completer when accessing the mobile version
- '''
+ """
class Meta:
model = Set
exclude = ('order', 'exerciseday')
@@ -132,18 +132,18 @@ class SettingForm(ModelForm):
class HelperDateForm(Form):
- '''
+ """
A helper form used in the workout log view
- '''
+ """
date = DateField(input_formats=DATE_FORMATS, widget=Html5DateInput())
class WorkoutLogForm(ModelForm):
- '''
+ """
Helper form for a WorkoutLog.
These fields are re-defined here only to make them optional
- '''
+ """
repetition_unit = ModelChoiceField(queryset=RepetitionUnit.objects.all(),
label=_('Unit'),
required=False)
@@ -165,27 +165,27 @@ class WorkoutLogForm(ModelForm):
class HelperWorkoutSessionForm(ModelForm):
- '''
+ """
A helper form used in the workout log view
- '''
+ """
class Meta:
model = WorkoutSession
exclude = ('user', 'workout', 'date')
class WorkoutSessionForm(ModelForm):
- '''
+ """
Workout Session form
- '''
+ """
class Meta:
model = WorkoutSession
exclude = ('user', 'workout', 'date')
class WorkoutSessionHiddenFieldsForm(ModelForm):
- '''
+ """
Workout Session form used in the timer view
- '''
+ """
class Meta:
model = WorkoutSession
exclude = []
diff --git a/wger/manager/helpers.py b/wger/manager/helpers.py
index f275a39d6..7ddf1d393 100644
--- a/wger/manager/helpers.py
+++ b/wger/manager/helpers.py
@@ -41,7 +41,7 @@ from wger.utils.pdf import styleSheet
def render_workout_day(day, nr_of_weeks=7, images=False, comments=False, only_table=False):
- '''
+ """
Render a table with reportlab with the contents of the training day
:param day: a workout day object
@@ -52,7 +52,7 @@ def render_workout_day(day, nr_of_weeks=7, images=False, comments=False, only_ta
be rendered as well
:param only_table: boolean indicating whether to draw a table with space
for weight logs or just a list of the exercises
- '''
+ """
# If rendering only the table, reset the nr of weeks, since these columns
# will not be rendered anyway.
@@ -194,7 +194,7 @@ def render_workout_day(day, nr_of_weeks=7, images=False, comments=False, only_ta
def reps_smart_text(settings, set_obj):
- '''
+ """
"Smart" textual representation
This is a human representation of the settings, in a way that humans
@@ -205,15 +205,15 @@ def reps_smart_text(settings, set_obj):
:param settings:
:param set_obj:
:return setting_text, setting_list:
- '''
+ """
def get_reps_reprentation(setting, rep_unit):
- '''
+ """
Returns the representation for the repetitions for a setting
This is basically just to allow for a special representation for the
"Until Failure" unit
- '''
+ """
if setting.repetition_unit_id != 2:
reps = "{0} {1}".format(setting.reps, rep_unit).strip()
else:
@@ -221,12 +221,12 @@ def reps_smart_text(settings, set_obj):
return reps
def get_weight_unit_reprentation(setting):
- '''
+ """
Returns the representation for the weight unit for a setting
This is basically just to allow for a special representation for the
"Repetition" and "Until Failure" unit
- '''
+ """
if setting.repetition_unit.id not in (1, 2):
rep_unit = _(setting.repetition_unit.name)
else:
@@ -234,11 +234,11 @@ def reps_smart_text(settings, set_obj):
return rep_unit
def normalize_weight(setting):
- '''
+ """
The weight can be None, or a decimal. In that case, normalize so
that we don't return e.g. '15.00', but always '15', independently of
the database used.
- '''
+ """
if setting.weight:
weight = normalize_decimal(setting.weight)
else:
@@ -307,10 +307,10 @@ def reps_smart_text(settings, set_obj):
class WorkoutCalendar(HTMLCalendar):
- '''
+ """
A calendar renderer, see this blog entry for details:
* http://uggedal.com/journal/creating-a-flexible-monthly-calendar-in-django/
- '''
+ """
def __init__(self, workout_logs, *args, **kwargs):
super(WorkoutCalendar, self).__init__(*args, **kwargs)
self.workout_logs = workout_logs
@@ -363,10 +363,10 @@ class WorkoutCalendar(HTMLCalendar):
return self.day_cell(cssclass, '{0}'.format(''.join(body)))
def formatmonth(self, year, month):
- '''
+ """
Format the table header. This is basically the same code from python's
calendar module but with additional bootstrap classes
- '''
+ """
self.year, self.month = year, month
out = []
out.append('<table class="month table table-bordered">\n')
@@ -381,7 +381,7 @@ class WorkoutCalendar(HTMLCalendar):
return ''.join(out)
def day_cell(self, cssclass, body):
- '''
+ """
Renders a day cell
- '''
+ """
return '<td class="{0}" style="vertical-align: middle;">{1}</td>'.format(cssclass, body)
diff --git a/wger/manager/management/commands/email-reminders.py b/wger/manager/management/commands/email-reminders.py
index 120149ac5..81ae84dba 100644
--- a/wger/manager/management/commands/email-reminders.py
+++ b/wger/manager/management/commands/email-reminders.py
@@ -32,16 +32,16 @@ from wger.manager.models import Schedule
class Command(BaseCommand):
- '''
+ """
Helper admin command to send out email reminders
- '''
+ """
help = 'Send out automatic email reminders for workouts'
def handle(self, **options):
- '''
+ """
Find if the currently active workout is overdue
- '''
+ """
profile_list = UserProfile.objects.filter(workout_reminder_active=True)
counter = 0
for profile in profile_list:
@@ -99,13 +99,13 @@ class Command(BaseCommand):
@staticmethod
def send_email(user, workout, delta):
- '''
+ """
Notify a user that a workout is about to expire
:type user User
:type workout Workout
:type delta datetime.timedelta
- '''
+ """
# Update the last notification date field
user.userprofile.last_workout_notification = datetime.date.today()
diff --git a/wger/manager/migrations/0007_auto_20160311_2258.py b/wger/manager/migrations/0007_auto_20160311_2258.py
index c9f048b78..5532fb109 100644
--- a/wger/manager/migrations/0007_auto_20160311_2258.py
+++ b/wger/manager/migrations/0007_auto_20160311_2258.py
@@ -5,9 +5,9 @@ from django.db import migrations, models
def convert_logs(apps, schema_editor):
- '''
+ """
Adds a unit to users who have imperial units in the profile
- '''
+ """
WorkoutLog = apps.get_model('manager', 'WorkoutLog')
UserProfile = apps.get_model('core', 'UserProfile')
@@ -17,9 +17,9 @@ def convert_logs(apps, schema_editor):
def convert_settings(apps, schema_editor):
- '''
+ """
Adds a unit to workout settings that have 99 for 'until failure'
- '''
+ """
Setting = apps.get_model('manager', 'Setting')
Setting.objects.filter(reps=99).update(reps=1, repetition_unit=2)
diff --git a/wger/manager/models.py b/wger/manager/models.py
index a1e0408ae..89173baaa 100644
--- a/wger/manager/models.py
+++ b/wger/manager/models.py
@@ -60,14 +60,14 @@ logger = logging.getLogger(__name__)
# Classes
#
class Workout(models.Model):
- '''
+ """
Model for a training schedule
- '''
+ """
class Meta:
- '''
+ """
Meta class to set some other properties
- '''
+ """
ordering = ["-creation_date", ]
creation_date = models.DateField(_('Creation date'), auto_now_add=True)
@@ -79,49 +79,49 @@ class Workout(models.Model):
user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE)
def get_absolute_url(self):
- '''
+ """
Returns the canonical URL to view a workout
- '''
+ """
return reverse('manager:workout:view', kwargs={'pk': self.id})
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
if self.comment:
return u"{0}".format(self.comment)
else:
return u"{0} ({1})".format(_('Workout'), self.creation_date)
def save(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
reset_workout_canonical_form(self.id)
super(Workout, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
reset_workout_canonical_form(self.id)
super(Workout, self).delete(*args, **kwargs)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self
@property
def canonical_representation(self):
- '''
+ """
Returns a canonical representation of the workout
This form makes it easier to cache and use everywhere where all or part
of a workout structure is needed. As an additional benefit, the template
caches are not needed anymore.
- '''
+ """
workout_canonical_form = cache.get(cache_mapper.get_workout_canonical(self.pk))
if not workout_canonical_form:
day_canonical_repr = []
@@ -166,16 +166,16 @@ class Workout(models.Model):
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
:rtype : list
- '''
+ """
# Try first to find an active schedule that has steps
try:
@@ -207,35 +207,35 @@ class ScheduleManager(models.Manager):
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'''
+ """Custom manager"""
user = models.ForeignKey(User,
verbose_name=_('User'),
editable=False,
on_delete=models.CASCADE)
- '''
+ """
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
- '''
+ """
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.'''
+ """Name or short description of the schedule."""
start_date = Html5DateField(verbose_name=_('Start date'),
default=datetime.date.today)
- '''The start date of this schedule'''
+ """The start date of this schedule"""
is_active = models.BooleanField(verbose_name=_('Schedule active'),
default=True,
@@ -243,33 +243,33 @@ class Schedule(models.Model):
"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)'''
+ """A flag indicating whether the schedule is active (needed for dashboard)"""
is_loop = models.BooleanField(verbose_name=_('Is a 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'''
+ """A flag indicating whether the schedule should act as a loop"""
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
def get_absolute_url(self):
return reverse('manager:schedule:view', kwargs={'pk': self.id})
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
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
@@ -277,9 +277,9 @@ class Schedule(models.Model):
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()
start_date = self.start_date
found = False
@@ -298,10 +298,10 @@ class Schedule(models.Model):
return False
def get_end_date(self):
- '''
+ """
Calculates the date when the schedule is over or None is the schedule
is a loop.
- '''
+ """
if self.is_loop:
return None
@@ -312,52 +312,52 @@ class Schedule(models.Model):
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'),
on_delete=models.CASCADE)
- '''The schedule is step belongs to'''
+ """The schedule is step belongs to"""
workout = models.ForeignKey(Workout, on_delete=models.CASCADE)
- '''The workout this step manages'''
+ """The workout this step manages"""
duration = models.IntegerField(verbose_name=_('Duration'),
help_text=_('The duration in weeks'),
default=4,
validators=[MinValueValidator(1), MaxValueValidator(25)])
- '''The duration in weeks'''
+ """The duration in weeks"""
order = models.IntegerField(verbose_name=_('Order'),
default=1)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self.workout
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.workout.comment
def get_dates(self):
- '''
+ """
Calculate the start and end date for this step
- '''
+ """
steps = self.schedule.schedulestep_set.all()
start_date = end_date = self.schedule.start_date
@@ -376,9 +376,9 @@ class ScheduleStep(models.Model):
class Day(models.Model):
- '''
+ """
Model for a training day
- '''
+ """
training = models.ForeignKey(Workout,
verbose_name=_('Workout'), on_delete=models.CASCADE)
@@ -391,57 +391,57 @@ class Day(models.Model):
verbose_name=_('Day'))
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.description
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self.training
@property
def get_first_day_id(self):
- '''
+ """
Return the PK of the first day of the week, this is used in the template
to order the days in the template
- '''
+ """
return self.day.all()[0].pk
def save(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
reset_workout_canonical_form(self.training_id)
super(Day, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
reset_workout_canonical_form(self.training_id)
super(Day, self).delete(*args, **kwargs)
@property
def canonical_representation(self):
- '''
+ """
Return the canonical representation for this day
This is extracted from the workout representation because that one is cached
and this isn't.
- '''
+ """
for i in self.training.canonical_representation['day_list']:
if int(i['obj'].pk) == int(self.pk):
return i
def get_canonical_representation(self):
- '''
+ """
Creates a canonical representation for this day
- '''
+ """
canonical_repr = []
muscles_front = []
muscles_back = []
@@ -551,9 +551,9 @@ class Day(models.Model):
class Set(models.Model):
- '''
+ """
Model for a set of exercises
- '''
+ """
DEFAULT_SETS = 4
MAX_SETS = 10
@@ -574,38 +574,38 @@ class Set(models.Model):
ordering = ["order", ]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"Set-ID {0}".format(self.id)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self.exerciseday.training
def save(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
reset_workout_canonical_form(self.exerciseday.training_id)
super(Set, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset all cached infos
- '''
+ """
reset_workout_canonical_form(self.exerciseday.training_id)
super(Set, self).delete(*args, **kwargs)
class Setting(models.Model):
- '''
+ """
Settings for an exercise (weight, reps, etc.)
- '''
+ """
set = models.ForeignKey(Set, verbose_name=_('Sets'), on_delete=models.CASCADE)
exercise = models.ForeignKey(Exercise,
@@ -615,18 +615,18 @@ class Setting(models.Model):
verbose_name=_('Unit'),
default=1,
on_delete=models.CASCADE)
- '''
+ """
The repetition unit of a set. This can be e.g. a repetition, a minute, etc.
- '''
+ """
reps = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(600)],
verbose_name=_('Amount'))
- '''
+ """
Amount of repetitions, minutes, etc. for a set.
Note that since adding the unit field, the name is no longer correct, but is
kept for compatibility reasons (specially for the REST API).
- '''
+ """
weight = models.DecimalField(verbose_name=_('Weight'),
max_digits=6,
@@ -634,15 +634,15 @@ class Setting(models.Model):
blank=True,
null=True,
validators=[MinValueValidator(0), MaxValueValidator(1500)])
- '''Planed weight for the repetitions'''
+ """Planed weight for the repetitions"""
weight_unit = models.ForeignKey(WeightUnit,
verbose_name=_('Unit'),
default=1,
on_delete=models.CASCADE)
- '''
+ """
The weight unit of a set. This can be e.g. kg, lb, km/h, etc.
- '''
+ """
order = models.IntegerField(blank=True,
verbose_name=_('Order'))
@@ -655,15 +655,15 @@ class Setting(models.Model):
ordering = ["order", "id"]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"settings for exercise {0} in set {1}".format(self.exercise.id, self.set.id)
def save(self, *args, **kwargs):
- '''
+ """
Reset cache
- '''
+ """
reset_workout_canonical_form(self.set.exerciseday.training_id)
# If the user selected "Until Failure", do only 1 "repetition",
@@ -673,24 +673,24 @@ class Setting(models.Model):
super(Setting, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset cache
- '''
+ """
reset_workout_canonical_form(self.set.exerciseday.training_id)
super(Setting, self).delete(*args, **kwargs)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self.set.exerciseday.training
class WorkoutLog(models.Model):
- '''
+ """
A log entry for an exercise
- '''
+ """
user = models.ForeignKey(User,
verbose_name=_('User'),
@@ -707,18 +707,18 @@ class WorkoutLog(models.Model):
verbose_name=_('Unit'),
default=1,
on_delete=models.CASCADE)
- '''
+ """
The unit of the log. This can be e.g. a repetition, a minute, etc.
- '''
+ """
reps = models.IntegerField(verbose_name=_('Repetitions'),
validators=[MinValueValidator(0)])
- '''
+ """
Amount of repetitions, minutes, etc.
Note that since adding the unit field, the name is no longer correct, but is
kept for compatibility reasons (specially for the REST API).
- '''
+ """
weight = models.DecimalField(decimal_places=2,
max_digits=5,
@@ -729,9 +729,9 @@ class WorkoutLog(models.Model):
verbose_name=_('Unit'),
default=1,
on_delete=models.CASCADE)
- '''
+ """
The weight unit of the log. This can be e.g. kg, lb, km/h, etc.
- '''
+ """
date = Html5DateField(verbose_name=_('Date'))
@@ -740,25 +740,25 @@ class WorkoutLog(models.Model):
ordering = ["date", "reps"]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"Log entry: {0} - {1} kg on {2}".format(self.reps,
self.weight,
self.date)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self
def get_workout_session(self, date=None):
- '''
+ """
Returns the corresponding workout session
:return the WorkoutSession object or None if nothing was found
- '''
+ """
if not date:
date = self.date
@@ -768,9 +768,9 @@ class WorkoutLog(models.Model):
return None
def save(self, *args, **kwargs):
- '''
+ """
Reset cache
- '''
+ """
reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
# If the user selected "Until Failure", do only 1 "repetition",
@@ -780,17 +780,17 @@ class WorkoutLog(models.Model):
super(WorkoutLog, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset cache
- '''
+ """
reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
super(WorkoutLog, self).delete(*args, **kwargs)
class WorkoutSession(models.Model):
- '''
+ """
Model for a workout session
- '''
+ """
# Note: values hardcoded in manager.helpers.WorkoutCalendar
IMPRESSION_BAD = '1'
@@ -806,32 +806,32 @@ class WorkoutSession(models.Model):
user = models.ForeignKey(User,
verbose_name=_('User'),
on_delete=models.CASCADE)
- '''
+ """
The user the workout session belongs to
See note in weight.models.WeightEntry about why this is not editable=False
- '''
+ """
workout = models.ForeignKey(Workout,
verbose_name=_('Workout'),
on_delete=models.CASCADE)
- '''
+ """
The workout the session belongs to
- '''
+ """
date = Html5DateField(verbose_name=_('Date'))
- '''
+ """
The date the workout session was performed
- '''
+ """
notes = models.TextField(verbose_name=_('Notes'),
null=True,
blank=True,
help_text=_('Any notes you might want to save about this workout '
'session.'))
- '''
+ """
User notes about the workout
- '''
+ """
impression = models.CharField(verbose_name=_('General impression'),
max_length=2,
@@ -839,41 +839,41 @@ class WorkoutSession(models.Model):
default=IMPRESSION_NEUTRAL,
help_text=_('Your impression about this workout session. '
'Did you exercise as well as you could?'))
- '''
+ """
The user's general impression of workout
- '''
+ """
time_start = models.TimeField(verbose_name=_('Start time'),
blank=True,
null=True)
- '''
+ """
Time the workout session started
- '''
+ """
time_end = models.TimeField(verbose_name=_('Finish time'),
blank=True,
null=True)
- '''
+ """
Time the workout session ended
- '''
+ """
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{0} - {1}".format(self.workout, self.date)
class Meta:
- '''
+ """
Set other properties
- '''
+ """
ordering = ["date", ]
unique_together = ("date", "user")
def clean(self):
- '''
+ """
Perform some additional validations
- '''
+ """
if (not self.time_end and self.time_start) or (self.time_end and not self.time_start):
raise ValidationError(_("If you enter a time, you must enter both start and end time."))
@@ -882,21 +882,21 @@ class WorkoutSession(models.Model):
raise ValidationError(_("The start time cannot be after the end time."))
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self
def save(self, *args, **kwargs):
- '''
+ """
Reset cache
- '''
+ """
reset_workout_log(self.user_id, self.date.year, self.date.month)
super(WorkoutSession, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
- '''
+ """
Reset cache
- '''
+ """
reset_workout_log(self.user_id, self.date.year, self.date.month)
super(WorkoutSession, self).delete(*args, **kwargs)
diff --git a/wger/manager/signals.py b/wger/manager/signals.py
index 0a27c10c9..7999b5a93 100644
--- a/wger/manager/signals.py
+++ b/wger/manager/signals.py
@@ -36,9 +36,9 @@ from wger.utils.cache import delete_template_fragment_cache
def update_activity_cache(sender, instance, **kwargs):
- '''
+ """
Update the user's cached last activity date
- '''
+ """
user = instance.user
user.usercache.last_activity = get_user_last_activity(user)
diff --git a/wger/manager/tests/test_copy_workout.py b/wger/manager/tests/test_copy_workout.py
index 1859d7c4d..c4f5a330e 100644
--- a/wger/manager/tests/test_copy_workout.py
+++ b/wger/manager/tests/test_copy_workout.py
@@ -28,14 +28,14 @@ logger = logging.getLogger(__name__)
class CopyWorkoutTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests copying a workout
- '''
+ """
def copy_workout(self, owner=False):
- '''
+ """
Helper function to test copying workouts
- '''
+ """
# Open the copy workout form
response = self.client.get(reverse('manager:workout:copy', kwargs={'pk': '3'}))
@@ -94,17 +94,17 @@ class CopyWorkoutTestCase(WorkoutManagerTestCase):
self.assertEqual(exercises_original[k], exercises_copy[k])
def test_copy_workout_owner(self):
- '''
+ """
Test copying a workout as the owner user
- '''
+ """
self.user_login('test')
self.copy_workout(owner=True)
def test_copy_shared_not_allowed(self):
- '''
+ """
Test copying a workout from another shared user where user does not share workouts
- '''
+ """
profile = UserProfile.objects.get(user__username='test')
profile.ro_access = False
profile.save()
@@ -114,9 +114,9 @@ class CopyWorkoutTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 403)
def test_copy_shared_allowed(self):
- '''
+ """
Test copying a workout from another shared user where user does share workouts
- '''
+ """
profile = UserProfile.objects.get(user__username='test')
profile.ro_access = True
profile.save()
diff --git a/wger/manager/tests/test_day.py b/wger/manager/tests/test_day.py
index 4425dcd92..f02e37fd2 100644
--- a/wger/manager/tests/test_day.py
+++ b/wger/manager/tests/test_day.py
@@ -27,21 +27,21 @@ from wger.utils.cache import cache_mapper
class DayRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Day.objects.get(pk=1)), 'A day')
class AddWorkoutDayTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a day to a workout
- '''
+ """
object_class = Day
url = reverse('manager:day:add', kwargs={'workout_pk': 3})
@@ -52,14 +52,14 @@ class AddWorkoutDayTestCase(WorkoutManagerAddTestCase):
class DeleteWorkoutDayTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests deleting a day
- '''
+ """
def delete_day(self, fail=False):
- '''
+ """
Helper function to test deleting a day
- '''
+ """
# Fetch the day edit page
count_before = Day.objects.count()
@@ -77,33 +77,33 @@ class DeleteWorkoutDayTestCase(WorkoutManagerTestCase):
self.assertEqual(count_before - 1, count_after)
def test_delete_day_anonymous(self):
- '''
+ """
Test deleting a day as an anonymous user
- '''
+ """
self. delete_day(fail=True)
def test_delete_workout_owner(self):
- '''
+ """
Test deleting a day as the owner user
- '''
+ """
self.user_login('test')
self.delete_day(fail=False)
def test_delete_workout_other(self):
- '''
+ """
Test deleting a day as a different logged in user
- '''
+ """
self.user_login('admin')
self.delete_day(fail=True)
class EditWorkoutDayTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing the day of a Workout
- '''
+ """
object_class = Day
url = 'manager:day:edit'
@@ -115,14 +115,14 @@ class EditWorkoutDayTestCase(WorkoutManagerEditTestCase):
class RenderWorkoutDayTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests rendering a single workout day
- '''
+ """
def render_day(self, fail=False):
- '''
+ """
Helper function to test rendering a single workout day
- '''
+ """
# Fetch the day edit page
response = self.client.get(reverse('manager:day:view', kwargs={'id': 5}))
@@ -136,38 +136,38 @@ class RenderWorkoutDayTestCase(WorkoutManagerTestCase):
self.assertTemplateUsed('day/view.html')
def test_render_day_anonymous(self):
- '''
+ """
Test rendering a single workout day as an anonymous user
- '''
+ """
self.render_day(fail=True)
def test_render_workout_owner(self):
- '''
+ """
Test rendering a single workout day as the owner user
- '''
+ """
self.user_login('test')
self.render_day(fail=False)
def test_render_workout_other(self):
- '''
+ """
Test rendering a single workout day as a different logged in user
- '''
+ """
self.user_login('admin')
self.render_day(fail=True)
class WorkoutCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Workout cache test case
- '''
+ """
def test_canonical_form_cache_save(self):
- '''
+ """
Tests the workout cache when saving
- '''
+ """
day = Day.objects.get(pk=1)
day.canonical_representation
self.assertTrue(cache.get(cache_mapper.get_workout_canonical(day.training_id)))
@@ -176,9 +176,9 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_canonical(day.training_id)))
def test_canonical_form_cache_delete(self):
- '''
+ """
Tests the workout cache when deleting
- '''
+ """
day = Day.objects.get(pk=1)
day.canonical_representation
self.assertTrue(cache.get(cache_mapper.get_workout_canonical(day.training_id)))
@@ -188,14 +188,14 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
class DayTestCase(WorkoutManagerTestCase):
- '''
+ """
Other tests
- '''
+ """
def test_day_id_property(self):
- '''
+ """
Test that the attribute get_first_day_id works correctly
- '''
+ """
day = Day.objects.get(pk=5)
self.assertEqual(day.get_first_day_id, 3)
@@ -205,9 +205,9 @@ class DayTestCase(WorkoutManagerTestCase):
# class DayApiTestCase(api_base_test.ApiBaseResourceTestCase):
-# '''
+# """
# Tests the day API resource
-# '''
+# """
# pk = 5
# resource = Day
# private_resource = True
diff --git a/wger/manager/tests/test_email_reminder.py b/wger/manager/tests/test_email_reminder.py
index 94b2b31f9..8c849e20c 100644
--- a/wger/manager/tests/test_email_reminder.py
+++ b/wger/manager/tests/test_email_reminder.py
@@ -30,16 +30,16 @@ from wger.manager.models import (
class EmailReminderTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the email reminder command.
User 2 has setting in profile active
- '''
+ """
def test_reminder_no_workouts(self):
- '''
+ """
Test with no schedules or workouts
- '''
+ """
Schedule.objects.all().delete()
Workout.objects.all().delete()
@@ -47,11 +47,11 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_reminder_one_workout(self):
- '''
+ """
Test user with no schedules but one workout
User 2, workout created 2012-11-20
- '''
+ """
Schedule.objects.all().delete()
Workout.objects.exclude(user=User.objects.get(pk=2)).delete()
@@ -60,11 +60,11 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 1)
def test_reminder_skip_if_no_email(self):
- '''
+ """
Tests that no emails are sent if the user has provided no email
User 2, workout created 2012-11-20
- '''
+ """
user = User.objects.get(pk=2)
user.email = ''
@@ -77,12 +77,12 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_reminder_last_notification(self):
- '''
+ """
Test that no emails are sent if the last notification field is more
recent than one week.
User 2, workout created 2012-11-20
- '''
+ """
profile = UserProfile.objects.get(user=2)
profile.last_workout_notification = datetime.date.today() - datetime.timedelta(days=3)
@@ -95,12 +95,12 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_reminder_last_notification_2(self):
- '''
+ """
Test that no emails are sent if the last notification field is more
than one week away.
User 2, workout created 2012-11-20
- '''
+ """
profile = UserProfile.objects.get(user=2)
profile.last_workout_notification = datetime.date.today() - datetime.timedelta(days=10)
@@ -113,11 +113,11 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 1)
def test_reminder_last_notification_3(self):
- '''
+ """
Test that no emails are sent if the last notification field is null
User 2, workout created 2012-11-20
- '''
+ """
profile = UserProfile.objects.get(user=2)
profile.last_workout_notification = None
@@ -130,9 +130,9 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 1)
def test_reminder_setting_off(self):
- '''
+ """
Test user with no schedules, one workout but setting in profile off
- '''
+ """
user = User.objects.get(pk=2)
user.userprofile.workout_reminder_active = False
@@ -144,9 +144,9 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_reminder_empty_schedule(self):
- '''
+ """
Test user with emtpy schedules and no workouts
- '''
+ """
user = User.objects.get(pk=2)
user.userprofile.workout_reminder_active = False
@@ -165,9 +165,9 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_reminder_schedule(self):
- '''
+ """
Test user with a schedule and a workout
- '''
+ """
user = User.objects.get(pk=2)
Workout.objects.exclude(user=user).delete()
@@ -176,9 +176,9 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 1)
def test_reminder_schedule_recent(self):
- '''
+ """
Test user with a schedule that has not finished
- '''
+ """
user = User.objects.get(pk=1)
user.userprofile.workout_reminder_active = True
@@ -196,9 +196,9 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_reminder_schedule_recent_2(self):
- '''
+ """
Test user with a schedule that is about to finish
- '''
+ """
user = User.objects.get(pk=1)
user.userprofile.workout_reminder_active = True
@@ -217,9 +217,9 @@ class EmailReminderTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 1)
def test_reminder_schedule_recent_3(self):
- '''
+ """
Test user with a schedule that is about to finish
- '''
+ """
user = User.objects.get(pk=1)
user.userprofile.workout_reminder_active = True
diff --git a/wger/manager/tests/test_ical.py b/wger/manager/tests/test_ical.py
index 21b49c04f..7fdaef6c3 100644
--- a/wger/manager/tests/test_ical.py
+++ b/wger/manager/tests/test_ical.py
@@ -31,14 +31,14 @@ from wger.utils.helpers import (
class IcalToolsTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests some tools used for iCal generation
- '''
+ """
def test_next_weekday(self):
- '''
+ """
Test the next weekday function
- '''
+ """
start_date = datetime.date(2013, 12, 5)
# Find next monday
@@ -52,14 +52,14 @@ class IcalToolsTestCase(WorkoutManagerTestCase):
class WorkoutICalExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests exporting the ical file for a workout
- '''
+ """
def export_ical_token(self):
- '''
+ """
Helper function that checks exporing an ical file using tokens for access
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
@@ -77,9 +77,9 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):
self.assertLess(len(response.content), 560)
def export_ical_token_wrong(self):
- '''
+ """
Helper function that checks exporing an ical file using a wrong token
- '''
+ """
uid = 'AB'
token = 'abc-11223344556677889900'
@@ -90,9 +90,9 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 403)
def export_ical(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('manager:workout:ical', kwargs={'pk': 3}))
@@ -109,18 +109,18 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):
self.assertLess(len(response.content), 560)
def test_export_ical_anonymous(self):
- '''
+ """
Tests exporting a workout as an ical file as an anonymous user
- '''
+ """
self.export_ical(fail=True)
self.export_ical_token()
self.export_ical_token_wrong()
def test_export_ical_owner(self):
- '''
+ """
Tests exporting a workout as an ical file as the owner user
- '''
+ """
self.user_login('test')
self.export_ical(fail=False)
@@ -128,9 +128,9 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):
self.export_ical_token_wrong()
def test_export_ical_other(self):
- '''
+ """
Tests exporting a workout as an ical file as a logged user not owning the data
- '''
+ """
self.user_login('admin')
self.export_ical(fail=True)
@@ -139,14 +139,14 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):
class ScheduleICalExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests exporting the ical file for a schedule
- '''
+ """
def export_ical_token(self):
- '''
+ """
Helper function that checks exporing an ical file using tokens for access
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
@@ -164,9 +164,9 @@ class ScheduleICalExportTestCase(WorkoutManagerTestCase):
self.assertLess(len(response.content), 1670)
def export_ical_token_wrong(self):
- '''
+ """
Helper function that checks exporing an ical file using a wrong token
- '''
+ """
uid = 'AB'
token = 'abc-11223344556677889900'
@@ -177,9 +177,9 @@ class ScheduleICalExportTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 403)
def export_ical(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('manager:schedule:ical', kwargs={'pk': 2}))
@@ -196,18 +196,18 @@ class ScheduleICalExportTestCase(WorkoutManagerTestCase):
self.assertLess(len(response.content), 1670)
def test_export_ical_anonymous(self):
- '''
+ """
Tests exporting a schedule as an ical file as an anonymous user
- '''
+ """
self.export_ical(fail=True)
self.export_ical_token()
self.export_ical_token_wrong()
def test_export_ical_owner(self):
- '''
+ """
Tests exporting a schedule as an ical file as the owner user
- '''
+ """
self.user_login('admin')
self.export_ical(fail=False)
@@ -215,9 +215,9 @@ class ScheduleICalExportTestCase(WorkoutManagerTestCase):
self.export_ical_token_wrong()
def test_export_ical_other(self):
- '''
+ """
Tests exporting a schedule as an ical file as a logged user not owning the data
- '''
+ """
self.user_login('test')
self.export_ical(fail=True)
diff --git a/wger/manager/tests/test_pdf.py b/wger/manager/tests/test_pdf.py
index aec560e97..5238ed2e9 100644
--- a/wger/manager/tests/test_pdf.py
+++ b/wger/manager/tests/test_pdf.py
@@ -22,14 +22,14 @@ from wger.utils.helpers import make_token
class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests exporting a workout as a pdf
- '''
+ """
def export_pdf_token(self):
- '''
+ """
Helper function to test exporting a workout as a pdf using tokens
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
@@ -47,9 +47,9 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_token_wrong(self):
- '''
+ """
Helper function to test exporting a workout as a pdf using a wrong token
- '''
+ """
uid = 'AB'
token = 'abc-11223344556677889900'
@@ -60,9 +60,9 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 403)
def export_pdf(self, fail=False):
- '''
+ """
Helper function to test exporting a workout as a pdf
- '''
+ """
response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3}))
@@ -79,9 +79,9 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_with_comments(self, fail=False):
- '''
+ """
Helper function to test exporting a workout as a pdf, with exercise coments
- '''
+ """
response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3,
'comments': 0}))
@@ -99,9 +99,9 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_with_images(self, fail=False):
- '''
+ """
Helper function to test exporting a workout as a pdf, with exercise images
- '''
+ """
response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3,
'images': 1}))
@@ -119,9 +119,9 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_with_images_and_comments(self, fail=False):
- '''
+ """
Helper function to test exporting a workout as a pdf, with images and comments
- '''
+ """
response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3,
'images': 1,
@@ -140,18 +140,18 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def test_export_pdf_anonymous(self):
- '''
+ """
Tests exporting a workout as a pdf as an anonymous user
- '''
+ """
self.export_pdf(fail=True)
self.export_pdf_token()
self.export_pdf_token_wrong()
def test_export_pdf_owner(self):
- '''
+ """
Tests exporting a workout as a pdf as the owner user
- '''
+ """
self.user_login('test')
self.export_pdf(fail=False)
@@ -159,9 +159,9 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.export_pdf_token_wrong()
def test_export_pdf_other(self):
- '''
+ """
Tests exporting a workout as a pdf as a logged user not owning the data
- '''
+ """
self.user_login('admin')
self.export_pdf(fail=True)
@@ -170,14 +170,14 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests exporting a workout as a pdf
- '''
+ """
def export_pdf_token(self):
- '''
+ """
Helper function to test exporting a workout as a pdf using tokens
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
@@ -195,9 +195,9 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_token_wrong(self):
- '''
+ """
Helper function to test exporting a workout as a pdf using a wrong token
- '''
+ """
uid = 'AB'
token = 'abc-11223344556677889900'
@@ -208,9 +208,9 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 403)
def export_pdf(self, fail=False):
- '''
+ """
Helper function to test exporting a workout as a pdf
- '''
+ """
# Create a workout
response = self.client.get(reverse('manager:workout:pdf-table', kwargs={'id': 3}))
@@ -228,18 +228,18 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def test_export_pdf_anonymous(self):
- '''
+ """
Tests exporting a workout as a pdf as an anonymous user
- '''
+ """
self.export_pdf(fail=True)
self.export_pdf_token()
self.export_pdf_token_wrong()
def test_export_pdf_owner(self):
- '''
+ """
Tests exporting a workout as a pdf as the owner user
- '''
+ """
self.user_login('test')
self.export_pdf(fail=False)
@@ -247,9 +247,9 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):
self.export_pdf_token_wrong()
def test_export_pdf_other(self):
- '''
+ """
Tests exporting a workout as a pdf as a logged user not owning the data
- '''
+ """
self.user_login('admin')
self.export_pdf(fail=True)
diff --git a/wger/manager/tests/test_schedule.py b/wger/manager/tests/test_schedule.py
index 0c88cefce..e842c0707 100644
--- a/wger/manager/tests/test_schedule.py
+++ b/wger/manager/tests/test_schedule.py
@@ -41,9 +41,9 @@ logger = logging.getLogger(__name__)
class ScheduleShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
workout = Workout.objects.get(pk=2)
@@ -61,14 +61,14 @@ class ScheduleShareButtonTestCase(WorkoutManagerTestCase):
class ScheduleAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Test accessing the workout page
- '''
+ """
def test_access_shared(self):
- '''
+ """
Test accessing the URL of a shared workout
- '''
+ """
workout = Schedule.objects.get(pk=2)
self.user_login('admin')
@@ -84,9 +84,9 @@ class ScheduleAccessTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_access_not_shared(self):
- '''
+ """
Test accessing the URL of a private workout
- '''
+ """
workout = Schedule.objects.get(pk=1)
self.user_login('admin')
@@ -103,22 +103,22 @@ class ScheduleAccessTestCase(WorkoutManagerTestCase):
class ScheduleRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Schedule.objects.get(pk=1)),
'my cool schedule that i found on the internet')
class CreateScheduleTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a schedule
- '''
+ """
object_class = Schedule
url = 'manager:schedule:add'
@@ -131,9 +131,9 @@ class CreateScheduleTestCase(WorkoutManagerAddTestCase):
class DeleteScheduleTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a schedule
- '''
+ """
object_class = Schedule
url = 'manager:schedule:delete'
@@ -143,9 +143,9 @@ class DeleteScheduleTestCase(WorkoutManagerDeleteTestCase):
class EditScheduleTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a schedule
- '''
+ """
object_class = Schedule
url = 'manager:schedule:edit'
@@ -157,14 +157,14 @@ class EditScheduleTestCase(WorkoutManagerEditTestCase):
class ScheduleTestCase(WorkoutManagerTestCase):
- '''
+ """
Other tests
- '''
+ """
def schedule_detail_page(self):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('manager:schedule:view', kwargs={'pk': 2}))
self.assertEqual(response.status_code, 200)
@@ -182,17 +182,17 @@ class ScheduleTestCase(WorkoutManagerTestCase):
# Commented out since travis was seemingly randomly failing this. See #468
#
# 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_overview(self):
- '''
+ """
Tests the schedule overview
- '''
+ """
self.user_login()
response = self.client.get(reverse('manager:schedule:overview'))
@@ -210,9 +210,9 @@ class ScheduleTestCase(WorkoutManagerTestCase):
self.assertFalse(response.context['schedules'][i].is_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)
@@ -240,9 +240,9 @@ class ScheduleTestCase(WorkoutManagerTestCase):
self.assertFalse(schedule3.is_active)
def start_schedule(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
schedule = Schedule.objects.get(pk=2)
self.assertFalse(schedule.is_active)
@@ -260,78 +260,78 @@ class ScheduleTestCase(WorkoutManagerTestCase):
self.assertEqual(schedule.start_date, datetime.date.today())
def test_start_schedule_owner(self):
- '''
+ """
Tests starting a schedule as the owning user
- '''
+ """
self.user_login()
self.start_schedule()
def test_start_schedule_other(self):
- '''
+ """
Tests starting a schedule as a different user
- '''
+ """
self.user_login('test')
self.start_schedule(fail=True)
def test_start_schedule_anonymous(self):
- '''
+ """
Tests starting a schedule as a logged out user
- '''
+ """
self.start_schedule(fail=True)
class ScheduleEndDateTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the schedule's get_end_date method
- '''
+ """
def test_loop_schedule(self):
- '''
+ """
Loop schedules have no end date
- '''
+ """
schedule = Schedule.objects.get(pk=2)
self.assertTrue(schedule.is_loop)
self.assertFalse(schedule.get_end_date())
def test_calculate(self):
- '''
+ """
Test the actual calculation
Steps: 3, 5 and 2 weeks, starting on the 2013-04-21
- '''
+ """
schedule = Schedule.objects.get(pk=2)
schedule.is_loop = False
schedule.save()
self.assertEqual(schedule.get_end_date(), datetime.date(2013, 6, 30))
def test_empty_schedule(self):
- '''
+ """
Test the end date with an empty schedule
- '''
+ """
schedule = Schedule.objects.get(pk=3)
self.assertEqual(schedule.get_end_date(), schedule.start_date)
class ScheduleModelTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the model methods
- '''
+ """
def delete_objects(self, user):
- '''
+ """
Helper function
- '''
+ """
Workout.objects.filter(user=user).delete()
Schedule.objects.filter(user=user).delete()
def create_schedule(self, user, start_date=datetime.date.today(), is_loop=False):
- '''
+ """
Helper function
- '''
+ """
schedule = Schedule()
schedule.user = user
@@ -343,9 +343,9 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):
return schedule
def create_workout(self, user):
- '''
+ """
Helper function
- '''
+ """
workout = Workout()
workout.user = user
@@ -353,9 +353,9 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):
return workout
def test_get_workout_steps_test_1(self):
- '''
+ """
Test with no workouts and no schedule steps
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
self.delete_objects(user)
@@ -364,9 +364,9 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):
self.assertFalse(schedule.get_current_scheduled_workout())
def test_get_workout_steps_test_2(self):
- '''
+ """
Test with one schedule step
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
self.delete_objects(user)
@@ -381,9 +381,9 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):
self.assertEqual(schedule.get_current_scheduled_workout().workout, workout)
def test_get_workout_steps_test_3(self):
- '''
+ """
Test with 3 steps
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
self.delete_objects(user)
@@ -416,9 +416,9 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):
self.assertEqual(schedule.get_current_scheduled_workout().workout, workout2)
def test_get_workout_steps_test_4(self):
- '''
+ """
Test with 3 steps. Start is too far in the past, schedule ist not a loop
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
self.delete_objects(user)
@@ -451,9 +451,9 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):
self.assertFalse(schedule.get_current_scheduled_workout())
def test_get_workout_steps_test_5(self):
- '''
+ """
Test with 3 steps. Start is too far in the past but schedule is a loop
- '''
+ """
self.user_login('test')
user = User.objects.get(pk=2)
self.delete_objects(user)
@@ -487,14 +487,14 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):
class SchedulePdfExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Test exporting a schedule as a pdf
- '''
+ """
def export_pdf_token(self, pdf_type="log"):
- '''
+ """
Helper function to test exporting a workout as a pdf using tokens
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
@@ -522,9 +522,9 @@ class SchedulePdfExportTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 403)
def export_pdf(self, fail=False, pdf_type="log"):
- '''
+ """
Helper function to test exporting a workout as a pdf
- '''
+ """
response = self.client.get(reverse('manager:schedule:pdf-{0}'.format(pdf_type),
kwargs={'pk': 1}))
@@ -542,9 +542,9 @@ class SchedulePdfExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_with_comments(self, fail=False, pdf_type="log"):
- '''
+ """
Helper function to test exporting a workout as a pdf, with exercise coments
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
@@ -568,9 +568,9 @@ class SchedulePdfExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_with_images(self, fail=False, pdf_type="log"):
- '''
+ """
Helper function to test exporting a workout as a pdf, with exercise images
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
response = self.client.get(reverse('manager:schedule:pdf-{0}'.format(pdf_type),
@@ -593,9 +593,9 @@ class SchedulePdfExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def export_pdf_with_images_and_comments(self, fail=False, pdf_type="log"):
- '''
+ """
Helper function to test exporting a workout as a pdf, with images and comments
- '''
+ """
user = User.objects.get(username='test')
uid, token = make_token(user)
@@ -619,51 +619,51 @@ class SchedulePdfExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 35000)
def test_export_pdf_log_anonymous(self):
- '''
+ """
Tests exporting a workout as a pdf as an anonymous user
- '''
+ """
self.export_pdf(fail=True)
self.export_pdf_token()
def test_export_pdf_log_owner(self):
- '''
+ """
Tests exporting a workout as a pdf as the owner user
- '''
+ """
self.user_login('test')
self.export_pdf(fail=False)
self.export_pdf_token()
def test_export_pdf_log_other(self):
- '''
+ """
Tests exporting a workout as a pdf as a logged user not owning the data
- '''
+ """
self.user_login('admin')
self.export_pdf(fail=True)
self.export_pdf_token()
def test_export_pdf_log_with_comments(self, fail=False):
- '''
+ """
Tests exporting a workout as a pdf as the owner user with comments
- '''
+ """
self.user_login('test')
self.export_pdf_with_comments(fail=False)
self.export_pdf_token()
def test_export_pdf_log_with_images(self, fail=False):
- '''
+ """
Tests exporting a workout as a pdf as the owner user with images
- '''
+ """
self.user_login('test')
self.export_pdf_with_images(fail=False)
self.export_pdf_token()
def test_export_pdf_log_with_images_and_comments(self, fail=False):
- '''
+ """
Tests exporting a workout as a pdf as the owner user with images andcomments
- '''
+ """
self.user_login('test')
self.export_pdf_with_images_and_comments(fail=False)
self.export_pdf_token()
@@ -671,60 +671,60 @@ class SchedulePdfExportTestCase(WorkoutManagerTestCase):
# #####TABLE#####
def test_export_pdf_table_anonymous(self):
- '''
+ """
Tests exporting a workout as a pdf as an anonymous user
- '''
+ """
self.export_pdf(fail=True, pdf_type="table")
self.export_pdf_token(pdf_type="table")
def test_export_pdf_table_owner(self):
- '''
+ """
Tests exporting a workout as a pdf as the owner user
- '''
+ """
self.user_login('test')
self.export_pdf(fail=False, pdf_type="table")
self.export_pdf_token(pdf_type="table")
def test_export_pdf_table_other(self):
- '''
+ """
Tests exporting a workout as a pdf as a logged user not owning the data
- '''
+ """
self.user_login('admin')
self.export_pdf(fail=True, pdf_type="table")
self.export_pdf_token(pdf_type="table")
def test_export_pdf_table_with_comments(self, fail=False):
- '''
+ """
Tests exporting a workout as a pdf as the owner user with comments
- '''
+ """
self.user_login('test')
self.export_pdf_with_comments(fail=False, pdf_type="table")
self.export_pdf_token(pdf_type="table")
def test_export_pdf_table_with_images(self, fail=False):
- '''
+ """
Tests exporting a workout as a pdf as the owner user with images
- '''
+ """
self.user_login('test')
self.export_pdf_with_images(fail=False, pdf_type="table")
self.export_pdf_token(pdf_type="table")
def test_export_pdf_table_with_images_and_comments(self, fail=False):
- '''
+ """
Tests exporting a workout as a pdf as the owner user with images andcomments
- '''
+ """
self.user_login('test')
self.export_pdf_with_images_and_comments(fail=False, pdf_type="table")
self.export_pdf_token(pdf_type="table")
class ScheduleApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the schedule overview resource
- '''
+ """
pk = 1
resource = Schedule
private_resource = True
diff --git a/wger/manager/tests/test_schedule_step.py b/wger/manager/tests/test_schedule_step.py
index c2d8681a4..2a46b1c0c 100644
--- a/wger/manager/tests/test_schedule_step.py
+++ b/wger/manager/tests/test_schedule_step.py
@@ -30,26 +30,26 @@ from wger.manager.models import ScheduleStep
class ScheduleStepRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(ScheduleStep.objects.get(pk=1)), 'A test workout')
class ScheduleStepTestCase(WorkoutManagerTestCase):
- '''
+ """
Other tests
- '''
+ """
def test_schedule_dates_util(self, fail=False):
- '''
+ """
Test the get_dates() method
- '''
+ """
s1 = ScheduleStep.objects.get(pk=1)
s2 = ScheduleStep.objects.get(pk=2)
s3 = ScheduleStep.objects.get(pk=3)
@@ -60,9 +60,9 @@ class ScheduleStepTestCase(WorkoutManagerTestCase):
class CreateScheduleStepTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a schedule
- '''
+ """
object_class = ScheduleStep
url = reverse_lazy('manager:step:add', kwargs={'schedule_pk': 1})
@@ -73,9 +73,9 @@ class CreateScheduleStepTestCase(WorkoutManagerAddTestCase):
class EditScheduleStepTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a schedule
- '''
+ """
object_class = ScheduleStep
url = 'manager:step:edit'
@@ -85,9 +85,9 @@ class EditScheduleStepTestCase(WorkoutManagerEditTestCase):
class DeleteScheduleStepTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests editing a schedule
- '''
+ """
object_class = ScheduleStep
url = 'manager:step:delete'
@@ -95,9 +95,9 @@ class DeleteScheduleStepTestCase(WorkoutManagerDeleteTestCase):
class ScheduleStepApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the schedule step overview resource
- '''
+ """
pk = 4
resource = ScheduleStep
private_resource = True
diff --git a/wger/manager/tests/test_set.py b/wger/manager/tests/test_set.py
index 24e3dcebd..ed7ba1649 100644
--- a/wger/manager/tests/test_set.py
+++ b/wger/manager/tests/test_set.py
@@ -42,9 +42,9 @@ logger = logging.getLogger(__name__)
class SetAddTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Test adding a set to a day
- '''
+ """
object_class = Set
url = reverse_lazy('manager:set:add', kwargs={'day_pk': 5})
@@ -87,9 +87,9 @@ class SetAddTestCase(WorkoutManagerAddTestCase):
'exercise1-3-weight_unit')
def test_add_set(self, fail=False):
- '''
+ """
Tests adding a set and corresponding settings at the same time
- '''
+ """
# POST the data
self.user_login('test')
@@ -148,14 +148,14 @@ class SetAddTestCase(WorkoutManagerAddTestCase):
class SetDeleteTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests deleting a set from a workout
- '''
+ """
def delete_set(self, fail=True):
- '''
+ """
Helper function to test deleting a set from a workout
- '''
+ """
# Fetch the overview page
count_before = Set.objects.count()
@@ -171,39 +171,39 @@ class SetDeleteTestCase(WorkoutManagerTestCase):
self.assertRaises(Set.DoesNotExist, Set.objects.get, pk=3)
def test_delete_set_anonymous(self):
- '''
+ """
Tests deleting a set from a workout as an anonymous user
- '''
+ """
self.delete_set(fail=True)
def test_delete_set_owner(self):
- '''
+ """
Tests deleting a set from a workout as the owner user
- '''
+ """
self.user_login('admin')
self.delete_set(fail=True)
def test_delete_set_other(self):
- '''
+ """
Tests deleting a set from a workout as a logged user not owning the data
- '''
+ """
self.user_login('test')
self.delete_set(fail=False)
class TestSetOrderTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests that the order of the (existing) sets in a workout is preservead
when adding new ones
- '''
+ """
def add_set(self, exercises_id):
- '''
+ """
Helper function that adds a set to a day
- '''
+ """
nr_sets = 4
post_data = {'exercises': exercises_id,
'exercise_list': exercises_id[0], # Only for mobile version,
@@ -223,9 +223,9 @@ class TestSetOrderTestCase(WorkoutManagerTestCase):
return response
def get_order(self):
- '''
+ """
Helper function that reads the order of the the sets in a day
- '''
+ """
day = Day.objects.get(pk=5)
order = ()
@@ -236,9 +236,9 @@ class TestSetOrderTestCase(WorkoutManagerTestCase):
return order
def test_set_order(self, logged_in=False):
- '''
+ """
Helper function that add some sets and checks the order
- '''
+ """
self.user_login('test')
orig = self.get_order()
@@ -252,15 +252,15 @@ class TestSetOrderTestCase(WorkoutManagerTestCase):
class TestSetAddFormset(WorkoutManagerTestCase):
- '''
+ """
Tests the functionality of the formset mini-view that is used in the add
set page
- '''
+ """
def get_formset(self):
- '''
+ """
Helper function
- '''
+ """
exercise = Exercise.objects.get(pk=1)
response = self.client.get(reverse('manager:set:get-formset',
kwargs={'exercise_pk': 1, 'reps': 4}))
@@ -270,23 +270,23 @@ class TestSetAddFormset(WorkoutManagerTestCase):
self.assertTrue(response.context['formset'])
def test_get_formset_logged_in(self):
- '''
+ """
Tests the formset view as an authorized user
- '''
+ """
self.user_login('test')
self.get_formset()
class SetEditEditTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests editing a set
- '''
+ """
def edit_set(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
# Fetch the edit page
response = self.client.get(reverse('manager:set:edit', kwargs={'pk': 3}))
@@ -347,31 +347,31 @@ class SetEditEditTestCase(WorkoutManagerTestCase):
self.post_test_hook()
def test_edit_set_authorized(self):
- '''
+ """
Tests editing the object as an authorized user
- '''
+ """
self.user_login('admin')
self.edit_set(fail=True)
def test_edit_set_other(self):
- '''
+ """
Tests editing the object as an unauthorized, logged in user
- '''
+ """
self.user_login('test')
self.edit_set(fail=False)
class SetWorkoutCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Workout cache test case
- '''
+ """
def test_canonical_form_cache_save(self):
- '''
+ """
Tests the workout cache when saving
- '''
+ """
set = Set.objects.get(pk=1)
set.exerciseday.training.canonical_representation
self.assertTrue(cache.get(cache_mapper.get_workout_canonical(set.exerciseday.training_id)))
@@ -380,9 +380,9 @@ class SetWorkoutCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_canonical(set.exerciseday.training_id)))
def test_canonical_form_cache_delete(self):
- '''
+ """
Tests the workout cache when deleting
- '''
+ """
set = Set.objects.get(pk=1)
set.exerciseday.training.canonical_representation
self.assertTrue(cache.get(cache_mapper.get_workout_canonical(set.exerciseday.training_id)))
@@ -392,14 +392,14 @@ class SetWorkoutCacheTestCase(WorkoutManagerTestCase):
class SettingWorkoutCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Workout cache test case
- '''
+ """
def test_canonical_form_cache_save(self):
- '''
+ """
Tests the workout cache when saving
- '''
+ """
setting = Setting.objects.get(pk=1)
workout_id = setting.set.exerciseday.training_id
setting.set.exerciseday.training.canonical_representation
@@ -409,9 +409,9 @@ class SettingWorkoutCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_canonical(workout_id)))
def test_canonical_form_cache_delete(self):
- '''
+ """
Tests the workout cache when deleting
- '''
+ """
setting = Setting.objects.get(pk=1)
workout_id = setting.set.exerciseday.training_id
setting.set.exerciseday.training.canonical_representation
@@ -422,9 +422,9 @@ class SettingWorkoutCacheTestCase(WorkoutManagerTestCase):
class SetApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the set overview resource
- '''
+ """
pk = 3
resource = Set
private_resource = True
diff --git a/wger/manager/tests/test_timer.py b/wger/manager/tests/test_timer.py
index 5ec183cbb..b728e0ae1 100644
--- a/wger/manager/tests/test_timer.py
+++ b/wger/manager/tests/test_timer.py
@@ -35,14 +35,14 @@ logger = logging.getLogger(__name__)
class WorkoutTimerTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the timer view (gym mode) for a workout day
- '''
+ """
def test_timer_no_weight(self):
- '''
+ """
Test the timer page when there are no saved weights
- '''
+ """
# Fetch the timer page
self.user_login('test')
@@ -57,9 +57,9 @@ class WorkoutTimerTestCase(WorkoutManagerTestCase):
self.assertEqual(current_step['weight'], '')
def timer(self, fail=True, pause_active=True, pause_seconds=90):
- '''
+ """
Helper function
- '''
+ """
# Fetch the timer page
response = self.client.get(reverse('manager:workout:timer', kwargs={'day_pk': 2}))
@@ -118,23 +118,23 @@ class WorkoutTimerTestCase(WorkoutManagerTestCase):
self.assertEqual(current_step['weight'], Decimal(15))
def test_timer_anonymous(self):
- '''
+ """
Tests the timer as an anonymous user
- '''
+ """
self.timer(fail=True)
def test_timer_owner(self):
- '''
+ """
Tests the timer as the owner user
- '''
+ """
self.user_login('admin')
self.timer(fail=False)
def test_timer_owner_custom_pause(self):
- '''
+ """
Tests the timer as the owner, use custom time
- '''
+ """
self.user_login('admin')
user = User.objects.get(username='admin')
user.userprofile.timer_pause = 120
@@ -142,9 +142,9 @@ class WorkoutTimerTestCase(WorkoutManagerTestCase):
self.timer(fail=False, pause_seconds=120)
def test_timer_owner_no_pause(self):
- '''
+ """
Tests the timer as the owner, deactivate timer
- '''
+ """
self.user_login('admin')
user = User.objects.get(username='admin')
user.userprofile.timer_active = False
@@ -152,23 +152,23 @@ class WorkoutTimerTestCase(WorkoutManagerTestCase):
self.timer(fail=False, pause_active=False)
def test_timer_other(self):
- '''
+ """
Tests the timer as a logged user not owning the data
- '''
+ """
self.user_login('test')
self.timer(fail=True)
class WorkoutTimerWorkoutSessionTestCase(WorkoutManagerTestCase):
- '''
+ """
Other tests
- '''
+ """
def test_workout_session(self):
- '''
+ """
Tests that the correct urls and forms for workout session is passed
- '''
+ """
WorkoutSession.objects.all().delete()
self.user_login('test')
diff --git a/wger/manager/tests/test_weight_log.py b/wger/manager/tests/test_weight_log.py
index 48e712b99..b15c52b42 100644
--- a/wger/manager/tests/test_weight_log.py
+++ b/wger/manager/tests/test_weight_log.py
@@ -43,9 +43,9 @@ logger = logging.getLogger(__name__)
class WorkoutLogShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
url = reverse('manager:log:log', kwargs={'pk': 1})
@@ -63,14 +63,14 @@ class WorkoutLogShareButtonTestCase(WorkoutManagerTestCase):
class WeightLogAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Test accessing the weight log page
- '''
+ """
def test_access_shared(self):
- '''
+ """
Test accessing the URL of a shared weight log
- '''
+ """
url = reverse('manager:log:log', kwargs={'pk': 1})
self.user_login('admin')
@@ -86,9 +86,9 @@ class WeightLogAccessTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_access_not_shared(self):
- '''
+ """
Test accessing the URL of a private weight log
- '''
+ """
url = reverse('manager:log:log', kwargs={'pk': 3})
self.user_login('admin')
@@ -105,9 +105,9 @@ class WeightLogAccessTestCase(WorkoutManagerTestCase):
class CalendarShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
url = reverse('manager:workout:calendar', kwargs={'username': 'admin'})
@@ -125,14 +125,14 @@ class CalendarShareButtonTestCase(WorkoutManagerTestCase):
class CalendarAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Test accessing the calendar page
- '''
+ """
def test_access_shared(self):
- '''
+ """
Test accessing the URL of a shared calendar page
- '''
+ """
url = reverse('manager:workout:calendar', kwargs={'username': 'admin'})
self.user_login('admin')
@@ -148,9 +148,9 @@ class CalendarAccessTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_access_not_shared(self):
- '''
+ """
Test accessing the URL of a unshared calendar page
- '''
+ """
url = reverse('manager:workout:calendar', kwargs={'username': 'test'})
self.user_login('admin')
@@ -167,14 +167,14 @@ class CalendarAccessTestCase(WorkoutManagerTestCase):
class WeightLogOverviewAddTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the weight log functionality
- '''
+ """
def add_weight_log(self, fail=True):
- '''
+ """
Helper function to test adding weight log entries
- '''
+ """
# Fetch the overview page
response = self.client.get(reverse('manager:log:log', kwargs={'pk': 1}))
@@ -223,38 +223,38 @@ class WeightLogOverviewAddTestCase(WorkoutManagerTestCase):
self.assertGreater(count_after, count_before)
def test_add_weight_log_anonymous(self):
- '''
+ """
Tests adding weight log entries as an anonymous user
- '''
+ """
self.add_weight_log(fail=True)
def test_add_weight_log_owner(self):
- '''
+ """
Tests adding weight log entries as the owner user
- '''
+ """
self.user_login('admin')
self.add_weight_log(fail=False)
def test_add_weight_log_other(self):
- '''
+ """
Tests adding weight log entries as a logged user not owning the data
- '''
+ """
self.user_login('test')
self.add_weight_log(fail=True)
class WeightlogTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests other model methods
- '''
+ """
def test_get_workout_session(self):
- '''
+ """
Test the wgerGetWorkoutSession method
- '''
+ """
user1 = User.objects.get(pk=1)
user2 = User.objects.get(pk=2)
@@ -299,9 +299,9 @@ class WeightlogTestCase(WorkoutManagerTestCase):
class WeightLogDeleteTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a WorkoutLog
- '''
+ """
object_class = WorkoutLog
url = reverse_lazy('manager:log:delete', kwargs={'pk': 1})
@@ -309,14 +309,14 @@ class WeightLogDeleteTestCase(WorkoutManagerDeleteTestCase):
class WeightLogEntryEditTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests editing individual weight log entries
- '''
+ """
def edit_log_entry(self, fail=True):
- '''
+ """
Helper function to test edit log entries
- '''
+ """
response = self.client.get(reverse('manager:log:edit', kwargs={'pk': 1}))
if fail:
@@ -348,38 +348,38 @@ class WeightLogEntryEditTestCase(WorkoutManagerTestCase):
self.assertEqual(date_after, datetime.date(2012, 1, 1))
def test_edit_log_entry_anonymous(self):
- '''
+ """
Tests editing a weight log entries as an anonymous user
- '''
+ """
self.edit_log_entry(fail=True)
def test_edit_log_entry_owner(self):
- '''
+ """
Tests editing a weight log entries as the owner user
- '''
+ """
self.user_login('admin')
self.edit_log_entry(fail=False)
def test_edit_log_entry_other(self):
- '''
+ """
Tests editing a weight log entries as a logged user not owning the data
- '''
+ """
self.user_login('test')
self.edit_log_entry(fail=True)
class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Workout log cache test case
- '''
+ """
def test_calendar(self):
- '''
+ """
Test the log cache is correctly generated on visit
- '''
+ """
log_hash = hash((1, 2012, 10))
self.user_login('admin')
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash)))
@@ -388,9 +388,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash)))
def test_calendar_day(self):
- '''
+ """
Test the log cache on the calendar day view is correctly generated on visit
- '''
+ """
log_hash = hash((1, 2012, 10, 1))
self.user_login('admin')
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash)))
@@ -402,9 +402,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash)))
def test_calendar_anonymous(self):
- '''
+ """
Test the log cache is correctly generated on visit by anonymous users
- '''
+ """
log_hash = hash((1, 2012, 10))
self.user_logout()
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash)))
@@ -415,9 +415,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash)))
def test_calendar_day_anonymous(self):
- '''
+ """
Test the log cache is correctly generated on visit by anonymous users
- '''
+ """
log_hash = hash((1, 2012, 10, 1))
self.user_logout()
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash)))
@@ -429,9 +429,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash)))
def test_cache_update_log(self):
- '''
+ """
Test that the caches are cleared when saving a log
- '''
+ """
log_hash = hash((1, 2012, 10))
log_hash_day = hash((1, 2012, 10, 1))
self.user_login('admin')
@@ -449,9 +449,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash_day)))
def test_cache_update_log_2(self):
- '''
+ """
Test that the caches are only cleared for a the log's month
- '''
+ """
log_hash = hash((1, 2012, 10))
log_hash_day = hash((1, 2012, 10, 1))
self.user_login('admin')
@@ -469,9 +469,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash_day)))
def test_cache_delete_log(self):
- '''
+ """
Test that the caches are cleared when deleting a log
- '''
+ """
log_hash = hash((1, 2012, 10))
log_hash_day = hash((1, 2012, 10, 1))
self.user_login('admin')
@@ -488,9 +488,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash_day)))
def test_cache_delete_log_2(self):
- '''
+ """
Test that the caches are only cleared for a the log's month
- '''
+ """
log_hash = hash((1, 2012, 10))
log_hash_day = hash((1, 2012, 10, 1))
self.user_login('admin')
@@ -508,9 +508,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
class WorkoutLogApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the workout log overview resource
- '''
+ """
pk = 5
resource = WorkoutLog
private_resource = True
diff --git a/wger/manager/tests/test_workout.py b/wger/manager/tests/test_workout.py
index 37d024d18..4926ff2bb 100644
--- a/wger/manager/tests/test_workout.py
+++ b/wger/manager/tests/test_workout.py
@@ -29,9 +29,9 @@ from wger.manager.models import Workout
class WorkoutShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
workout = Workout.objects.get(pk=1)
@@ -49,14 +49,14 @@ class WorkoutShareButtonTestCase(WorkoutManagerTestCase):
class WorkoutAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Test accessing the workout page
- '''
+ """
def test_access_shared(self):
- '''
+ """
Test accessing the URL of a shared workout
- '''
+ """
workout = Workout.objects.get(pk=1)
self.user_login('admin')
@@ -72,9 +72,9 @@ class WorkoutAccessTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_access_not_shared(self):
- '''
+ """
Test accessing the URL of a private workout
- '''
+ """
workout = Workout.objects.get(pk=3)
self.user_login('admin')
@@ -91,14 +91,14 @@ class WorkoutAccessTestCase(WorkoutManagerTestCase):
class AddWorkoutTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests adding a Workout
- '''
+ """
def create_workout(self):
- '''
+ """
Helper function to test creating workouts
- '''
+ """
# Create a workout
count_before = Workout.objects.count()
@@ -119,9 +119,9 @@ class AddWorkoutTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_create_workout_logged_in(self):
- '''
+ """
Test creating a workout a logged in user
- '''
+ """
self.user_login()
self.create_workout()
@@ -129,9 +129,9 @@ class AddWorkoutTestCase(WorkoutManagerTestCase):
class DeleteTestWorkoutTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a Workout
- '''
+ """
object_class = Workout
url = 'manager:workout:delete'
@@ -141,9 +141,9 @@ class DeleteTestWorkoutTestCase(WorkoutManagerDeleteTestCase):
class EditWorkoutTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a Workout
- '''
+ """
object_class = Workout
url = 'manager:workout:edit'
@@ -154,14 +154,14 @@ class EditWorkoutTestCase(WorkoutManagerEditTestCase):
class WorkoutOverviewTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the workout overview
- '''
+ """
def get_workout_overview(self):
- '''
+ """
Helper function to test the workout overview
- '''
+ """
response = self.client.get(reverse('manager:workout:overview'))
@@ -170,22 +170,22 @@ class WorkoutOverviewTestCase(WorkoutManagerTestCase):
self.assertEqual(len(response.context['workouts']), 2)
def test_dashboard_logged_in(self):
- '''
+ """
Test creating a workout a logged in user
- '''
+ """
self.user_login()
self.get_workout_overview()
class WorkoutModelTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests other functionality from the model
- '''
+ """
def test_unicode(self):
- '''
+ """
Test the unicode representation
- '''
+ """
workout = Workout()
workout.creation_date = datetime.date.today()
@@ -197,9 +197,9 @@ class WorkoutModelTestCase(WorkoutManagerTestCase):
class WorkoutApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the workout overview resource
- '''
+ """
pk = 3
resource = Workout
private_resource = True
diff --git a/wger/manager/tests/test_workout_canonical.py b/wger/manager/tests/test_workout_canonical.py
index 2fda71402..4a8f7d20f 100644
--- a/wger/manager/tests/test_workout_canonical.py
+++ b/wger/manager/tests/test_workout_canonical.py
@@ -36,15 +36,15 @@ from wger.utils.cache import cache_mapper
class WorkoutCanonicalFormTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the canonical form for a workout
- '''
+ """
maxDiff = None
def test_canonical_form(self):
- '''
+ """
Tests the canonical form for a workout
- '''
+ """
workout = Workout.objects.get(pk=1)
setting_1 = Setting.objects.get(pk=1)
@@ -124,9 +124,9 @@ class WorkoutCanonicalFormTestCase(WorkoutManagerTestCase):
self.assertEqual(workout.canonical_representation['day_list'][2], canonical_form)
def test_canonical_form_day(self):
- '''
+ """
Tests the canonical form for a day
- '''
+ """
day = Day.objects.get(pk=5)
weekday1 = DaysOfWeek.objects.get(pk=3)
@@ -165,14 +165,14 @@ class WorkoutCanonicalFormTestCase(WorkoutManagerTestCase):
class WorkoutCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Test case for the workout canonical representation
- '''
+ """
def test_canonical_form_cache(self):
- '''
+ """
Tests that the workout cache of the canonical form is correctly generated
- '''
+ """
self.assertFalse(cache.get(cache_mapper.get_workout_canonical(1)))
workout = Workout.objects.get(pk=1)
@@ -180,9 +180,9 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(cache_mapper.get_workout_canonical(1)))
def test_canonical_form_cache_save(self):
- '''
+ """
Tests the workout cache when saving
- '''
+ """
workout = Workout.objects.get(pk=1)
workout.canonical_representation
self.assertTrue(cache.get(cache_mapper.get_workout_canonical(1)))
@@ -191,9 +191,9 @@ class WorkoutCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_canonical(1)))
def test_canonical_form_cache_delete(self):
- '''
+ """
Tests the workout cache when deleting
- '''
+ """
workout = Workout.objects.get(pk=1)
workout.canonical_representation
self.assertTrue(cache.get(cache_mapper.get_workout_canonical(1)))
diff --git a/wger/manager/tests/test_workout_session.py b/wger/manager/tests/test_workout_session.py
index d0f5b7d64..92add61bf 100644
--- a/wger/manager/tests/test_workout_session.py
+++ b/wger/manager/tests/test_workout_session.py
@@ -40,15 +40,15 @@ from wger.manager.models import (
from wger.utils.cache import cache_mapper
-'''
+"""
Tests for workout sessions
-'''
+"""
class AddWorkoutSessionTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a workout session
- '''
+ """
object_class = WorkoutSession
url = reverse_lazy('manager:session:add', kwargs={'workout_pk': 1,
@@ -67,9 +67,9 @@ class AddWorkoutSessionTestCase(WorkoutManagerAddTestCase):
class EditWorkoutSessionTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a workout session
- '''
+ """
object_class = WorkoutSession
url = 'manager:session:edit'
@@ -86,14 +86,14 @@ class EditWorkoutSessionTestCase(WorkoutManagerEditTestCase):
class WorkoutSessionModelTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests other functionality from the model
- '''
+ """
def test_unicode(self):
- '''
+ """
Test the unicode representation
- '''
+ """
session = WorkoutSession()
session.workout = Workout.objects.get(pk=1)
@@ -103,9 +103,9 @@ class WorkoutSessionModelTestCase(WorkoutManagerTestCase):
class DeleteTestWorkoutTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a Workout
- '''
+ """
object_class = WorkoutSession
url = 'manager:session:delete'
@@ -113,9 +113,9 @@ class DeleteTestWorkoutTestCase(WorkoutManagerDeleteTestCase):
class WorkoutSessionDeleteLogsTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests that deleting a session can also delete all weight logs
- '''
+ """
def test_delete_logs(self):
self.user_login('admin')
@@ -134,14 +134,14 @@ class WorkoutSessionDeleteLogsTestCase(WorkoutManagerTestCase):
class WorkoutSessionTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests other workout session methods
- '''
+ """
def test_model_validation(self):
- '''
+ """
Tests the custom clean() method
- '''
+ """
self.user_login('admin')
# Values OK
@@ -177,14 +177,14 @@ class WorkoutSessionTestCase(WorkoutManagerTestCase):
class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
- '''
+ """
Workout log cache test case
- '''
+ """
def test_cache_update_session(self):
- '''
+ """
Test that the caches are cleared when updating a workout session
- '''
+ """
log_hash = hash((1, 2012, 10))
self.user_login('admin')
self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10}))
@@ -196,9 +196,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash)))
def test_cache_update_session_2(self):
- '''
+ """
Test that the caches are only cleared for a the session's month
- '''
+ """
log_hash = hash((1, 2012, 10))
self.user_login('admin')
self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10}))
@@ -211,9 +211,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash)))
def test_cache_delete_session(self):
- '''
+ """
Test that the caches are cleared when deleting a workout session
- '''
+ """
log_hash = hash((1, 2012, 10))
self.user_login('admin')
self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10}))
@@ -224,9 +224,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash)))
def test_cache_delete_session_2(self):
- '''
+ """
Test that the caches are only cleared for a the session's month
- '''
+ """
log_hash = hash((1, 2012, 10))
self.user_login('admin')
self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10}))
@@ -238,9 +238,9 @@ class WorkoutLogCacheTestCase(WorkoutManagerTestCase):
class WorkoutSessionApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the workout overview resource
- '''
+ """
pk = 4
resource = WorkoutSession
private_resource = True
diff --git a/wger/manager/views/day.py b/wger/manager/views/day.py
index 032ca9725..16f83835f 100644
--- a/wger/manager/views/day.py
+++ b/wger/manager/views/day.py
@@ -50,9 +50,9 @@ logger = logging.getLogger(__name__)
# Day functions
# ************************
class DayView(WgerFormMixin, LoginRequiredMixin):
- '''
+ """
Base generic view for exercise day
- '''
+ """
model = Day
fields = ('description', 'day')
@@ -61,9 +61,9 @@ class DayView(WgerFormMixin, LoginRequiredMixin):
return reverse('manager:workout:view', kwargs={'pk': self.object.training_id})
def get_form(self, form_class=DayForm):
- '''
+ """
Filter the days of the week that are alreeady used by other days
- '''
+ """
# Get the form
form = super(DayView, self).get_form(form_class)
@@ -88,9 +88,9 @@ class DayView(WgerFormMixin, LoginRequiredMixin):
class DayEditView(DayView, UpdateView):
- '''
+ """
Generic view to update an existing exercise day
- '''
+ """
form_action_urlname = 'manager:day:edit'
@@ -102,17 +102,17 @@ class DayEditView(DayView, UpdateView):
class DayCreateView(DayView, CreateView):
- '''
+ """
Generic view to add a new exercise day
- '''
+ """
title = ugettext_lazy('Add workout day')
owner_object = {'pk': 'workout_pk', 'class': Workout}
def form_valid(self, form):
- '''
+ """
Set the workout this day belongs to
- '''
+ """
form.instance.training = Workout.objects.get(pk=self.kwargs['workout_pk'])
return super(DayCreateView, self).form_valid(form)
@@ -126,9 +126,9 @@ class DayCreateView(DayView, CreateView):
@login_required
def delete(request, pk):
- '''
+ """
Deletes the given day
- '''
+ """
day = get_object_or_404(Day, training__user=request.user, pk=pk)
day.delete()
return HttpResponseRedirect(reverse('manager:workout:view', kwargs={'pk': day.training_id}))
@@ -136,11 +136,11 @@ def delete(request, pk):
@login_required
def view(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
diff --git a/wger/manager/views/ical.py b/wger/manager/views/ical.py
index 81589af53..a4c87327b 100644
--- a/wger/manager/views/ical.py
+++ b/wger/manager/views/ical.py
@@ -48,7 +48,7 @@ from wger.utils.helpers import (
logger = logging.getLogger(__name__)
-'''
+"""
Exports workouts and schedules as an iCal file that can be imported to a
calendaring application.
@@ -58,16 +58,16 @@ to make this work, looking at the module test files or the official RF is
* https://tools.ietf.org/html/rfc5545
* https://github.com/collective/icalendar/tree/master/src/icalendar/tests
-'''
+"""
# Helper functions
def get_calendar():
- '''
+ """
Creates and returns a calendar object
:return: Calendar
- '''
+ """
calendar = Calendar()
calendar.add('prodid', '-//wger Workout Manager//wger.de//')
calendar.add('version', get_version())
@@ -75,7 +75,7 @@ def get_calendar():
def get_events_workout(calendar, workout, duration, start_date=None):
- '''
+ """
Creates all necessary events from the given workout and adds them to
the calendar. Each event's occurrence ist set to weekly (one event for
each training day).
@@ -85,7 +85,7 @@ def get_events_workout(calendar, workout, duration, start_date=None):
:param duration: duration in weeks
:param start_date: start date, default: profile default
:return: None
- '''
+ """
start_date = start_date if start_date else workout.creation_date
end_date = start_date + datetime.timedelta(weeks=duration)
@@ -116,9 +116,9 @@ def get_events_workout(calendar, workout, duration, start_date=None):
# Views
def export(request, pk, uidb64=None, token=None):
- '''
+ """
Export the current workout as an iCal file
- '''
+ """
# Load the workout
if uidb64 is not None and token is not None:
@@ -147,9 +147,9 @@ def export(request, pk, uidb64=None, token=None):
def export_schedule(request, pk, uidb64=None, token=None):
- '''
+ """
Export the current schedule as an iCal file
- '''
+ """
# Load the schedule
if uidb64 is not None and token is not None:
diff --git a/wger/manager/views/log.py b/wger/manager/views/log.py
index eef181f05..180072f12 100644
--- a/wger/manager/views/log.py
+++ b/wger/manager/views/log.py
@@ -77,9 +77,9 @@ logger = logging.getLogger(__name__)
# Log functions
# ************************
class WorkoutLogUpdateView(WgerFormMixin, UpdateView, LoginRequiredMixin):
- '''
+ """
Generic view to edit an existing workout log weight entry
- '''
+ """
model = WorkoutLog
form_class = WorkoutLogForm
success_url = reverse_lazy('manager:workout:calendar')
@@ -93,9 +93,9 @@ class WorkoutLogUpdateView(WgerFormMixin, UpdateView, LoginRequiredMixin):
class WorkoutLogDeleteView(WgerDeleteMixin, DeleteView, LoginRequiredMixin):
- '''
+ """
Delete a workout log
- '''
+ """
model = WorkoutLog
fields = ('exercise',
@@ -110,9 +110,9 @@ class WorkoutLogDeleteView(WgerDeleteMixin, DeleteView, LoginRequiredMixin):
def add(request, pk):
- '''
+ """
Add a new workout log
- '''
+ """
template_data = {}
template_data.update(csrf(request))
@@ -238,9 +238,9 @@ def add(request, pk):
class WorkoutLogDetailView(DetailView, LoginRequiredMixin):
- '''
+ """
An overview of the workout's log
- '''
+ """
model = Workout
template_name = 'workout/log.html'
@@ -295,9 +295,9 @@ class WorkoutLogDetailView(DetailView, LoginRequiredMixin):
return context
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Check for ownership
- '''
+ """
workout = get_object_or_404(Workout, pk=kwargs['pk'])
self.owner_user = workout.user
@@ -311,9 +311,9 @@ class WorkoutLogDetailView(DetailView, LoginRequiredMixin):
def calendar(request, username=None, year=None, month=None):
- '''
+ """
Show a calendar with all the workout logs
- '''
+ """
context = {}
is_owner, user = check_access(request.user, username)
year = int(year) if year else datetime.date.today().year
@@ -336,9 +336,9 @@ def calendar(request, username=None, year=None, month=None):
def day(request, username, year, month, day):
- '''
+ """
Show the logs for a single day
- '''
+ """
context = {}
is_owner, user = check_access(request.user, username)
diff --git a/wger/manager/views/pdf.py b/wger/manager/views/pdf.py
index 5a5a6f828..47b750f7b 100644
--- a/wger/manager/views/pdf.py
+++ b/wger/manager/views/pdf.py
@@ -48,13 +48,13 @@ logger = logging.getLogger(__name__)
def workout_log(request, id, images=False, comments=False, uidb64=None, token=None):
- '''
+ """
Generates a PDF with the contents of the given workout
See also
* http://www.blog.pythonlibrary.org/2010/09/21/reportlab
* http://www.reportlab.com/apis/reportlab/dev/platypus.html
- '''
+ """
comments = bool(int(comments))
images = bool(int(images))
@@ -113,16 +113,16 @@ def workout_log(request, id, images=False, comments=False, uidb64=None, token=No
def workout_view(request, id, images=False, comments=False, uidb64=None, token=None):
- '''
+ """
Generates a PDF with the contents of the workout, without table for logs
- '''
+ """
- '''
+ """
Generates a PDF with the contents of the given workout
See also
* http://www.blog.pythonlibrary.org/2010/09/21/reportlab
* http://www.reportlab.com/apis/reportlab/dev/platypus.html
- '''
+ """
comments = bool(int(comments))
images = bool(int(images))
diff --git a/wger/manager/views/schedule.py b/wger/manager/views/schedule.py
index 82394ed29..7cfb88303 100644
--- a/wger/manager/views/schedule.py
+++ b/wger/manager/views/schedule.py
@@ -74,9 +74,9 @@ logger = logging.getLogger(__name__)
@login_required
def overview(request):
- '''
+ """
An overview of all the user's schedules
- '''
+ """
template_data = {}
template_data['schedules'] = (Schedule.objects
@@ -87,9 +87,9 @@ def overview(request):
@vary_on_headers('User-Agent')
def view(request, pk):
- '''
+ """
Show the workout schedule
- '''
+ """
template_data = {}
schedule = get_object_or_404(Schedule, pk=pk)
user = schedule.user
@@ -118,9 +118,9 @@ def view(request, pk):
def export_pdf_log(request, pk, images=False, comments=False, uidb64=None, token=None):
- '''
+ """
Show the workout schedule
- '''
+ """
user = request.user
comments = bool(int(comments))
@@ -183,9 +183,9 @@ def export_pdf_log(request, pk, images=False, comments=False, uidb64=None, token
def export_pdf_table(request, pk, images=False, comments=False, uidb64=None, token=None):
- '''
+ """
Show the workout schedule
- '''
+ """
user = request.user
comments = bool(int(comments))
@@ -250,12 +250,12 @@ def export_pdf_table(request, pk, images=False, comments=False, uidb64=None, tok
@login_required
def start(request, pk):
- '''
+ """
Starts a schedule
This simply sets the start date to today and the schedule is marked as
being active.
- '''
+ """
schedule = get_object_or_404(Schedule, pk=pk, user=request.user)
schedule.is_active = True
@@ -265,9 +265,9 @@ def start(request, pk):
class ScheduleCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin):
- '''
+ """
Creates a new workout schedule
- '''
+ """
model = Schedule
fields = '__all__'
@@ -276,7 +276,7 @@ class ScheduleCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin):
form_action = reverse_lazy('manager:schedule:add')
def form_valid(self, form):
- '''set the submitter'''
+ """set the submitter"""
form.instance.user = self.request.user
return super(ScheduleCreateView, self).form_valid(form)
@@ -285,9 +285,9 @@ class ScheduleCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin):
class ScheduleDeleteView(WgerDeleteMixin, DeleteView, PermissionRequiredMixin):
- '''
+ """
Generic view to delete a schedule
- '''
+ """
model = Schedule
fields = ('name', 'start_date', 'is_active', 'is_loop')
@@ -296,27 +296,27 @@ class ScheduleDeleteView(WgerDeleteMixin, DeleteView, PermissionRequiredMixin):
messages = ugettext_lazy('Successfully deleted')
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ScheduleDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
return context
class ScheduleEditView(WgerFormMixin, UpdateView, PermissionRequiredMixin):
- '''
+ """
Generic view to update an existing workout routine
- '''
+ """
model = Schedule
fields = '__all__'
form_action_urlname = 'manager:schedule:edit'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(ScheduleEditView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
diff --git a/wger/manager/views/schedule_step.py b/wger/manager/views/schedule_step.py
index 9aacb709c..90825ddce 100644
--- a/wger/manager/views/schedule_step.py
+++ b/wger/manager/views/schedule_step.py
@@ -51,21 +51,21 @@ logger = logging.getLogger(__name__)
class StepCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin):
- '''
+ """
Creates a new workout schedule
- '''
+ """
model = ScheduleStep
fields = '__all__'
title = ugettext_lazy('Add workout')
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))
@@ -86,7 +86,7 @@ class StepCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin):
return reverse('manager:schedule:view', kwargs={'pk': self.kwargs['schedule_pk']})
def form_valid(self, form):
- '''Set the schedule and the order'''
+ """Set the schedule and the order"""
schedule = Schedule.objects.get(pk=self.kwargs['schedule_pk'])
@@ -97,21 +97,21 @@ class StepCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin):
class StepEditView(WgerFormMixin, UpdateView, PermissionRequiredMixin):
- '''
+ """
Generic view to update an existing schedule step
- '''
+ """
model = ScheduleStep
title = ugettext_lazy('Edit workout')
form_action_urlname = 'manager: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))
@@ -127,9 +127,9 @@ class StepEditView(WgerFormMixin, UpdateView, PermissionRequiredMixin):
class StepDeleteView(WgerDeleteMixin, DeleteView, PermissionRequiredMixin):
- '''
+ """
Generic view to delete a schedule step
- '''
+ """
model = ScheduleStep
fields = ('workout', 'duration', 'order')
@@ -140,9 +140,9 @@ class StepDeleteView(WgerDeleteMixin, DeleteView, PermissionRequiredMixin):
return reverse('manager:schedule:view', kwargs={'pk': self.object.schedule.id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(StepDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
context['form_action'] = reverse('core:license:delete', kwargs={'pk': self.kwargs['pk']})
diff --git a/wger/manager/views/set.py b/wger/manager/views/set.py
index b4d3b0cd9..6da47c898 100644
--- a/wger/manager/views/set.py
+++ b/wger/manager/views/set.py
@@ -70,10 +70,10 @@ SettingFormset = modelformset_factory(Setting,
@login_required
def create(request, day_pk):
- '''
+ """
Creates a new set. This view handles both the set form and the corresponding
settings formsets
- '''
+ """
day = get_object_or_404(Day, pk=day_pk)
if day.get_owner_object().user != request.user:
return HttpResponseForbidden()
@@ -146,9 +146,9 @@ def create(request, day_pk):
@login_required
def get_formset(request, exercise_pk, reps=Set.DEFAULT_SETS):
- '''
+ """
Returns a formset. This is then rendered inside the new set template
- '''
+ """
exercise = Exercise.objects.get(pk=exercise_pk)
SettingFormSet = inlineformset_factory(Set,
Setting,
@@ -166,9 +166,9 @@ def get_formset(request, exercise_pk, reps=Set.DEFAULT_SETS):
@login_required
def delete(request, pk):
- '''
+ """
Deletes the given set
- '''
+ """
# Load the set
set_obj = get_object_or_404(Set, pk=pk)
@@ -184,9 +184,9 @@ def delete(request, pk):
@login_required
def edit(request, pk):
- '''
+ """
Edit a set (its settings actually)
- '''
+ """
set_obj = get_object_or_404(Set, pk=pk)
if set_obj.get_owner_object().user != request.user:
return HttpResponseForbidden()
diff --git a/wger/manager/views/workout.py b/wger/manager/views/workout.py
index 5e721e3f0..59407ed98 100644
--- a/wger/manager/views/workout.py
+++ b/wger/manager/views/workout.py
@@ -77,9 +77,9 @@ logger = logging.getLogger(__name__)
# ************************
@login_required
def overview(request):
- '''
+ """
An overview of all the user's workouts
- '''
+ """
template_data = {}
@@ -93,9 +93,9 @@ def overview(request):
@vary_on_headers('User-Agent')
def view(request, pk):
- '''
+ """
Show the workout with the given ID
- '''
+ """
template_data = {}
workout = get_object_or_404(Workout, pk=pk)
user = workout.user
@@ -143,9 +143,9 @@ def view(request, pk):
@login_required
def copy_workout(request, pk):
- '''
+ """
Makes a copy of a workout
- '''
+ """
workout = get_object_or_404(Workout, pk=pk)
user = workout.user
@@ -225,9 +225,9 @@ def copy_workout(request, pk):
@login_required
def add(request):
- '''
+ """
Add a new workout and redirect to its page
- '''
+ """
workout = Workout()
workout.user = request.user
workout.save()
@@ -236,9 +236,9 @@ def add(request):
class WorkoutDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
- '''
+ """
Generic view to delete a workout routine
- '''
+ """
model = Workout
fields = ('comment',)
@@ -254,9 +254,9 @@ class WorkoutDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
class WorkoutEditView(WgerFormMixin, LoginRequiredMixin, UpdateView):
- '''
+ """
Generic view to update an existing workout routine
- '''
+ """
model = Workout
form_class = WorkoutForm
@@ -270,10 +270,10 @@ class WorkoutEditView(WgerFormMixin, LoginRequiredMixin, UpdateView):
class LastWeightHelper:
- '''
+ """
Small helper class to retrieve the last workout log for a certain
user, exercise and repetition combination.
- '''
+ """
user = None
last_weight_list = {}
@@ -281,14 +281,14 @@ class LastWeightHelper:
self.user = user
def get_last_weight(self, exercise, reps, default_weight):
- '''
+ """
Returns an emtpy string if no entry is found
:param exercise:
:param reps:
:param default_weight:
:return: WorkoutLog or '' if none is found
- '''
+ """
key = (self.user.pk, exercise.pk, reps, default_weight)
if self.last_weight_list.get(key) is None:
last_log = WorkoutLog.objects.filter(user=self.user,
@@ -303,9 +303,9 @@ class LastWeightHelper:
@login_required
def timer(request, day_pk):
- '''
+ """
The timer view ("gym mode") for a workout
- '''
+ """
day = get_object_or_404(Day, pk=day_pk, training__user=request.user)
canonical_day = day.canonical_representation
diff --git a/wger/manager/views/workout_session.py b/wger/manager/views/workout_session.py
index c7df24f95..5574b6018 100644
--- a/wger/manager/views/workout_session.py
+++ b/wger/manager/views/workout_session.py
@@ -53,15 +53,15 @@ from wger.utils.generic_views import (
logger = logging.getLogger(__name__)
-'''
+"""
Workout session
-'''
+"""
class WorkoutSessionUpdateView(WgerFormMixin, LoginRequiredMixin, UpdateView):
- '''
+ """
Generic view to edit an existing workout session entry
- '''
+ """
model = WorkoutSession
form_class = WorkoutSessionForm
@@ -77,17 +77,17 @@ class WorkoutSessionUpdateView(WgerFormMixin, LoginRequiredMixin, UpdateView):
class WorkoutSessionAddView(WgerFormMixin, LoginRequiredMixin, CreateView):
- '''
+ """
Generic view to add a new workout session entry
- '''
+ """
model = WorkoutSession
form_class = WorkoutSessionForm
def get_date(self):
- '''
+ """
Returns a date object from the URL parameters or None if no date
could be created
- '''
+ """
try:
date = datetime.date(int(self.kwargs['year']),
int(self.kwargs['month']),
@@ -98,9 +98,9 @@ class WorkoutSessionAddView(WgerFormMixin, LoginRequiredMixin, CreateView):
return date
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Check for ownership
- '''
+ """
workout = Workout.objects.get(pk=kwargs['workout_pk'])
if workout.get_owner_object().user != request.user:
return HttpResponseForbidden()
@@ -124,9 +124,9 @@ class WorkoutSessionAddView(WgerFormMixin, LoginRequiredMixin, CreateView):
return reverse('manager:workout:calendar')
def form_valid(self, form):
- '''
+ """
Set the workout and the user
- '''
+ """
workout = Workout.objects.get(pk=self.kwargs['workout_pk'])
form.instance.workout = workout
@@ -136,9 +136,9 @@ class WorkoutSessionAddView(WgerFormMixin, LoginRequiredMixin, CreateView):
class WorkoutSessionDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
- '''
+ """
Generic view to delete a workout routine
- '''
+ """
model = WorkoutSession
fields = ('date', 'notes', 'impression', 'time_start', 'time_end')
@@ -146,9 +146,9 @@ class WorkoutSessionDeleteView(WgerDeleteMixin, LoginRequiredMixin, DeleteView):
messages = ugettext_lazy('Successfully deleted')
def delete(self, request, *args, **kwargs):
- '''
+ """
Delete the workout session and, if wished, all associated weight logs as well
- '''
+ """
if self.kwargs.get('logs') == 'logs':
WorkoutLog.objects.filter(user=self.request.user, date=self.get_object().date).delete()
diff --git a/wger/nutrition/api/resources.py b/wger/nutrition/api/resources.py
index 21af0326a..2b3fc346e 100644
--- a/wger/nutrition/api/resources.py
+++ b/wger/nutrition/api/resources.py
@@ -86,22 +86,22 @@ class IngredientToWeightUnit(ModelResource):
class NutritionPlanResource(ModelResource):
- '''
+ """
Resource for nutritional plans
- '''
+ """
meals = fields.ToManyField('wger.nutrition.api.resources.MealResource', 'meal_set')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(user=bundle.request.user)
def dehydrate(self, bundle):
- '''
+ """
Also send the nutritional values
- '''
+ """
bundle.data['nutritional_values'] = bundle.obj.get_nutritional_values()
return bundle
@@ -116,23 +116,23 @@ class NutritionPlanResource(ModelResource):
class MealResource(ModelResource):
- '''
+ """
Resource for meals
- '''
+ """
plan = fields.ToOneField(NutritionPlanResource, 'plan')
meal_items = fields.ToManyField('wger.nutrition.api.resources.MealItemResource', 'mealitem_set')
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(plan__user=bundle.request.user)
def dehydrate(self, bundle):
- '''
+ """
Also send the nutritional values
- '''
+ """
bundle.data['nutritional_values'] = bundle.obj.get_nutritional_values()
return bundle
@@ -147,24 +147,24 @@ class MealResource(ModelResource):
class MealItemResource(ModelResource):
- '''
+ """
Resource for meal items
- '''
+ """
meal = fields.ToOneField(MealResource, 'meal')
ingredient = fields.ToOneField(IngredientResource, 'ingredient')
weight_unit = fields.ToOneField(WeightUnitResource, 'weight_unit', null=True)
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(meal__plan__user=bundle.request.user)
def dehydrate(self, bundle):
- '''
+ """
Also send the nutritional values
- '''
+ """
bundle.data['nutritional_values'] = bundle.obj.get_nutritional_values()
return bundle
diff --git a/wger/nutrition/api/serializers.py b/wger/nutrition/api/serializers.py
index c9b9b9bae..35b39aaab 100644
--- a/wger/nutrition/api/serializers.py
+++ b/wger/nutrition/api/serializers.py
@@ -30,9 +30,9 @@ from wger.nutrition.models import (
class NutritionPlanSerializer(serializers.ModelSerializer):
- '''
+ """
Nutritional plan serializer
- '''
+ """
class Meta:
model = NutritionPlan
@@ -40,9 +40,9 @@ class NutritionPlanSerializer(serializers.ModelSerializer):
class IngredientWeightUnitSerializer(serializers.ModelSerializer):
- '''
+ """
IngredientWeightUnit serializer
- '''
+ """
class Meta:
model = IngredientWeightUnit
@@ -50,9 +50,9 @@ class IngredientWeightUnitSerializer(serializers.ModelSerializer):
class WeightUnitSerializer(serializers.ModelSerializer):
- '''
+ """
WeightUnit serializer
- '''
+ """
class Meta:
model = WeightUnit
@@ -60,9 +60,9 @@ class WeightUnitSerializer(serializers.ModelSerializer):
class MealItemSerializer(serializers.ModelSerializer):
- '''
+ """
MealItem serializer
- '''
+ """
meal = serializers.PrimaryKeyRelatedField(label='Nutrition plan',
queryset=Meal.objects.all())
@@ -72,9 +72,9 @@ class MealItemSerializer(serializers.ModelSerializer):
class MealSerializer(serializers.ModelSerializer):
- '''
+ """
Meal serializer
- '''
+ """
plan = serializers.PrimaryKeyRelatedField(label='Nutrition plan',
queryset=NutritionPlan.objects.all())
@@ -84,9 +84,9 @@ class MealSerializer(serializers.ModelSerializer):
class IngredientSerializer(serializers.ModelSerializer):
- '''
+ """
Ingredient serializer
- '''
+ """
class Meta:
model = Ingredient
diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.py
index 3f4aa43ed..82094a94e 100644
--- a/wger/nutrition/api/views.py
+++ b/wger/nutrition/api/views.py
@@ -49,9 +49,9 @@ from wger.utils.viewsets import WgerOwnerObjectModelViewSet
class IngredientViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for ingredient objects
- '''
+ """
queryset = Ingredient.objects.all()
serializer_class = IngredientSerializer
ordering_fields = '__all__'
@@ -73,14 +73,14 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):
@action(detail=True)
def get_values(self, request, pk):
- '''
+ """
Calculates the nutritional values for current ingredient and
the given amount and unit.
This function basically just performs a multiplication (in the model), and
is a candidate to be moved to pure AJAX calls, however doing it like this
keeps the logic nicely hidden and respects the DRY principle.
- '''
+ """
result = {
'energy': 0,
@@ -122,11 +122,11 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):
@api_view(['GET'])
def search(request):
- '''
+ """
Searches for ingredients.
This format is currently used by the ingredient search autocompleter
- '''
+ """
q = request.GET.get('term', None)
results = []
json_response = {}
@@ -151,9 +151,9 @@ def search(request):
class WeightUnitViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for weight unit objects
- '''
+ """
queryset = WeightUnit.objects.all()
serializer_class = WeightUnitSerializer
ordering_fields = '__all__'
@@ -162,9 +162,9 @@ class WeightUnitViewSet(viewsets.ReadOnlyModelViewSet):
class IngredientWeightUnitViewSet(viewsets.ReadOnlyModelViewSet):
- '''
+ """
API endpoint for many-to-many table ingredient-weight unit objects
- '''
+ """
queryset = IngredientWeightUnit.objects.all()
serializer_class = IngredientWeightUnitSerializer
ordering_fields = '__all__'
@@ -175,9 +175,9 @@ class IngredientWeightUnitViewSet(viewsets.ReadOnlyModelViewSet):
class NutritionPlanViewSet(viewsets.ModelViewSet):
- '''
+ """
API endpoint for nutrition plan objects
- '''
+ """
serializer_class = NutritionPlanSerializer
is_private = True
ordering_fields = '__all__'
@@ -187,29 +187,29 @@ class NutritionPlanViewSet(viewsets.ModelViewSet):
'has_goal_calories')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return NutritionPlan.objects.filter(user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the owner
- '''
+ """
serializer.save(user=self.request.user, language=load_language())
@action(detail=True)
def nutritional_values(self, request, pk):
- '''
+ """
Return an overview of the nutritional plan's values
- '''
+ """
return Response(NutritionPlan.objects.get(pk=pk).get_nutritional_values())
class MealViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for meal objects
- '''
+ """
serializer_class = MealSerializer
is_private = True
ordering_fields = '__all__'
@@ -218,35 +218,35 @@ class MealViewSet(WgerOwnerObjectModelViewSet):
'time')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return Meal.objects.filter(plan__user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the order
- '''
+ """
serializer.save(order=1)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(NutritionPlan, 'plan')]
@action(detail=True)
def nutritional_values(self, request, pk):
- '''
+ """
Return an overview of the nutritional plan's values
- '''
+ """
return Response(Meal.objects.get(pk=pk).get_nutritional_values())
class MealItemViewSet(WgerOwnerObjectModelViewSet):
- '''
+ """
API endpoint for meal item objects
- '''
+ """
serializer_class = MealItemSerializer
is_private = True
ordering_fields = '__all__'
@@ -257,26 +257,26 @@ class MealItemViewSet(WgerOwnerObjectModelViewSet):
'weight_unit')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return MealItem.objects.filter(meal__plan__user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the order
- '''
+ """
serializer.save(order=1)
def get_owner_objects(self):
- '''
+ """
Return objects to check for ownership permission
- '''
+ """
return [(Meal, 'meal')]
@action(detail=True)
def nutritional_values(self, request, pk):
- '''
+ """
Return an overview of the nutritional plan's values
- '''
+ """
return Response(MealItem.objects.get(pk=pk).get_nutritional_values())
diff --git a/wger/nutrition/forms.py b/wger/nutrition/forms.py
index 3f9744395..3e5f7fb29 100644
--- a/wger/nutrition/forms.py
+++ b/wger/nutrition/forms.py
@@ -35,9 +35,9 @@ logger = logging.getLogger(__name__)
class UnitChooserForm(forms.Form):
- '''
+ """
A small form to select an amount and a unit for an ingredient
- '''
+ """
amount = forms.DecimalField(decimal_places=2,
max_digits=5,
localize=True)
@@ -74,9 +74,9 @@ class BmiForm(forms.ModelForm):
class BmrForm(forms.ModelForm):
- '''
+ """
Form for the basal metabolic rate
- '''
+ """
weight = forms.DecimalField(widget=Html5NumberInput())
class Meta:
@@ -85,9 +85,9 @@ class BmrForm(forms.ModelForm):
class PhysicalActivitiesForm(forms.ModelForm):
- '''
+ """
Form for the additional physical activities
- '''
+ """
class Meta:
model = UserProfile
fields = ('sleep_hours',
@@ -100,9 +100,9 @@ class PhysicalActivitiesForm(forms.ModelForm):
class DailyCaloriesForm(forms.ModelForm):
- '''
+ """
Form for the total daily calories needed
- '''
+ """
base_calories = forms.IntegerField(label=_('Basic caloric intake'),
help_text=_('Your basic caloric intake as calculated for '
diff --git a/wger/nutrition/migrations/0002_auto_20170101_1538.py b/wger/nutrition/migrations/0002_auto_20170101_1538.py
index 5b47fc6bf..cc83b68b4 100644
--- a/wger/nutrition/migrations/0002_auto_20170101_1538.py
+++ b/wger/nutrition/migrations/0002_auto_20170101_1538.py
@@ -5,9 +5,9 @@ from __future__ import unicode_literals
from django.db import migrations, models
def copy_username(apps, schema_editor):
- '''
+ """
Copies the exercise name to the original name field
- '''
+ """
Ingredient = apps.get_model("nutrition", "Ingredient")
for ingredient in Ingredient.objects.all():
if ingredient.user:
@@ -17,9 +17,9 @@ def copy_username(apps, schema_editor):
ingredient.save()
def update_status(apps, schema_editor):
- '''
+ """
Updates the status of the ingredients
- '''
+ """
Ingredient = apps.get_model("nutrition", "Ingredient")
Ingredient.objects.filter(status__in=('5', '4')).update(status=2)
diff --git a/wger/nutrition/models.py b/wger/nutrition/models.py
index e00e800ab..24e7dfaee 100644
--- a/wger/nutrition/models.py
+++ b/wger/nutrition/models.py
@@ -60,18 +60,18 @@ ENERGY_FACTOR = {'protein': {'kg': 4,
'lb': 113},
'fat': {'kg': 9,
'lb': 225}}
-'''
+"""
Simple approximation of energy (kcal) provided per gram or ounce
-'''
+"""
logger = logging.getLogger(__name__)
class NutritionPlan(models.Model):
- '''
+ """
A nutrition plan
- '''
+ """
# Metaclass to set some other properties
class Meta:
@@ -99,27 +99,27 @@ class NutritionPlan(models.Model):
"plan as having a goal amount of calories. "
"You can use the calculator or enter the "
"value yourself."))
- '''A flag indicating whether the plan has a goal amount of calories'''
+ """A flag indicating whether the plan has a goal amount of calories"""
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
if self.description:
return u"{0}".format(self.description)
else:
return u"{0}".format(_("Nutrition plan"))
def get_absolute_url(self):
- '''
+ """
Returns the canonical URL to view this object
- '''
+ """
return reverse('nutrition:plan:view', kwargs={'id': self.id})
def get_nutritional_values(self):
- '''
+ """
Sums the nutritional info of all items in the plan
- '''
+ """
use_metric = self.user.userprofile.use_metric
unit = 'kg' if use_metric else 'lb'
result = {'total': {'energy': 0,
@@ -166,10 +166,10 @@ class NutritionPlan(models.Model):
return result
def get_closest_weight_entry(self):
- '''
+ """
Returns the closest weight entry for the nutrition plan.
Returns None if there are no entries.
- '''
+ """
target = self.creation_date
closest_entry_gte = WeightEntry.objects.filter(user=self.user) \
.filter(date__gte=target).order_by('date').first()
@@ -183,16 +183,16 @@ class NutritionPlan(models.Model):
return closest_entry_lte
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self
def get_calories_approximation(self):
- '''
+ """
Calculates the deviation from the goal calories and the actual
amount of the current plan
- '''
+ """
goal_calories = self.user.userprofile.calories
actual_calories = self.get_nutritional_values()['total']['energy']
@@ -212,15 +212,15 @@ class NutritionPlan(models.Model):
class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
- '''
+ """
An ingredient, with some approximate nutrition values
- '''
+ """
ENERGY_APPROXIMATION = 15
- '''
+ """
How much the calculated energy from protein, etc. can deviate from the
energy amount given (in percent).
- '''
+ """
# Metaclass to set some other properties
class Meta:
@@ -305,14 +305,14 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
#
def get_absolute_url(self):
- '''
+ """
Returns the canonical URL to view this object
- '''
+ """
return reverse('nutrition:ingredient:view',
kwargs={'id': self.id, 'slug': slugify(self.name)})
def clean(self):
- '''
+ """
Do a very broad sanity check on the nutritional values according to
the following rules:
- 1g of protein: 4kcal
@@ -321,7 +321,7 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
The sum is then compared to the given total energy, with ENERGY_APPROXIMATION
percent tolerance.
- '''
+ """
# Note: calculations in 100 grams, to save us the '/100' everywhere
energy_protein = 0
@@ -350,23 +350,23 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
'provided by protein, carbohydrates and fat.'))
def save(self, *args, **kwargs):
- '''
+ """
Reset the cache
- '''
+ """
super(Ingredient, self).save(*args, **kwargs)
cache.delete(cache_mapper.get_ingredient_key(self.id))
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
def __eq__(self, other):
- '''
+ """
Compare ingredients based on their values, not like django on their PKs
- '''
+ """
logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.')
equal = True
@@ -395,11 +395,11 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
# Own methods
#
def compare_with_database(self):
- '''
+ """
Compares the current ingredient with the version saved in the database.
If the current object has no PK, returns false
- '''
+ """
if not self.pk:
return False
@@ -410,10 +410,10 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
return True
def send_email(self, request):
- '''
+ """
Sends an email after being successfully added to the database (for user
submitted ingredients only)
- '''
+ """
try:
user = User.objects.get(username=self.license_author)
except User.DoesNotExist:
@@ -446,23 +446,23 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
# Send email to administrator
subject = _('New user submitted ingredient')
- message = _(u'''The user {0} submitted a new ingredient "{1}".'''.format(
+ message = _(u"""The user {0} submitted a new ingredient "{1}".""".format(
request.user.username, self.name))
mail.mail_admins(subject,
message,
fail_silently=True)
def get_owner_object(self):
- '''
+ """
Ingredient has no owner information
- '''
+ """
return False
class WeightUnit(models.Model):
- '''
+ """
A more human usable weight unit (spoon, table, slice...)
- '''
+ """
language = models.ForeignKey(Language,
verbose_name=_('Language'),
@@ -476,22 +476,22 @@ class WeightUnit(models.Model):
ordering = ["name", ]
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return self.name
def get_owner_object(self):
- '''
+ """
Weight unit has no owner information
- '''
+ """
return None
class IngredientWeightUnit(models.Model):
- '''
+ """
A specific human usable weight unit for an ingredient
- '''
+ """
ingredient = models.ForeignKey(Ingredient,
verbose_name=_('Ingredient'),
@@ -507,15 +507,15 @@ class IngredientWeightUnit(models.Model):
help_text=_('Unit amount, e.g. "1 Cup" or "1/2 spoon"'))
def get_owner_object(self):
- '''
+ """
Weight unit has no owner information
- '''
+ """
return None
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{0}{1} ({2}g)".format(self.amount if self.amount > 1 else '',
self.unit.name,
@@ -523,9 +523,9 @@ class IngredientWeightUnit(models.Model):
class Meal(models.Model):
- '''
+ """
A meal
- '''
+ """
# Metaclass to set some other properties
class Meta:
@@ -543,23 +543,23 @@ class Meal(models.Model):
verbose_name=_('Time (approx)'))
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{0} Meal".format(self.order)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self.plan
def get_nutritional_values(self, use_metric=True):
- '''
+ """
Sums the nutrional info of all items in the meal
:param use_metric Flag that controls the units used
- '''
+ """
nutritional_info = {'energy': 0,
'protein': 0,
'carbohydrates': 0,
@@ -584,9 +584,9 @@ class Meal(models.Model):
class MealItem(models.Model):
- '''
+ """
An item (component) of a meal
- '''
+ """
meal = models.ForeignKey(Meal,
verbose_name=_('Nutrition plan'),
@@ -611,23 +611,23 @@ class MealItem(models.Model):
MaxValueValidator(1000)])
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{0}g ingredient {1}".format(self.amount, self.ingredient_id)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self.meal.plan
def get_unit_type(self):
- '''
+ """
Returns the type of unit used:
- a value in grams
- a 'human' unit like 'a cup' or 'a slice'
- '''
+ """
if self.weight_unit:
return MEALITEM_WEIGHT_UNIT
@@ -635,11 +635,11 @@ class MealItem(models.Model):
return MEALITEM_WEIGHT_GRAM
def get_nutritional_values(self, use_metric=True):
- '''
+ """
Sums the nutrional info for the ingredient in the MealItem
:param use_metric Flag that controls the units used
- '''
+ """
nutritional_info = {'energy': 0,
'protein': 0,
'carbohydrates': 0,
diff --git a/wger/nutrition/tests/test_bmi.py b/wger/nutrition/tests/test_bmi.py
index 5bef4e855..41e0e80b2 100644
--- a/wger/nutrition/tests/test_bmi.py
+++ b/wger/nutrition/tests/test_bmi.py
@@ -29,14 +29,14 @@ from wger.weight.models import WeightEntry
class BmiTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the BMI methods and views
- '''
+ """
def test_page(self):
- '''
+ """
Access the BMI page
- '''
+ """
response = self.client.get(reverse('nutrition:bmi:view'))
self.assertEqual(response.status_code, 302)
@@ -47,9 +47,9 @@ class BmiTestCase(WorkoutManagerTestCase):
def test_calculator(self):
- '''
+ """
Tests the calculator itself
- '''
+ """
self.user_login('test')
response = self.client.post(reverse('nutrition:bmi:calculate'),
@@ -63,9 +63,9 @@ class BmiTestCase(WorkoutManagerTestCase):
def test_calculator_imperial(self):
- '''
+ """
Tests the calculator using imperial units
- '''
+ """
self.user_login('test')
profile = UserProfile.objects.get(user__username='test')
@@ -81,9 +81,9 @@ class BmiTestCase(WorkoutManagerTestCase):
self.assertEqual(Decimal(bmi['height']), Decimal(180))
def test_automatic_weight_entry(self):
- '''
+ """
Tests that weight entries are automatically created or updated
- '''
+ """
self.user_login('test')
user = User.objects.get(username=self.current_user)
diff --git a/wger/nutrition/tests/test_calories_calculator.py b/wger/nutrition/tests/test_calories_calculator.py
index 177bd9ab9..19d89d004 100644
--- a/wger/nutrition/tests/test_calories_calculator.py
+++ b/wger/nutrition/tests/test_calories_calculator.py
@@ -28,14 +28,14 @@ from wger.weight.models import WeightEntry
class CaloriesCalculatorTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the calories calculator methods and views
- '''
+ """
def test_page(self):
- '''
+ """
Access the page
- '''
+ """
response = self.client.get(reverse('nutrition:calories:view'))
self.assertEqual(response.status_code, 302)
@@ -45,9 +45,9 @@ class CaloriesCalculatorTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_calculator(self):
- '''
+ """
Tests the calculator itself
- '''
+ """
self.user_login('test')
response = self.client.post(reverse('nutrition:calories:activities'),
@@ -65,9 +65,9 @@ class CaloriesCalculatorTestCase(WorkoutManagerTestCase):
self.assertEqual(decimal.Decimal(result['activities']), decimal.Decimal(2920))
def test_automatic_weight_entry_bmi(self):
- '''
+ """
Tests that weight entries are automatically created or updated
- '''
+ """
self.user_login('test')
user = User.objects.get(username=self.current_user)
@@ -105,9 +105,9 @@ class CaloriesCalculatorTestCase(WorkoutManagerTestCase):
self.assertEqual(entry.date, datetime.date.today())
def test_bmr(self):
- '''
+ """
Tests the BMR view
- '''
+ """
self.user_login('test')
response = self.client.post(reverse('nutrition:calories:bmr'),
@@ -120,9 +120,9 @@ class CaloriesCalculatorTestCase(WorkoutManagerTestCase):
self.assertEqual(result, {'bmr': '1780'})
def test_automatic_weight_entry_bmr(self):
- '''
+ """
Tests that weight entries are automatically created or updated
- '''
+ """
self.user_login('test')
user = User.objects.get(username=self.current_user)
diff --git a/wger/nutrition/tests/test_copy_plan.py b/wger/nutrition/tests/test_copy_plan.py
index 61526bb5b..7274ba4ec 100644
--- a/wger/nutrition/tests/test_copy_plan.py
+++ b/wger/nutrition/tests/test_copy_plan.py
@@ -21,14 +21,14 @@ from wger.nutrition.models import NutritionPlan
class CopyPlanTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests copying a nutritional plan
- '''
+ """
def copy_plan(self, fail=False):
- '''
+ """
Helper function to test copying nutrition plans
- '''
+ """
# Open the copy nutritional plan form
response = self.client.get(reverse('nutrition:plan:copy', kwargs={'pk': 4}))
@@ -58,24 +58,24 @@ class CopyPlanTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_copy_plan_anonymous(self):
- '''
+ """
Test copying a nutritional plan as an anonymous user
- '''
+ """
self.copy_plan(fail=True)
def test_copy_plan_owner(self):
- '''
+ """
Test copying a nutritional plan as the owner user
- '''
+ """
self.user_login('test')
self.copy_plan(fail=False)
def test_copy_plan_other(self):
- '''
+ """
Test copying a nutritional plan as a logged in user not owning the plan
- '''
+ """
self.user_login('admin')
self.copy_plan(fail=True)
diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.py
index d8533ab96..86442aa9e 100644
--- a/wger/nutrition/tests/test_ingredient.py
+++ b/wger/nutrition/tests/test_ingredient.py
@@ -39,21 +39,21 @@ from wger.utils.constants import NUTRITION_TAB
class IngredientRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Ingredient.objects.get(pk=1)), 'Test ingredient 1')
class DeleteIngredientTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting an ingredient
- '''
+ """
object_class = Ingredient
url = 'nutrition:ingredient:delete'
@@ -61,9 +61,9 @@ class DeleteIngredientTestCase(WorkoutManagerDeleteTestCase):
class EditIngredientTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing an ingredient
- '''
+ """
object_class = Ingredient
url = 'nutrition:ingredient:edit'
@@ -81,18 +81,18 @@ class EditIngredientTestCase(WorkoutManagerEditTestCase):
'license_author': 'me!'}
def post_test_hook(self):
- '''
+ """
Test that the update date is correctly set
- '''
+ """
if self.current_user == 'admin':
ingredient = Ingredient.objects.get(pk=1)
self.assertEqual(ingredient.update_date, datetime.date.today())
class AddIngredientTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding an ingredient
- '''
+ """
object_class = Ingredient
url = 'nutrition:ingredient:add'
@@ -110,9 +110,9 @@ class AddIngredientTestCase(WorkoutManagerAddTestCase):
'license_author': 'me!'}
def post_test_hook(self):
- '''
+ """
Test that the creation date and the status are correctly set
- '''
+ """
if self.current_user == 'admin':
ingredient = Ingredient.objects.get(pk=self.pk_after)
self.assertEqual(ingredient.creation_date, datetime.date.today())
@@ -123,14 +123,14 @@ class AddIngredientTestCase(WorkoutManagerAddTestCase):
class IngredientDetailTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the ingredient details page
- '''
+ """
def ingredient_detail(self, editor=False):
- '''
+ """
Tests the ingredient details page
- '''
+ """
response = self.client.get(reverse('nutrition:ingredient:view', kwargs={'id': 6}))
self.assertEqual(response.status_code, 200)
@@ -154,38 +154,38 @@ class IngredientDetailTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 404)
def test_ingredient_detail_editor(self):
- '''
+ """
Tests the ingredient details page as a logged in user with editor rights
- '''
+ """
self.user_login('admin')
self.ingredient_detail(editor=True)
def test_ingredient_detail_non_editor(self):
- '''
+ """
Tests the ingredient details page as a logged in user without editor rights
- '''
+ """
self.user_login('test')
self.ingredient_detail(editor=False)
def test_ingredient_detail_logged_out(self):
- '''
+ """
Tests the ingredient details page as an anonymous (logged out) user
- '''
+ """
self.ingredient_detail(editor=False)
class IngredientSearchTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the ingredient search functions
- '''
+ """
def search_ingredient(self, fail=True):
- '''
+ """
Helper function
- '''
+ """
kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
response = self.client.get(reverse('ingredient-search'), {'term': 'test'}, **kwargs)
@@ -202,30 +202,30 @@ class IngredientSearchTestCase(WorkoutManagerTestCase):
self.assertEqual(len(result['suggestions']), 0)
def test_search_ingredient_anonymous(self):
- '''
+ """
Test searching for an ingredient by an anonymous user
- '''
+ """
self.search_ingredient()
def test_search_ingredient_logged_in(self):
- '''
+ """
Test searching for an ingredient by a logged in user
- '''
+ """
self.user_login('test')
self.search_ingredient()
class IngredientValuesTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the nutritional value calculator for an ingredient
- '''
+ """
def calculate_value(self):
- '''
+ """
Helper function
- '''
+ """
# Get the nutritional values in 1 gram of product
response = self.client.get(reverse('api-ingredient-get-values', kwargs={'pk': 1}),
@@ -264,29 +264,29 @@ class IngredientValuesTestCase(WorkoutManagerTestCase):
u'carbohydrates': u'0.14'})
def test_calculate_value_anonymous(self):
- '''
+ """
Calculate the nutritional values as an anonymous user
- '''
+ """
self.calculate_value()
def test_calculate_value_logged_in(self):
- '''
+ """
Calculate the nutritional values as a logged in user
- '''
+ """
self.user_login('test')
self.calculate_value()
class IngredientTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests other ingredient functions
- '''
+ """
def test_compare(self):
- '''
+ """
Tests the custom compare method based on values
- '''
+ """
language = Language.objects.get(pk=1)
ingredient1 = Ingredient.objects.get(pk=1)
@@ -319,9 +319,9 @@ class IngredientTestCase(WorkoutManagerTestCase):
self.assertFalse(ingredient1 == meal)
def test_total_energy(self):
- '''
+ """
Tests the custom clean() method
- '''
+ """
self.user_login('admin')
# Values OK
@@ -352,9 +352,9 @@ class IngredientTestCase(WorkoutManagerTestCase):
class IngredientApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the ingredient API resource
- '''
+ """
pk = 4
resource = Ingredient
private_resource = False
diff --git a/wger/nutrition/tests/test_ingredient_overview.py b/wger/nutrition/tests/test_ingredient_overview.py
index 3d8f50d25..766b0101e 100644
--- a/wger/nutrition/tests/test_ingredient_overview.py
+++ b/wger/nutrition/tests/test_ingredient_overview.py
@@ -22,9 +22,9 @@ from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE
class OverviewPlanTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the ingredient overview
- '''
+ """
def test_overview(self):
@@ -75,9 +75,9 @@ class OverviewPlanTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 404)
def ingredient_overview(self, logged_in=True, demo=False, admin=False):
- '''
+ """
Helper function to test the ingredient overview page
- '''
+ """
# Page exists
response = self.client.get(reverse('nutrition:ingredient:list'))
@@ -97,32 +97,32 @@ class OverviewPlanTestCase(WorkoutManagerTestCase):
self.assertContains(response, 'Only registered users can do this')
def test_ingredient_index_editor(self):
- '''
+ """
Tests the ingredient overview page as a logged in user with editor rights
- '''
+ """
self.user_login('admin')
self.ingredient_overview(admin=True)
def test_ingredient_index_non_editor(self):
- '''
+ """
Tests the overview overview page as a logged in user without editor rights
- '''
+ """
self.user_login('test')
self.ingredient_overview()
def test_ingredient_index_demo_user(self):
- '''
+ """
Tests the overview overview page as a logged in demo user
- '''
+ """
self.user_login('demo')
self.ingredient_overview(demo=True)
def test_ingredient_index_logged_out(self):
- '''
+ """
Tests the overview overview page as an anonymous (logged out) user
- '''
+ """
self.ingredient_overview(logged_in=False)
diff --git a/wger/nutrition/tests/test_meal.py b/wger/nutrition/tests/test_meal.py
index b3e76a069..fbc75859d 100644
--- a/wger/nutrition/tests/test_meal.py
+++ b/wger/nutrition/tests/test_meal.py
@@ -33,21 +33,21 @@ from wger.nutrition.models import (
class MealRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(Meal.objects.get(pk=1)), '1 Meal')
class EditMealTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a meal
- '''
+ """
object_class = Meal
url = 'nutrition:meal:edit'
@@ -56,9 +56,9 @@ class EditMealTestCase(WorkoutManagerEditTestCase):
class AddMealTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a Meal
- '''
+ """
object_class = Meal
url = reverse('nutrition:meal:add', kwargs={'plan_pk': 4})
@@ -68,14 +68,14 @@ class AddMealTestCase(WorkoutManagerAddTestCase):
class PlanOverviewTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the nutrition plan overview
- '''
+ """
def get_plan_overview(self):
- '''
+ """
Helper function to test the nutrition plan overview
- '''
+ """
response = self.client.get(reverse('nutrition:plan:overview'))
@@ -84,22 +84,22 @@ class PlanOverviewTestCase(WorkoutManagerTestCase):
self.assertEqual(len(response.context['plans']), 3)
def test_dashboard_logged_in(self):
- '''
+ """
Test the nutrition plan as a logged in user
- '''
+ """
self.user_login()
self.get_plan_overview()
class PlanDetailTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the nutrition plan detail view
- '''
+ """
def get_plan_detail_page(self, fail=False):
- '''
+ """
Helper function to test the plan detail view
- '''
+ """
response = self.client.get(reverse('nutrition:plan:view', kwargs={'id': 1}))
@@ -112,24 +112,24 @@ class PlanDetailTestCase(WorkoutManagerTestCase):
self.assertEqual(response.context['plan'], plan)
def test_dashboard_owner(self):
- '''
+ """
Test the nutrition plan as the owner user
- '''
+ """
self.user_login('test')
self.get_plan_detail_page(fail=False)
def test_dashboard_other(self):
- '''
+ """
Test the nutrition plan as a differnt user
- '''
+ """
self.user_login('admin')
self.get_plan_detail_page(fail=True)
class MealApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the meal overview resource
- '''
+ """
pk = 2
resource = Meal
private_resource = True
diff --git a/wger/nutrition/tests/test_meal_item.py b/wger/nutrition/tests/test_meal_item.py
index 22591070d..562d46bba 100644
--- a/wger/nutrition/tests/test_meal_item.py
+++ b/wger/nutrition/tests/test_meal_item.py
@@ -26,9 +26,9 @@ from wger.nutrition.models import MealItem
class EditMealItemUnitTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a meal, set the amount using a unit
- '''
+ """
object_class = MealItem
url = 'nutrition:meal_item:edit'
@@ -39,9 +39,9 @@ class EditMealItemUnitTestCase(WorkoutManagerEditTestCase):
class EditMealItemWeightTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a meal, set the amount using weight
- '''
+ """
object_class = MealItem
url = 'nutrition:meal_item:edit'
@@ -51,9 +51,9 @@ class EditMealItemWeightTestCase(WorkoutManagerEditTestCase):
class AddMealItemUnitTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a meal, set the amount using a unit
- '''
+ """
object_class = MealItem
url = reverse('nutrition:meal_item:add', kwargs={'meal_id': 3})
@@ -63,9 +63,9 @@ class AddMealItemUnitTestCase(WorkoutManagerAddTestCase):
class AddMealItemWeightTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a meal, set the amount using weight
- '''
+ """
object_class = MealItem
url = reverse('nutrition:meal_item:add', kwargs={'meal_id': 3})
@@ -74,9 +74,9 @@ class AddMealItemWeightTestCase(WorkoutManagerAddTestCase):
class MealItemApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the meal overview resource
- '''
+ """
pk = 10
resource = MealItem
private_resource = True
diff --git a/wger/nutrition/tests/test_nutritional_calculations.py b/wger/nutrition/tests/test_nutritional_calculations.py
index 6bd8a51b9..ea6e2cdad 100644
--- a/wger/nutrition/tests/test_nutritional_calculations.py
+++ b/wger/nutrition/tests/test_nutritional_calculations.py
@@ -27,9 +27,9 @@ logger = logging.getLogger(__name__)
class NutritionalValuesCalculationsTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the nutritional values calculators in the different models
- '''
+ """
def test_calculations(self):
plan = models.NutritionPlan(user_id=1, language_id=1)
@@ -130,10 +130,10 @@ class NutritionalValuesCalculationsTestCase(WorkoutManagerTestCase):
self.assertEqual(result_meal, result_plan['total'])
def test_calculations_user(self):
- '''
+ """
Tests the calculations
:return:
- '''
+ """
self.user_login('test')
plan = models.NutritionPlan.objects.get(pk=4)
values = plan.get_nutritional_values()
diff --git a/wger/nutrition/tests/test_pdf.py b/wger/nutrition/tests/test_pdf.py
index 7ba6b94b8..03e9b5727 100644
--- a/wger/nutrition/tests/test_pdf.py
+++ b/wger/nutrition/tests/test_pdf.py
@@ -24,15 +24,15 @@ from wger.utils.helpers import make_token
class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests exporting a nutritional plan as a pdf
- '''
+ """
def export_pdf_token(self):
- '''
+ """
Helper function to test exporting a nutritional plan as a pdf using
a token as access (no fails)
- '''
+ """
user = User.objects.get(pk=2)
uid, token = make_token(user)
@@ -51,9 +51,9 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 34000)
def export_pdf(self, fail=False):
- '''
+ """
Helper function to test exporting a nutritional plan as a pdf
- '''
+ """
# Get a plan
response = self.client.get(reverse('nutrition:plan:export-pdf',
@@ -94,26 +94,26 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):
self.assertLess(int(response['Content-Length']), 33420)
def test_export_pdf_anonymous(self):
- '''
+ """
Tests exporting a nutritional plan as a pdf as an anonymous user
- '''
+ """
self.export_pdf(fail=True)
self.export_pdf_token()
def test_export_pdf_owner(self):
- '''
+ """
Tests exporting a nutritional plan as a pdf as the owner user
- '''
+ """
self.user_login('test')
self.export_pdf(fail=False)
self.export_pdf_token()
def test_export_pdf_other(self):
- '''
+ """
Tests exporting a nutritional plan as a pdf as a logged user not owning the data
- '''
+ """
self.user_login('admin')
self.export_pdf(fail=True)
diff --git a/wger/nutrition/tests/test_plan.py b/wger/nutrition/tests/test_plan.py
index be8da225e..b8617d3be 100644
--- a/wger/nutrition/tests/test_plan.py
+++ b/wger/nutrition/tests/test_plan.py
@@ -27,14 +27,14 @@ from wger.nutrition.models import NutritionPlan
class PlanRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
p = NutritionPlan.objects.get(pk=5)
self.assertEqual("{0}".format(p), 'Description 1')
@@ -44,9 +44,9 @@ class PlanRepresentationTestCase(WorkoutManagerTestCase):
class PlanShareButtonTestCase(WorkoutManagerTestCase):
- '''
+ """
Test that the share button is correctly displayed and hidden
- '''
+ """
def test_share_button(self):
plan = NutritionPlan.objects.get(pk=5)
@@ -65,14 +65,14 @@ class PlanShareButtonTestCase(WorkoutManagerTestCase):
class PlanAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Test accessing the workout page
- '''
+ """
def test_access_shared(self):
- '''
+ """
Test accessing the URL of a shared workout
- '''
+ """
plan = NutritionPlan.objects.get(pk=5)
self.user_login('admin')
@@ -88,9 +88,9 @@ class PlanAccessTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_access_not_shared(self):
- '''
+ """
Test accessing the URL of a private workout
- '''
+ """
plan = NutritionPlan.objects.get(pk=4)
self.user_login('admin')
@@ -107,9 +107,9 @@ class PlanAccessTestCase(WorkoutManagerTestCase):
class DeletePlanTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a nutritional plan
- '''
+ """
object_class = NutritionPlan
url = 'nutrition:plan:delete'
@@ -117,9 +117,9 @@ class DeletePlanTestCase(WorkoutManagerDeleteTestCase):
class EditPlanTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing an ingredient
- '''
+ """
object_class = NutritionPlan
url = 'nutrition:plan:edit'
@@ -128,13 +128,13 @@ class EditPlanTestCase(WorkoutManagerEditTestCase):
class PlanDailyCaloriesTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the handling of the daily calories in the plan page
- '''
+ """
def test_overview_no_calories(self):
- '''
+ """
Tests the overview page with no daily calories set
- '''
+ """
self.user_login('test')
@@ -146,9 +146,9 @@ class PlanDailyCaloriesTestCase(WorkoutManagerTestCase):
self.assertNotContains(response, 'goal amount of calories')
def test_overview_calories(self):
- '''
+ """
Tests the overview page with no daily calories set
- '''
+ """
# Plan has daily calories goal
self.user_login('test')
@@ -164,9 +164,9 @@ class PlanDailyCaloriesTestCase(WorkoutManagerTestCase):
class PlanApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the nutritional plan overview resource
- '''
+ """
pk = 4
resource = NutritionPlan
private_resource = True
diff --git a/wger/nutrition/tests/test_submitted_ingredient.py b/wger/nutrition/tests/test_submitted_ingredient.py
index 602c02893..5234079fe 100644
--- a/wger/nutrition/tests/test_submitted_ingredient.py
+++ b/wger/nutrition/tests/test_submitted_ingredient.py
@@ -22,14 +22,14 @@ from wger.nutrition.models import Ingredient
class IngredientsPendingTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the pending ingredients overview page
- '''
+ """
def pending_overview(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('nutrition:ingredient:pending'))
if not fail:
self.assertEqual(response.status_code, 200)
@@ -38,38 +38,38 @@ class IngredientsPendingTestCase(WorkoutManagerTestCase):
self.assertIn(response.status_code, (302, 403))
def test_pending_overview_admin(self):
- '''
+ """
Tests the pending exercises overview page as an admin user
- '''
+ """
self.user_login('admin')
self.pending_overview()
def test_pending_overview_user(self):
- '''
+ """
Tests the pending exercises overview page as a regular user
- '''
+ """
self.user_login('test')
self.pending_overview(fail=True)
def test_pending_overview_logged_out(self):
- '''
+ """
Tests the pending exercises overview page as a logged out user
- '''
+ """
self.pending_overview(fail=True)
class IngredientsPendingDetailTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the detail page of a pending ingredient
- '''
+ """
def pending_view(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
response = self.client.get(reverse('nutrition:ingredient:view', kwargs={'id': 7}))
self.assertContains(response, 'pending review')
@@ -84,38 +84,38 @@ class IngredientsPendingDetailTestCase(WorkoutManagerTestCase):
self.assertNotContains(response, 'Decline')
def test_pending_view_admin(self):
- '''
+ """
Tests the detail page of a pending exercise as an admin user
- '''
+ """
self.user_login('admin')
self.pending_view()
def test_pending_view_user(self):
- '''
+ """
Tests the detail page of a pending exercise as a regular user
- '''
+ """
self.user_login('test')
self.pending_view(fail=True)
def test_pending_view_logged_out(self):
- '''
+ """
Tests the detail page of a pending exercise as a logged out user
- '''
+ """
self.pending_view(fail=True)
class IngredientAcceptTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests accepting a user submitted ingredient
- '''
+ """
def accept(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
ingredient = Ingredient.objects.get(pk=7)
self.assertEqual(ingredient.status, Ingredient.STATUS_PENDING)
response = self.client.get(reverse('nutrition:ingredient:accept', kwargs={'pk': 7}))
@@ -132,38 +132,38 @@ class IngredientAcceptTestCase(WorkoutManagerTestCase):
self.assertEqual(len(mail.outbox), 0)
def test_accept_admin(self):
- '''
+ """
Tests accepting a user submitted ingredient as an admin user
- '''
+ """
self.user_login('admin')
self.accept(fail=False)
def test_accept_user(self):
- '''
+ """
Tests accepting a user submitted ingredient as a regular user
- '''
+ """
self.user_login('test')
self.accept(fail=True)
def test_accept_logged_out(self):
- '''
+ """
Tests accepting a user submitted ingredient as a logged out user
- '''
+ """
self.accept(fail=True)
class IngredientRejectTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests rejecting a user submitted ingredient
- '''
+ """
def reject(self, fail=False):
- '''
+ """
Helper function
- '''
+ """
ingredient = Ingredient.objects.get(pk=7)
self.assertEqual(ingredient.status, Ingredient.STATUS_PENDING)
response = self.client.get(reverse('nutrition:ingredient:decline', kwargs={'pk': 7}))
@@ -179,24 +179,24 @@ class IngredientRejectTestCase(WorkoutManagerTestCase):
self.assertEqual(ingredient.status, Ingredient.STATUS_PENDING)
def test_reject_admin(self):
- '''
+ """
Tests rejecting a user submitted ingredient as an admin user
- '''
+ """
self.user_login('admin')
self.reject()
def test_reject_user(self):
- '''
+ """
Tests rejecting a user submitted ingredient as a regular user
- '''
+ """
self.user_login('test')
self.reject(fail=True)
def test_reject_logged_out(self):
- '''
+ """
Tests rejecting a user submitted ingredient as a logged out user
- '''
+ """
self.reject(fail=True)
diff --git a/wger/nutrition/tests/test_weight_unit.py b/wger/nutrition/tests/test_weight_unit.py
index 73fea69be..c9077896a 100644
--- a/wger/nutrition/tests/test_weight_unit.py
+++ b/wger/nutrition/tests/test_weight_unit.py
@@ -29,21 +29,21 @@ from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE
class WeightUnitRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(WeightUnit.objects.get(pk=1)), 'Scheibe')
class AddWeightUnitTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new weight unit
- '''
+ """
object_class = WeightUnit
url = 'nutrition:weight_unit:add'
@@ -51,9 +51,9 @@ class AddWeightUnitTestCase(WorkoutManagerAddTestCase):
class DeleteWeightUnitTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a weight unit
- '''
+ """
object_class = WeightUnit
url = 'nutrition:weight_unit:delete'
@@ -61,9 +61,9 @@ class DeleteWeightUnitTestCase(WorkoutManagerDeleteTestCase):
class EditWeightUnitTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a weight unit
- '''
+ """
object_class = WeightUnit
url = 'nutrition:weight_unit:edit'
@@ -72,9 +72,9 @@ class EditWeightUnitTestCase(WorkoutManagerEditTestCase):
class WeightUnitOverviewTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the ingredient unit overview page
- '''
+ """
def test_overview(self):
@@ -112,9 +112,9 @@ class WeightUnitOverviewTestCase(WorkoutManagerTestCase):
class WeightUnitApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the weight unit overview resource
- '''
+ """
pk = 1
resource = WeightUnit
private_resource = False
diff --git a/wger/nutrition/tests/test_weight_unit_ingredient.py b/wger/nutrition/tests/test_weight_unit_ingredient.py
index bd324000e..45f9f1686 100644
--- a/wger/nutrition/tests/test_weight_unit_ingredient.py
+++ b/wger/nutrition/tests/test_weight_unit_ingredient.py
@@ -34,21 +34,21 @@ from wger.nutrition.models import (
class WeightUnitIngredientRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(IngredientWeightUnit.objects.get(pk=1)), 'Spoon (109g)')
class AddWeightUnitIngredientTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a new weight unit to an ingredient
- '''
+ """
object_class = IngredientWeightUnit
url = reverse_lazy('nutrition:unit_ingredient:add',
@@ -59,9 +59,9 @@ class AddWeightUnitIngredientTestCase(WorkoutManagerAddTestCase):
class DeleteWeightUnitIngredientTestCase(WorkoutManagerDeleteTestCase):
- '''
+ """
Tests deleting a weight unit from an ingredient
- '''
+ """
object_class = IngredientWeightUnit
url = 'nutrition:unit_ingredient:delete'
@@ -69,9 +69,9 @@ class DeleteWeightUnitIngredientTestCase(WorkoutManagerDeleteTestCase):
class EditWeightUnitTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a weight unit from an ingredient
- '''
+ """
object_class = IngredientWeightUnit
url = 'nutrition:unit_ingredient:edit'
@@ -82,14 +82,14 @@ class EditWeightUnitTestCase(WorkoutManagerEditTestCase):
class WeightUnitFormTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the form for the weight units
- '''
+ """
def test_add_weight_unit(self):
- '''
+ """
Tests the form in the add view
- '''
+ """
self.user_login('admin')
response = self.client.get(reverse('nutrition:unit_ingredient:add',
kwargs={'ingredient_pk': 1}))
@@ -102,9 +102,9 @@ class WeightUnitFormTestCase(WorkoutManagerTestCase):
self.assertIn(unit.name, choices)
def test_edit_weight_unit(self):
- '''
+ """
Tests that the form in the edit view only shows weight units in the user's language
- '''
+ """
self.user_login('admin')
response = self.client.get(reverse('nutrition:unit_ingredient:edit',
kwargs={'pk': 1}))
@@ -118,9 +118,9 @@ class WeightUnitFormTestCase(WorkoutManagerTestCase):
class WeightUnitToIngredientApiTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the weight unit to ingredient API resource
- '''
+ """
pk = 1
resource = IngredientWeightUnit
private_resource = False
diff --git a/wger/nutrition/views/bmi.py b/wger/nutrition/views/bmi.py
index df05dab20..58c2174c7 100644
--- a/wger/nutrition/views/bmi.py
+++ b/wger/nutrition/views/bmi.py
@@ -30,16 +30,16 @@ from wger.utils import helpers
logger = logging.getLogger(__name__)
-'''
+"""
BMI views
-'''
+"""
@login_required
def view(request):
- '''
+ """
The BMI calculator detail page
- '''
+ """
context = {}
form_data = {'height': request.user.userprofile.height,
@@ -50,9 +50,9 @@ def view(request):
@login_required
def calculate(request):
- '''
+ """
Calculates the BMI
- '''
+ """
data = []
@@ -74,13 +74,13 @@ def calculate(request):
def chart_data(request):
- '''
+ """
Returns the data to render the BMI chart
The individual values taken from
* http://apps.who.int/bmi/index.jsp?introPage=intro_3.html
* https://de.wikipedia.org/wiki/Body-Mass-Index
- '''
+ """
if request.user.userprofile.use_metric:
data = json.dumps([
diff --git a/wger/nutrition/views/calculator.py b/wger/nutrition/views/calculator.py
index 9377eb018..513d91d84 100644
--- a/wger/nutrition/views/calculator.py
+++ b/wger/nutrition/views/calculator.py
@@ -34,16 +34,16 @@ from wger.utils.helpers import ua_aware_render
logger = logging.getLogger(__name__)
-'''
+"""
Protein calculator views
-'''
+"""
@login_required
def view(request):
- '''
+ """
The basal metabolic rate detail page
- '''
+ """
form_data = {'age': request.user.userprofile.age,
'height': request.user.userprofile.height,
@@ -60,11 +60,11 @@ def view(request):
@login_required
def calculate_bmr(request):
- '''
+ """
Calculates the basal metabolic rate.
Currently only the Mifflin-St.Jeor-Formel is supported
- '''
+ """
data = []
@@ -87,9 +87,9 @@ def calculate_bmr(request):
@login_required
def calculate_activities(request):
- '''
+ """
Calculates the calories needed by additional physical activities
- '''
+ """
data = []
diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.py
index 4e2d07f24..ddabbad5c 100644
--- a/wger/nutrition/views/ingredient.py
+++ b/wger/nutrition/views/ingredient.py
@@ -69,30 +69,30 @@ logger = logging.getLogger(__name__)
# Ingredient functions
# ************************
class IngredientListView(UAAwareViewMixin, ListView):
- '''
+ """
Show an overview of all ingredients
- '''
+ """
model = Ingredient
template_name = 'ingredient/overview.html'
context_object_name = 'ingredients_list'
paginate_by = PAGINATION_OBJECTS_PER_PAGE
def get_queryset(self):
- '''
+ """
Filter the ingredients the user will see by its language
(the user can also want to see ingredients in English, in addition to his
native language, see load_ingredient_languages)
- '''
+ """
languages = load_ingredient_languages(self.request)
return (Ingredient.objects.filter(language__in=languages)
.filter(status=Ingredient.STATUS_ACCEPTED)
.only('id', 'name'))
def get_context_data(self, **kwargs):
- '''
+ """
Pass additional data to the template
- '''
+ """
context = super(IngredientListView, self).get_context_data(**kwargs)
context['show_shariff'] = True
return context
@@ -118,9 +118,9 @@ class IngredientDeleteView(WgerDeleteMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
DeleteView):
- '''
+ """
Generic view to delete an existing ingredient
- '''
+ """
model = Ingredient
fields = ('name',
@@ -149,9 +149,9 @@ class IngredientDeleteView(WgerDeleteMixin,
class IngredientMixin(WgerFormMixin):
- '''
+ """
Manually set the order of the fields
- '''
+ """
fields = ['name',
'energy',
@@ -167,27 +167,27 @@ class IngredientMixin(WgerFormMixin):
class IngredientEditView(IngredientMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
- '''
+ """
Generic view to update an existing ingredient
- '''
+ """
model = Ingredient
form_action_urlname = 'nutrition:ingredient:edit'
permission_required = 'nutrition.change_ingredient'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(IngredientEditView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
class IngredientCreateView(IngredientMixin, CreateView):
- '''
+ """
Generic view to add a new ingredient
- '''
+ """
model = Ingredient
title = ugettext_lazy('Add a new ingredient')
@@ -201,9 +201,9 @@ class IngredientCreateView(IngredientMixin, CreateView):
return super(IngredientCreateView, self).form_valid(form)
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Demo users can't submit ingredients
- '''
+ """
if request.user.userprofile.is_temporary:
return HttpResponseForbidden()
return super(IngredientCreateView, self).dispatch(request, *args, **kwargs)
@@ -211,9 +211,9 @@ class IngredientCreateView(IngredientMixin, CreateView):
class PendingIngredientListView(LoginRequiredMixin, PermissionRequiredMixin,
UAAwareViewMixin, ListView):
- '''
+ """
List all ingredients pending review
- '''
+ """
model = Ingredient
template_name = 'ingredient/pending.html'
@@ -221,18 +221,18 @@ class PendingIngredientListView(LoginRequiredMixin, PermissionRequiredMixin,
permission_required = 'nutrition.change_ingredient'
def get_queryset(self):
- '''
+ """
Only show ingredients pending review
- '''
+ """
return Ingredient.objects.filter(status=Ingredient.STATUS_PENDING) \
.order_by('-creation_date')
@permission_required('nutrition.add_ingredient')
def accept(request, pk):
- '''
+ """
Accepts a pending user submitted ingredient
- '''
+ """
ingredient = get_object_or_404(Ingredient, pk=pk)
ingredient.status = Ingredient.STATUS_ACCEPTED
ingredient.save()
@@ -244,9 +244,9 @@ def accept(request, pk):
@permission_required('nutrition.add_ingredient')
def decline(request, pk):
- '''
+ """
Declines and deletes a pending user submitted ingredient
- '''
+ """
ingredient = get_object_or_404(Ingredient, pk=pk)
ingredient.status = Ingredient.STATUS_DECLINED
ingredient.save()
diff --git a/wger/nutrition/views/meal.py b/wger/nutrition/views/meal.py
index 0f3fe499c..ee7201f72 100644
--- a/wger/nutrition/views/meal.py
+++ b/wger/nutrition/views/meal.py
@@ -47,9 +47,9 @@ logger = logging.getLogger(__name__)
# ************************
class MealCreateView(WgerFormMixin, CreateView):
- '''
+ """
Generic view to add a new meal to a nutrition plan
- '''
+ """
model = Meal
fields = '__all__'
@@ -75,9 +75,9 @@ class MealCreateView(WgerFormMixin, CreateView):
class MealEditView(WgerFormMixin, UpdateView):
- '''
+ """
Generic view to update an existing meal
- '''
+ """
model = Meal
fields = '__all__'
@@ -90,9 +90,9 @@ class MealEditView(WgerFormMixin, UpdateView):
@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)
diff --git a/wger/nutrition/views/meal_item.py b/wger/nutrition/views/meal_item.py
index 4e2f2da80..64d4d4e0c 100644
--- a/wger/nutrition/views/meal_item.py
+++ b/wger/nutrition/views/meal_item.py
@@ -45,9 +45,9 @@ logger = logging.getLogger(__name__)
@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)
@@ -62,18 +62,18 @@ def delete_meal_item(request, item_id):
class MealItemCreateView(WgerFormMixin, CreateView):
- '''
+ """
Generic view to create a new meal item
- '''
+ """
model = MealItem
form_class = MealItemForm
template_name = 'meal_item/edit.html'
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Check that the user owns the meal
- '''
+ """
meal = get_object_or_404(Meal, pk=kwargs['meal_id'])
if meal.plan.user == request.user:
self.meal = meal
@@ -85,9 +85,9 @@ class MealItemCreateView(WgerFormMixin, CreateView):
return reverse('nutrition:plan:view', kwargs={'id': self.meal.plan.id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(MealItemCreateView, self).get_context_data(**kwargs)
context['form_action'] = reverse('nutrition:meal_item:add',
kwargs={'meal_id': self.meal.id})
@@ -95,18 +95,18 @@ class MealItemCreateView(WgerFormMixin, CreateView):
return context
def form_valid(self, form):
- '''
+ """
Manually set the corresponding meal
- '''
+ """
form.instance.meal = self.meal
form.instance.order = 1
return super(MealItemCreateView, self).form_valid(form)
class MealItemEditView(WgerFormMixin, UpdateView):
- '''
+ """
Generic view to update an existing meal item
- '''
+ """
model = MealItem
form_class = MealItemForm
@@ -118,9 +118,9 @@ class MealItemEditView(WgerFormMixin, UpdateView):
return reverse('nutrition:plan:view', kwargs={'id': self.object.meal.plan.id})
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(MealItemEditView, self).get_context_data(**kwargs)
context['ingredient_searchfield'] = self.object.ingredient.name
return context
diff --git a/wger/nutrition/views/plan.py b/wger/nutrition/views/plan.py
index 27f19888c..5002fec1d 100644
--- a/wger/nutrition/views/plan.py
+++ b/wger/nutrition/views/plan.py
@@ -92,9 +92,9 @@ def overview(request):
@login_required
def add(request):
- '''
+ """
Add a new nutrition plan and redirect to its page
- '''
+ """
plan = NutritionPlan()
plan.user = request.user
@@ -105,9 +105,9 @@ def add(request):
class PlanDeleteView(WgerDeleteMixin, DeleteView):
- '''
+ """
Generic view to delete a nutritional plan
- '''
+ """
model = NutritionPlan
fields = ('description', 'has_goal_calories')
@@ -116,36 +116,36 @@ class PlanDeleteView(WgerDeleteMixin, DeleteView):
messages = ugettext_lazy('Successfully deleted')
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(PlanDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
return context
class PlanEditView(WgerFormMixin, UpdateView):
- '''
+ """
Generic view to update an existing nutritional plan
- '''
+ """
model = NutritionPlan
fields = ('description', 'has_goal_calories')
form_action_urlname = 'nutrition:plan:edit'
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(PlanEditView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
def view(request, id):
- '''
+ """
Show the nutrition plan with the given ID
- '''
+ """
template_data = {}
plan = get_object_or_404(NutritionPlan, pk=id)
@@ -183,9 +183,9 @@ def view(request, id):
@login_required
def copy(request, pk):
- '''
+ """
Copy the nutrition plan
- '''
+ """
plan = get_object_or_404(NutritionPlan, pk=pk, user=request.user)
@@ -217,13 +217,13 @@ def copy(request, pk):
def export_pdf(request, id, uidb64=None, token=None):
- '''
+ """
Generates a PDF with the contents of a nutrition plan
See also
* http://www.blog.pythonlibrary.org/2010/09/21/reportlab
* http://www.reportlab.com/apis/reportlab/dev/platypus.html
- '''
+ """
# Load the plan
if uidb64 is not None and token is not None:
@@ -386,12 +386,12 @@ def export_pdf(request, id, uidb64=None, token=None):
elements.append(Spacer(10 * cm, 0.5 * cm))
created = datetime.date.today().strftime("%d.%m.%Y")
url = reverse('nutrition:plan:view', kwargs={'id': plan.id})
- p = Paragraph('''<para align="left">
+ p = Paragraph("""<para align="left">
%(date)s -
<a href="%(url)s">%(url)s</a> -
%(created)s
%(version)s
- </para>''' %
+ </para>""" %
{'date': _("Created on the <b>%s</b>") % created,
'created': "wger Workout Manager",
'version': get_version(),
diff --git a/wger/nutrition/views/unit.py b/wger/nutrition/views/unit.py
index dc5c93530..24d44c61d 100644
--- a/wger/nutrition/views/unit.py
+++ b/wger/nutrition/views/unit.py
@@ -55,9 +55,9 @@ logger = logging.getLogger(__name__)
class WeightUnitListView(PermissionRequiredMixin, UAAwareViewMixin, ListView):
- '''
+ """
Generic view to list all weight units
- '''
+ """
model = WeightUnit
template_name = 'units/list.html'
@@ -66,9 +66,9 @@ class WeightUnitListView(PermissionRequiredMixin, UAAwareViewMixin, ListView):
permission_required = 'nutrition.add_ingredientweightunit'
def get_queryset(self):
- '''
+ """
Only show ingredient units in the current user's language
- '''
+ """
return WeightUnit.objects.filter(language=load_language())
@@ -76,9 +76,9 @@ class WeightUnitCreateView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
CreateView):
- '''
+ """
Generic view to add a new weight unit for ingredients
- '''
+ """
model = WeightUnit
fields = ['name']
@@ -98,9 +98,9 @@ class WeightUnitDeleteView(WgerDeleteMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
DeleteView):
- '''
+ """
Generic view to delete a weight unit
- '''
+ """
model = WeightUnit
fields = ['name']
@@ -110,9 +110,9 @@ class WeightUnitDeleteView(WgerDeleteMixin,
messages = ugettext_lazy('Successfully deleted')
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(WeightUnitDeleteView, self).get_context_data(**kwargs)
context['title'] = _(u'Delete {0}?').format(self.object)
return context
@@ -122,9 +122,9 @@ class WeightUnitUpdateView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
UpdateView):
- '''
+ """
Generic view to update an weight unit
- '''
+ """
model = WeightUnit
fields = ['name']
@@ -135,9 +135,9 @@ class WeightUnitUpdateView(WgerFormMixin,
return reverse('nutrition:weight_unit:list')
def get_context_data(self, **kwargs):
- '''
+ """
Send some additional data to the template
- '''
+ """
context = super(WeightUnitUpdateView, self).get_context_data(**kwargs)
context['title'] = _(u'Edit {0}').format(self.object)
return context
diff --git a/wger/nutrition/views/unit_ingredient.py b/wger/nutrition/views/unit_ingredient.py
index 801daa968..a20379197 100644
--- a/wger/nutrition/views/unit_ingredient.py
+++ b/wger/nutrition/views/unit_ingredient.py
@@ -60,9 +60,9 @@ class WeightUnitIngredientCreateView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
CreateView):
- '''
+ """
Generic view to add a new weight unit to ingredient entry
- '''
+ """
model = IngredientWeightUnit
title = ugettext_lazy('Add a new weight unit')
@@ -84,9 +84,9 @@ class WeightUnitIngredientCreateView(WgerFormMixin,
return super(WeightUnitIngredientCreateView, self).form_valid(form)
def get_form_class(self):
- '''
+ """
The form can only show units in the user's language
- '''
+ """
class IngredientWeightUnitForm(ModelForm):
unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language()))
@@ -102,9 +102,9 @@ class WeightUnitIngredientUpdateView(WgerFormMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
UpdateView):
- '''
+ """
Generic view to update an weight unit to ingredient entry
- '''
+ """
model = IngredientWeightUnit
title = ugettext_lazy('Edit a weight unit to ingredient connection')
@@ -115,9 +115,9 @@ class WeightUnitIngredientUpdateView(WgerFormMixin,
return reverse('nutrition:ingredient:view', kwargs={'id': self.object.ingredient.id})
def get_form_class(self):
- '''
+ """
The form can only show units in the user's language
- '''
+ """
class IngredientWeightUnitForm(ModelForm):
unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language()))
@@ -133,9 +133,9 @@ class WeightUnitIngredientDeleteView(WgerDeleteMixin,
LoginRequiredMixin,
PermissionRequiredMixin,
DeleteView):
- '''
+ """
Generic view to delete a weight unit to ingredient entry
- '''
+ """
model = IngredientWeightUnit
fields = ('unit', 'gram', 'amount')
diff --git a/wger/settings_global.py b/wger/settings_global.py
index 507b77e66..fab94995b 100644
--- a/wger/settings_global.py
+++ b/wger/settings_global.py
@@ -21,11 +21,11 @@ import re
import sys
-'''
+"""
This file contains the global settings that don't usually need to be changed.
For a full list of options, visit:
https://docs.djangoproject.com/en/dev/ref/settings/
-'''
+"""
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
diff --git a/wger/software/views.py b/wger/software/views.py
index 15c6c618f..62f79b1ba 100644
--- a/wger/software/views.py
+++ b/wger/software/views.py
@@ -28,9 +28,9 @@ logger = logging.getLogger(__name__)
def features(request):
- '''
+ """
Render the features page
- '''
+ """
context = {'allow_registration': settings.WGER_SETTINGS['ALLOW_REGISTRATION'],
'allow_guest_users': settings.WGER_SETTINGS['ALLOW_GUEST_USERS']}
diff --git a/wger/tasks.py b/wger/tasks.py
index d38bcff3e..d492ce218 100644
--- a/wger/tasks.py
+++ b/wger/tasks.py
@@ -59,9 +59,9 @@ logger = logging.getLogger(__name__)
'"--arg1 --arg2=value". Default: none'})
def start(context, address='localhost', port=8000, browser=False, settings_path=None,
extra_args=''):
- '''
+ """
Start the application using django's built in webserver
- '''
+ """
if browser:
start_browser("http://{0}:{1}".format(address, port))
@@ -91,9 +91,9 @@ def bootstrap(context,
port=8000,
browser=False,
start_server=True):
- '''
+ """
Performs all steps necessary to bootstrap the application
- '''
+ """
# Find url to wger
address, port = detect_listen_opts(address, port)
@@ -137,9 +137,9 @@ def bootstrap(context,
'key-length': 'Lenght of the generated secret key. Default: 50'})
def create_settings(context, settings_path=None, database_path=None, url=None,
database_type='sqlite3', key_length=50):
- '''
+ """
Creates a local settings file
- '''
+ """
if settings_path is None:
settings_path = get_user_config_path('wger', 'settings.py')
@@ -205,9 +205,9 @@ def create_settings(context, settings_path=None, database_path=None, url=None,
@task(help={'settings-path': 'Path to settings file (absolute path recommended). Leave empty for '
'default'})
def create_or_reset_admin(context, settings_path=None):
- '''
+ """
Creates an admin user or resets the password for an existing one
- '''
+ """
# Find the path to the settings and setup the django environment
setup_django_environment(settings_path)
@@ -230,9 +230,9 @@ def create_or_reset_admin(context, settings_path=None):
@task(help={'settings-path': 'Path to settings file (absolute path recommended). Leave empty for '
'default'})
def migrate_db(context, settings_path=None):
- '''
+ """
Run all database migrations
- '''
+ """
# Find the path to the settings and setup the django environment
setup_django_environment(settings_path)
@@ -243,9 +243,9 @@ def migrate_db(context, settings_path=None):
@task(help={'settings-path': 'Path to settings file (absolute path recommended). Leave empty for '
'default'})
def load_fixtures(context, settings_path=None):
- '''
+ """
Loads all fixtures
- '''
+ """
# Find the path to the settings and setup the django environment
setup_django_environment(settings_path)
@@ -296,9 +296,9 @@ def load_fixtures(context, settings_path=None):
@task
def config_location(context):
- '''
+ """
Returns the default location for the settings file and the data folder
- '''
+ """
print('Default locations:')
print('* settings: {0}'.format(get_user_config_path('wger', 'settings.py')))
print('* media folder: {0}'.format(get_user_data_path('wger', 'media')))
@@ -378,9 +378,9 @@ def detect_listen_opts(address, port):
def setup_django_environment(settings_path):
- '''
+ """
Setup the django environment
- '''
+ """
# Use default settings if the user didn't specify something else
if settings_path is None:
@@ -421,9 +421,9 @@ def database_exists():
def start_browser(url):
- '''
+ """
Start the web browser with the given URL
- '''
+ """
browser = webbrowser.get()
def function():
diff --git a/wger/utils/cache.py b/wger/utils/cache.py
index 13b926652..5816138b2 100644
--- a/wger/utils/cache.py
+++ b/wger/utils/cache.py
@@ -25,19 +25,19 @@ logger = logging.getLogger(__name__)
def get_template_cache_name(fragment_name='', *args):
- '''
+ """
Logic to calculate the cache key name when using django's template cache.
Code taken from django/templatetags/cache.py
- '''
+ """
key = u':'.join([str(arg) for arg in args])
key_name = hashlib.md5(force_bytes(key)).hexdigest()
return 'template.cache.{0}.{1}'.format(fragment_name, key_name)
def delete_template_fragment_cache(fragment_name='', *args):
- '''
+ """
Deletes a cache key created on the template with django's cache tag
- '''
+ """
cache.delete(get_template_cache_name(fragment_name, *args))
@@ -46,9 +46,9 @@ def reset_workout_canonical_form(workout_id):
def reset_workout_log(user_pk, year, month, day=None):
- '''
+ """
Resets the cached workout logs
- '''
+ """
log_hash = hash((user_pk, year, month))
cache.delete(cache_mapper.get_workout_log_list(log_hash))
@@ -58,9 +58,9 @@ def reset_workout_log(user_pk, year, month, day=None):
class CacheKeyMapper(object):
- '''
+ """
Simple class for mapping the cache keys of different objects
- '''
+ """
# Keys used by the cache
LANGUAGE_CACHE_KEY = 'language-{0}'
@@ -71,9 +71,9 @@ class CacheKeyMapper(object):
WORKOUT_LOG_LIST = 'workout-log-hash-{0}'
def get_pk(self, param):
- '''
+ """
Small helper function that returns the PK for the given parameter
- '''
+ """
try:
pk = param.pk
except AttributeError:
@@ -82,39 +82,39 @@ class CacheKeyMapper(object):
return pk
def get_exercise_muscle_bg_key(self, param):
- '''
+ """
Return the exercise muscle background cache key
- '''
+ """
return self.EXERCISE_CACHE_KEY_MUSCLE_BG.format(self.get_pk(param))
def get_language_key(self, param):
- '''
+ """
Return the language cache key
- '''
+ """
return self.LANGUAGE_CACHE_KEY.format(self.get_pk(param))
def get_language_config_key(self, param, item):
- '''
+ """
Return the language cache key
- '''
+ """
return self.LANGUAGE_CONFIG_CACHE_KEY.format(self.get_pk(param), item)
def get_ingredient_key(self, param):
- '''
+ """
Return the ingredient cache key
- '''
+ """
return self.INGREDIENT_CACHE_KEY.format(self.get_pk(param))
def get_workout_canonical(self, param):
- '''
+ """
Return the workout canonical representation
- '''
+ """
return self.WORKOUT_CANONICAL_REPRESENTATION.format(self.get_pk(param))
def get_workout_log_list(self, hash_value):
- '''
+ """
Return the workout canonical representation
- '''
+ """
return self.WORKOUT_LOG_LIST.format(hash_value)
diff --git a/wger/utils/context_processor.py b/wger/utils/context_processor.py
index 79e5ab56b..d9a8d8e4d 100644
--- a/wger/utils/context_processor.py
+++ b/wger/utils/context_processor.py
@@ -99,11 +99,11 @@ def processor(request):
def get_custom_header(request):
- '''
+ """
Loads the custom header for the application, if available
Currently the header can only be overwritten to use the user's current gym
- '''
+ """
# Current gym
current_gym = None
diff --git a/wger/utils/fields.py b/wger/utils/fields.py
index 0a90ebdc0..f4df2ee15 100644
--- a/wger/utils/fields.py
+++ b/wger/utils/fields.py
@@ -29,28 +29,28 @@ logger = logging.getLogger(__name__)
class Html5TimeField(models.TimeField):
- '''
+ """
Custom Time field that uses the Html5TimeInput widget
- '''
+ """
def formfield(self, **kwargs):
- '''
+ """
Use our custom field
- '''
+ """
defaults = {'form_class': Html5FormTimeField}
defaults.update(kwargs)
return super(Html5TimeField, self).formfield(**defaults)
class Html5DateField(models.DateField):
- '''
+ """
Custom Time field that uses the Html5DateInput widget
- '''
+ """
def formfield(self, **kwargs):
- '''
+ """
Use our custom field
- '''
+ """
defaults = {'form_class': Html5FormDateField}
defaults.update(kwargs)
return super(Html5DateField, self).formfield(**defaults)
diff --git a/wger/utils/generic_views.py b/wger/utils/generic_views.py
index 13eef4995..00f9bbbaa 100644
--- a/wger/utils/generic_views.py
+++ b/wger/utils/generic_views.py
@@ -50,10 +50,10 @@ logger = logging.getLogger(__name__)
class WgerMultiplePermissionRequiredMixin(PermissionRequiredMixin):
- '''
+ """
A PermissionRequiredMixin that checks that the user has at least one permission
instead of all of them.
- '''
+ """
def has_permission(self):
for permission in self.get_permission_required():
@@ -63,30 +63,30 @@ class WgerMultiplePermissionRequiredMixin(PermissionRequiredMixin):
class WgerPermissionMixin(object):
- '''
+ """
Custom permission mixim
This simply checks that the user has the given permissions to access a
resource and makes writing customized generic views easier.
- '''
+ """
permission_required = False
- '''
+ """
The name of the permission required to access this class.
This can be a string or a tuple, in the latter case having any of the permissions
listed is enough to access the resource
- '''
+ """
login_required = False
- '''
+ """
Set to True to restrict view to logged in users
- '''
+ """
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Check permissions and dispatch
- '''
+ """
if self.login_required or self.permission_required:
if not request.user.is_authenticated:
@@ -114,47 +114,47 @@ class WgerFormMixin(ModelFormMixin):
template_name = 'form.html'
custom_js = ''
- '''
+ """
Custom javascript to be executed.
- '''
+ """
form_action = ''
form_action_urlname = ''
sidebar = ''
- '''
+ """
Name of a template that will be included in the sidebar
- '''
+ """
title = ''
- '''
+ """
Title used in the form
- '''
+ """
owner_object = False
- '''
+ """
The object that holds the owner information. This only needs to be set if
the model doesn't provide a get_owner_object() method
- '''
+ """
submit_text = ugettext_lazy('Save')
- '''
+ """
Text used in the submit button, default _('save')
- '''
+ """
clean_html = ()
- '''
+ """
List of form fields that should be passed to bleach to clean the html
- '''
+ """
messages = ''
- '''
+ """
A message to display on sucess
- '''
+ """
def get_context_data(self, **kwargs):
- '''
+ """
Set necessary template data to correctly render the form
- '''
+ """
# Call the base implementation first to get a context
context = super(WgerFormMixin, self).get_context_data(**kwargs)
@@ -191,13 +191,13 @@ class WgerFormMixin(ModelFormMixin):
return context
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Custom dispatch method.
This basically only checks for ownerships of editable/deletable
objects and return a HttpResponseForbidden response if the user
is not the owner.
- '''
+ """
# These seem to be necessary for calling get_object
self.kwargs = kwargs
@@ -222,27 +222,27 @@ class WgerFormMixin(ModelFormMixin):
return super(WgerFormMixin, self).dispatch(request, *args, **kwargs)
def get_messages(self):
- '''
+ """
Getter for success message. Can be overwritten to e.g. to provide the
name of the object.
- '''
+ """
return self.messages
def form_invalid(self, form):
- '''
+ """
Log form errors to the console
- '''
+ """
logger.debug(form.errors)
return super(WgerFormMixin, self).form_invalid(form)
def form_valid(self, form):
- '''
+ """
Pre-process the form, cleaning up the HTML code found in the fields
given in clean_html. All HTML tags, attributes and styles not in the
whitelists are stripped from the output, leaving only the text content:
<table><tr><td>foo</td></tr></table> simply becomes 'foo'
- '''
+ """
for field in self.clean_html:
setattr(form.instance, field, bleach.clean(getattr(form.instance, field),
@@ -266,9 +266,9 @@ class WgerDeleteMixin(ModelFormMixin):
messages = ''
def get_context_data(self, **kwargs):
- '''
+ """
Set necessary template data to correctly render the form
- '''
+ """
# Call the base implementation first to get a context
context = super(WgerDeleteMixin, self).get_context_data(**kwargs)
@@ -298,13 +298,13 @@ class WgerDeleteMixin(ModelFormMixin):
return context
def dispatch(self, request, *args, **kwargs):
- '''
+ """
Custom dispatch method.
This basically only checks for ownerships of editable/deletable
objects and return a HttpResponseForbidden response if the user
is not the owner.
- '''
+ """
# These seem to be necessary if for calling get_object
self.kwargs = kwargs
@@ -319,25 +319,25 @@ class WgerDeleteMixin(ModelFormMixin):
return super(WgerDeleteMixin, self).dispatch(request, *args, **kwargs)
def get_messages(self):
- '''
+ """
Getter for success message. Can be overwritten to e.g. to provide the
name of the object.
- '''
+ """
return self.messages
def delete(self, request, *args, **kwargs):
- '''
+ """
Show a message on successful delete
- '''
+ """
if self.get_messages():
messages.success(request, self.get_messages())
return super(WgerDeleteMixin, self).delete(request, *args, **kwargs)
class TextTemplateView(TemplateView):
- '''
+ """
A regular templateView that sets the mime type as text/plain
- '''
+ """
def dispatch(self, request, *args, **kwargs):
resp = super().dispatch(request, args, kwargs)
resp['Content-Type'] = 'text/plain'
@@ -345,11 +345,11 @@ class TextTemplateView(TemplateView):
class WebappManifestView(TemplateView):
- '''
+ """
A regular templateView that sets the mime type as application/x-web-app-manifest+json
This is used in the mozilla market place
- '''
+ """
template_name = 'manifest.webapp'
def dispatch(request, *args, **kwargs):
diff --git a/wger/utils/helpers.py b/wger/utils/helpers.py
index fdfc3e497..32db5d326 100644
--- a/wger/utils/helpers.py
+++ b/wger/utils/helpers.py
@@ -65,13 +65,13 @@ class EmailAuthBackend(object):
class DecimalJsonEncoder(json.JSONEncoder):
- '''
+ """
Custom JSON encoder.
This class is needed because we store some data as a decimal (e.g. the
individual weight entries in the workout log) and they need to be
processed, json.dumps() doesn't work on them
- '''
+ """
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return str(obj)
@@ -81,11 +81,11 @@ class DecimalJsonEncoder(json.JSONEncoder):
def disable_for_loaddata(signal_handler):
- '''
+ """
Decorator to prevent clashes when loading data with loaddata and
post_connect signals. See also:
http://stackoverflow.com/questions/3499791/how-do-i-prevent-fixtures-from-conflicting
- '''
+ """
@wraps(signal_handler)
def wrapper(*args, **kwargs):
if kwargs['raw']:
@@ -96,7 +96,7 @@ def disable_for_loaddata(signal_handler):
def next_weekday(date, weekday):
- '''
+ """
Helper function to find the next weekday after a given date,
e.g. the first Monday after the 2013-12-05
@@ -108,7 +108,7 @@ def next_weekday(date, weekday):
:type date: datetime.date
:type weekday int
:return: datetime.date
- '''
+ """
days_ahead = weekday - date.weekday()
if days_ahead <= 0:
days_ahead += 7
@@ -116,20 +116,20 @@ def next_weekday(date, weekday):
def make_uid(input):
- '''
+ """
Small wrapper to generate a UID, usually used in URLs to allow for
anonymous access
- '''
+ """
return urlsafe_base64_encode(force_bytes(input))
def make_token(user):
- '''
+ """
Convenience function that generates the UID and token for a user
:param user: a user object
:return: the uid and the token
- '''
+ """
uid = make_uid(user.pk)
token = default_token_generator.make_token(user)
@@ -137,13 +137,13 @@ def make_token(user):
def check_token(uidb64, token):
- '''
+ """
Checks that the user token is correct.
:param uidb:
:param token:
:return: True on success, False in all other situations
- '''
+ """
if uidb64 is not None and token is not None:
try:
uid = int(urlsafe_base64_decode(uidb64))
@@ -159,13 +159,13 @@ def check_token(uidb64, token):
def password_generator(length=15):
- '''
+ """
A simple password generator
Also removes some 'problematic' characters like O and 0
:param length: the length of the password
:return: the generated password
- '''
+ """
chars = string.ascii_letters + string.digits
random.seed = (os.urandom(1024))
for char in ('I', '1', 'l', 'O', '0', 'o'):
@@ -175,7 +175,7 @@ def password_generator(length=15):
def check_access(request_user, username=None):
- '''
+ """
Small helper function to check that the current (possibly unauthenticated)
user can access a URL that the owner user shared the link.
@@ -184,7 +184,7 @@ def check_access(request_user, username=None):
:param request_user: the user in the current request
:param username: the username
:return: a tuple: (is_owner, user)
- '''
+ """
if username:
user = get_object_or_404(User, username=username)
@@ -204,7 +204,7 @@ def check_access(request_user, username=None):
def normalize_decimal(d):
- '''
+ """
Normalizes a decimal input
This simply performs a more "human" normalization, since python's decimal
@@ -213,7 +213,7 @@ def normalize_decimal(d):
:param d: decimal to convert
:return: normalized decimal
- '''
+ """
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
@@ -223,7 +223,7 @@ def normalize_decimal(d):
def smart_capitalize(input):
- '''
+ """
A "smart" capitalizer
This is used to capitalize e.g. exercise names. This is different than python's
@@ -234,7 +234,7 @@ def smart_capitalize(input):
:param input: the input string
:return: the capitalized string
- '''
+ """
out = []
for word in input.split(' '):
if len(word) > 2 and word[0] != u'ß':
diff --git a/wger/utils/language.py b/wger/utils/language.py
index ccb790915..86b2fd7a0 100644
--- a/wger/utils/language.py
+++ b/wger/utils/language.py
@@ -35,9 +35,9 @@ logger = logging.getLogger(__name__)
def load_language(language_code=None):
- '''
+ """
Returns the currently used language, e.g. to load appropriate exercises
- '''
+ """
# TODO: perhaps store a language preference in the user's profile?
@@ -62,9 +62,9 @@ def load_language(language_code=None):
def load_item_languages(item, language_code=None):
- '''
+ """
Returns the languages for a data type (exercises, ingredients)
- '''
+ """
language = load_language(language_code)
languages = cache.get(cache_mapper.get_language_config_key(language, item))
@@ -87,7 +87,7 @@ def load_item_languages(item, language_code=None):
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
@@ -96,7 +96,7 @@ def load_ingredient_languages(request):
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 = load_item_languages(LanguageConfig.SHOW_ITEM_INGREDIENTS)
diff --git a/wger/utils/managers.py b/wger/utils/managers.py
index 77458f1c6..f70717b7e 100644
--- a/wger/utils/managers.py
+++ b/wger/utils/managers.py
@@ -21,9 +21,9 @@ from django.db.models.query import QuerySet
from wger.utils.models import AbstractSubmissionModel
-'''
+"""
Custom managers and querysets
-'''
+"""
# TODO: starting with django 1.7 this is simplified, see
# https://docs.djangoproject.com/en/1.7/topics/db/managers/#creating-manager-with-queryset-methods
diff --git a/wger/utils/middleware.py b/wger/utils/middleware.py
index 6afb73c59..3f185b1c9 100644
--- a/wger/utils/middleware.py
+++ b/wger/utils/middleware.py
@@ -12,9 +12,9 @@
#
# You should have received a copy of the GNU Affero General Public License
-'''
+"""
Custom middleware
-'''
+"""
# Standard Library
import logging
@@ -37,10 +37,10 @@ SPECIAL_PATHS = ('dashboard',)
def check_current_request(request):
- '''
+ """
Simple helper function that checks whether the current request hit one
of the 'special' paths (paths that need a logged in user).
- '''
+ """
# Don't create guest users for requests that are accessing the site
# through the REST API
@@ -79,11 +79,11 @@ def get_user(request):
class WgerAuthenticationMiddleware(MiddlewareMixin):
- '''
+ """
Small wrapper around django's own AuthenticationMiddleware. Simply creates
a new user with a temporary flag if the user hits certain URLs that need
a logged in user
- '''
+ """
def process_request(self, request):
assert hasattr(request, 'session'), "The Django authentication middleware requires "
"session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert"
@@ -93,10 +93,10 @@ class WgerAuthenticationMiddleware(MiddlewareMixin):
class RobotsExclusionMiddleware(MiddlewareMixin):
- '''
+ """
Simple middleware that sends the "X-Robots-Tag" tag for the URLs used in
our WgerAuthenticationMiddleware so that those pages are not indexed.
- '''
+ """
def process_response(self, request, response):
# Don't set it if it's already in the response
if check_current_request(request) and response.get('X-Robots-Tag', None) is None:
@@ -105,7 +105,7 @@ class RobotsExclusionMiddleware(MiddlewareMixin):
class JavascriptAJAXRedirectionMiddleware(MiddlewareMixin):
- '''
+ """
Middleware that sends helper headers when working with AJAX.
This is used for AJAX forms due to limitations of javascript. The way it
@@ -113,7 +113,7 @@ class JavascriptAJAXRedirectionMiddleware(MiddlewareMixin):
in the page and redirect to that URL. This now just sends a header when the
form was called via the JS function wgerFormModalDialog() and no errors are
present.
- '''
+ """
def process_response(self, request, response):
diff --git a/wger/utils/models.py b/wger/utils/models.py
index 61fa1c2d1..196426af6 100644
--- a/wger/utils/models.py
+++ b/wger/utils/models.py
@@ -22,15 +22,15 @@ from django.utils.translation import ugettext_lazy as _
from wger.core.models import License
-'''
+"""
Abstract model classes
-'''
+"""
class AbstractLicenseModel(models.Model):
- '''
+ """
Abstract class that adds license information to a model
- '''
+ """
class Meta:
abstract = True
@@ -39,7 +39,7 @@ class AbstractLicenseModel(models.Model):
verbose_name=_('License'),
default=2,
on_delete=models.CASCADE)
- '''The item's license'''
+ """The item's license"""
license_author = models.CharField(verbose_name=_('Author'),
max_length=50,
@@ -48,17 +48,17 @@ class AbstractLicenseModel(models.Model):
help_text=_('If you are not the author, enter the name or '
'source here. This is needed for some licenses '
'e.g. the CC-BY-SA.'))
- '''The author if it is not the uploader'''
+ """The author if it is not the uploader"""
class AbstractSubmissionModel(models.Model):
- '''
+ """
Abstract class used for model for user submitted data.
These models have to be approved first by an administrator before they are
shows in the website. There is also a manager that can be used:
utils.managers.SubmissionManager
- '''
+ """
class Meta:
abstract = True
@@ -77,4 +77,4 @@ class AbstractSubmissionModel(models.Model):
choices=STATUS,
default=STATUS_PENDING,
editable=False)
- '''Status of the submission, e.g. accepted or declined'''
+ """Status of the submission, e.g. accepted or declined"""
diff --git a/wger/utils/pdf.py b/wger/utils/pdf.py
index 39a3c28c3..79a450234 100644
--- a/wger/utils/pdf.py
+++ b/wger/utils/pdf.py
@@ -41,9 +41,9 @@ from wger.core.models import Language
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'
@@ -60,7 +60,7 @@ def load_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
@@ -69,7 +69,7 @@ def load_ingredient_languages(request):
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,)
@@ -87,18 +87,18 @@ def load_ingredient_languages(request):
def render_footer(url, date=None):
- '''
+ """
Renders the footer used in the different PDFs
:return: a Paragraph object
- '''
+ """
if not date:
date = datetime.date.today().strftime("%d.%m.%Y")
- p = Paragraph('''<para>
+ p = Paragraph("""<para>
{date} -
<a href="{url}">{url}</a> -
wger Workout Manager
{version}
- </para>'''.format(date=date,
+ </para>""".format(date=date,
url=url,
version=get_version()),
styleSheet["Normal"])
diff --git a/wger/utils/permissions.py b/wger/utils/permissions.py
index 9d4ab95a4..1ed55eea9 100644
--- a/wger/utils/permissions.py
+++ b/wger/utils/permissions.py
@@ -20,30 +20,30 @@ from rest_framework import permissions
class WgerPermission(permissions.BasePermission):
- '''
+ """
Checks that the user has access to the object
If the object has a 'owner_object' method, only allow access for the owner
user. For the other objects (system wide objects like exercises, etc.) allow
only safe methods (GET, HEAD or OPTIONS)
- '''
+ """
def has_permission(self, request, view):
- '''
+ """
Access to public resources is allowed for all, for others, the user
has to be authenticated
The is_public flag is not present in all views, e.g. the special APIRoot
view. If it is not present, treat is as a public endpoint
- '''
+ """
if hasattr(view, 'is_private') and view.is_private:
return request.user and request.user.is_authenticated
return True
def has_object_permission(self, request, view, obj):
- '''
+ """
Perform the check
- '''
+ """
owner_object = obj.get_owner_object() if hasattr(obj, 'get_owner_object') else False
# Owner
@@ -59,12 +59,12 @@ class WgerPermission(permissions.BasePermission):
class CreateOnlyPermission(permissions.BasePermission):
- '''
+ """
Custom permission that permits read access the resource but limits the
write operations to creating (POSTing) new objects only and does not
allow allow editing them. This is currently used for exercises and their
images.
- '''
+ """
def has_permission(self, request, view):
return (request.method in ['GET', 'HEAD', 'OPTIONS'] or
@@ -74,10 +74,10 @@ class CreateOnlyPermission(permissions.BasePermission):
class UpdateOnlyPermission(permissions.BasePermission):
- '''
+ """
Custom permission that restricts write operations to PATCH. This is currently
used for the user profile.
- '''
+ """
def has_permission(self, request, view):
return (request.user and
diff --git a/wger/utils/resources.py b/wger/utils/resources.py
index 607677ae9..663bb2d6e 100644
--- a/wger/utils/resources.py
+++ b/wger/utils/resources.py
@@ -23,9 +23,9 @@ logger = logging.getLogger(__name__)
class UserObjectsOnlyAuthorization(ReadOnlyAuthorization):
- '''
+ """
Custom authorization class to limit the user's access to his own objects
- '''
+ """
def read_detail(self, object_list, bundle):
diff --git a/wger/utils/tests/test_capitalizer.py b/wger/utils/tests/test_capitalizer.py
index 2e5c5da6d..2472c51ab 100644
--- a/wger/utils/tests/test_capitalizer.py
+++ b/wger/utils/tests/test_capitalizer.py
@@ -21,14 +21,14 @@ from wger.utils.helpers import smart_capitalize
class CapitalizerTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the "intelligent" capitalizer
- '''
+ """
def test_capitalizer(self):
- '''
+ """
Tests different combinations of input strings
- '''
+ """
self.assertEqual(smart_capitalize("some long words"), "Some Long Words")
self.assertEqual(smart_capitalize("Here a short one"), "Here a Short One")
self.assertEqual(smart_capitalize("meine gym AG"), "Meine Gym AG")
diff --git a/wger/utils/tests/test_check_access.py b/wger/utils/tests/test_check_access.py
index 77c9bec1e..3bf2730a7 100644
--- a/wger/utils/tests/test_check_access.py
+++ b/wger/utils/tests/test_check_access.py
@@ -25,14 +25,14 @@ from wger.utils.helpers import check_access
class CheckAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the "check_access" helper function
- '''
+ """
def test_helper(self):
- '''
+ """
Test the helper function
- '''
+ """
user_share = User.objects.get(pk=1)
self.assertTrue(user_share.userprofile.ro_access)
diff --git a/wger/utils/tests/test_middleware.py b/wger/utils/tests/test_middleware.py
index 73c704f91..5129e578d 100644
--- a/wger/utils/tests/test_middleware.py
+++ b/wger/utils/tests/test_middleware.py
@@ -20,14 +20,14 @@ from wger.core.tests.base_testcase import WorkoutManagerTestCase
class RobotsExclusionMiddlewareTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the robots exclusion middleware
- '''
+ """
def test_middleware_manager(self):
- '''
+ """
Test the middleware on URLs from manager app
- '''
+ """
response = self.client.get(reverse('core:dashboard'))
self.assertTrue(response.get('X-Robots-Tag'))
@@ -48,18 +48,18 @@ class RobotsExclusionMiddlewareTestCase(WorkoutManagerTestCase):
self.assertFalse(response.get('X-Robots-Tag'))
def test_middleware_software(self):
- '''
+ """
Test the middleware on URLs from software app
- '''
+ """
for i in ('features', 'issues', 'license', 'code', 'contribute'):
response = self.client.get(reverse('software:{0}'.format(i)))
self.assertFalse(response.get('X-Robots-Tag'))
def test_middleware_nutrition(self):
- '''
+ """
Test the middleware on URLs from nutrition app
- '''
+ """
response = self.client.get(reverse('nutrition:ingredient:list'))
self.assertFalse(response.get('X-Robots-Tag'))
@@ -71,9 +71,9 @@ class RobotsExclusionMiddlewareTestCase(WorkoutManagerTestCase):
self.assertFalse(response.get('X-Robots-Tag'))
def test_middleware_exercises(self):
- '''
+ """
Test the middleware on URLs from exercises app
- '''
+ """
response = self.client.get(reverse('exercise:exercise:overview'))
self.assertFalse(response.get('X-Robots-Tag'))
diff --git a/wger/utils/tests/test_unit_conversion.py b/wger/utils/tests/test_unit_conversion.py
index c0145d043..1d899184b 100644
--- a/wger/utils/tests/test_unit_conversion.py
+++ b/wger/utils/tests/test_unit_conversion.py
@@ -22,14 +22,14 @@ from wger.utils.units import AbstractWeight
class WeightConversionTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the abstract weight class
- '''
+ """
def test_conversion(self):
- '''
+ """
Test the weight conversion
- '''
+ """
tmp = AbstractWeight(10)
self.assertEqual(tmp.kg, 10)
@@ -52,9 +52,9 @@ class WeightConversionTestCase(WorkoutManagerTestCase):
self.assertEqual(tmp.kg, 80)
def test_conversion_subunits(self):
- '''
+ """
Test the weight conversion with "subunits" (grams, ounces)
- '''
+ """
tmp = AbstractWeight(100.1, 'g')
self.assertEqual(tmp.kg, Decimal(0.1001).quantize(FOURPLACES))
@@ -81,9 +81,9 @@ class WeightConversionTestCase(WorkoutManagerTestCase):
self.assertEqual(tmp.lb, 1)
def test_sum(self):
- '''
+ """
Tests adding two abstract weights
- '''
+ """
weight1 = AbstractWeight(80, 'kg')
weight2 = AbstractWeight(10, 'kg')
sum = weight1 + weight2
@@ -100,9 +100,9 @@ class WeightConversionTestCase(WorkoutManagerTestCase):
self.assertEqual(sum.lb, Decimal(90))
def test_subunits(self):
- '''
+ """
Test weight subunit calculations
- '''
+ """
tmp = AbstractWeight(10)
self.assertEqual(tmp.g, 10000)
diff --git a/wger/utils/tests/test_user_agents.py b/wger/utils/tests/test_user_agents.py
index e5dd3397a..b7398f0a4 100644
--- a/wger/utils/tests/test_user_agents.py
+++ b/wger/utils/tests/test_user_agents.py
@@ -19,14 +19,14 @@ from wger.utils import user_agents
class AmazonUserAgentTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the amazon WebApp user agent detector
- '''
+ """
def test_user_agent_3rd_generation(self):
- '''
+ """
Tests 3rd generation user agents
- '''
+ """
agent = "Mozilla/5.0 (Linux; Android 4.2.2; <device> Build/<build>) AppleWebKit/ "\
"<webkit> (KHTML, like Gecko) Chrome/<chrome> Mobile Safari/<safari> "\
@@ -34,9 +34,9 @@ class AmazonUserAgentTestCase(WorkoutManagerTestCase):
self.assertTrue(user_agents.is_amazon_webview(agent))
def test_user_agent_2nd_generation(self):
- '''
+ """
Tests 2nd generation user agents
- '''
+ """
agent = "Mozilla/5.0 (Linux; Android 4.0.3; <device> Build/<build>) AppleWebKit/<webkit>" \
"(KHTML, like Gecko) Chrome/<chrome> Mobile Safari/<safari> AmazonWebAppPlatform"\
@@ -44,9 +44,9 @@ class AmazonUserAgentTestCase(WorkoutManagerTestCase):
self.assertTrue(user_agents.is_amazon_webview(agent))
def test_user_agent_1st_generation(self):
- '''
+ """
Tests 1st generation user agents
- '''
+ """
agent = "Mozilla/5.0 (Linux; U; Android 2.3.4; <locale>; Kindle Fire Build/GINGERBREAD) "\
"AppleWebKit/<webkit> (KHTML, like Gecko) Version/4.0 Safari/<safari> "\
@@ -54,9 +54,9 @@ class AmazonUserAgentTestCase(WorkoutManagerTestCase):
self.assertTrue(user_agents.is_amazon_webview(agent))
def test_user_agent_generic_android(self):
- '''
+ """
Tests generic android, from amazon app store
- '''
+ """
agent = "Mozilla/5.0 (Linux; U; Android <version>; <locale>; Build/<build>) AppleWebKit/"\
"<webkit> (KHTML, like Gecko) Version/4.0 Safari/<safari> AmazonWebAppPlatform/"\
@@ -64,9 +64,9 @@ class AmazonUserAgentTestCase(WorkoutManagerTestCase):
self.assertTrue(user_agents.is_amazon_webview(agent))
def test_user_agent_firefox(self):
- '''
+ """
Tests vanilla firefox user agent
- '''
+ """
agent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0"
self.assertFalse(user_agents.is_amazon_webview(agent))
@@ -75,9 +75,9 @@ class AmazonUserAgentTestCase(WorkoutManagerTestCase):
self.assertFalse(user_agents.is_amazon_webview(agent))
def test_user_agent_chrome(self):
- '''
+ """
Tests vanilla chrome user agent
- '''
+ """
agent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"\
"Chrome/32.0.1667.0 Safari/537.36"
@@ -89,25 +89,25 @@ class AmazonUserAgentTestCase(WorkoutManagerTestCase):
class AndroidUserAgentTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests the android WebApp user agent detector
https://developers.google.com/chrome/mobile/docs/webview/overview
- '''
+ """
def test_user_agent_old_ua(self):
- '''
+ """
Tests the old webview user agent
- '''
+ """
agent = "Mozilla/5.0 (Linux; U; Android 4.1.1; en-gb; Build/KLP) AppleWebKit/534.30 "\
"(KHTML, like Gecko) Version/4.0 Safari/534.30 WgerAndroidWebApp"
self.assertTrue(user_agents.is_android_webview(agent))
def test_user_agent_new_ua(self):
- '''
+ """
Tests the old webview user agent
- '''
+ """
agent = "Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/BuildID) AppleWebKit/537.36 "\
"(KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36 "\
@@ -115,9 +115,9 @@ class AndroidUserAgentTestCase(WorkoutManagerTestCase):
self.assertTrue(user_agents.is_android_webview(agent))
def test_user_agent_firefox(self):
- '''
+ """
Tests vanilla firefox user agent
- '''
+ """
agent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0"
self.assertFalse(user_agents.is_android_webview(agent))
@@ -126,9 +126,9 @@ class AndroidUserAgentTestCase(WorkoutManagerTestCase):
self.assertFalse(user_agents.is_android_webview(agent))
def test_user_agent_chrome(self):
- '''
+ """
Tests vanilla chrome user agent
- '''
+ """
agent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"\
"Chrome/32.0.1667.0 Safari/537.36"
diff --git a/wger/utils/units.py b/wger/utils/units.py
index e2f33afd4..01ec10d71 100644
--- a/wger/utils/units.py
+++ b/wger/utils/units.py
@@ -23,19 +23,19 @@ from wger.utils.constants import FOURPLACES
logger = logging.getLogger(__name__)
-'''
+"""
Weight unit classes
-'''
+"""
class AbstractWeight(object):
- '''
+ """
Helper class to use when working with sensible (kg) or imperial units.
Internally, all values are stored as kilograms and are converted only if
needed. For consistency, all results are converted to python decimal and
quantized to four places
- '''
+ """
KG_IN_LBS = Decimal(2.20462262)
LB_IN_KG = Decimal(0.45359237)
@@ -44,10 +44,10 @@ class AbstractWeight(object):
is_kg = True
def __init__(self, weight, mode='kg'):
- '''
+ """
:param weight: the numerical weight
:param mode: the mode, values 'kg' (default), 'g', 'lb' and 'oz' are supported
- '''
+ """
weight = self.normalize(weight)
if mode == 'g':
@@ -59,30 +59,30 @@ class AbstractWeight(object):
self.is_kg = mode in ('kg', 'g')
def __add__(self, other):
- '''
+ """
Implement adding abstract weights.
For simplicity, the sum always occurs in kg
- '''
+ """
return AbstractWeight(self.kg + other.kg)
@staticmethod
def normalize(value):
- '''
+ """
Helper method that returns quantized
:param value:
:return: a quantized value to four decimal places
- '''
+ """
return Decimal(value).quantize(FOURPLACES)
@property
def kg(self):
- '''
+ """
Return the weight in kilograms
:return: decimal
- '''
+ """
if self.is_kg:
return self.normalize(self.weight)
else:
@@ -90,20 +90,20 @@ class AbstractWeight(object):
@property
def g(self):
- '''
+ """
Return the weight in grams
:return: decimal
- '''
+ """
return self.normalize(self.kg * 1000)
@property
def lb(self):
- '''
+ """
Return the weight in pounds
:return: decimal
- '''
+ """
if self.is_kg:
return self.normalize(self.weight * self.KG_IN_LBS)
else:
@@ -111,9 +111,9 @@ class AbstractWeight(object):
@property
def oz(self):
- '''
+ """
Return the weight in ounces
:return: decimal
- '''
+ """
return self.normalize(self.lb * 16)
diff --git a/wger/utils/user_agents.py b/wger/utils/user_agents.py
index bbd54f59f..b902061fc 100644
--- a/wger/utils/user_agents.py
+++ b/wger/utils/user_agents.py
@@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)
def is_amazon_webview(user_agent):
- '''
+ """
Check if the client is an Amazon WebView.
See the amazon developer page for specific user agents:
@@ -28,7 +28,7 @@ def is_amazon_webview(user_agent):
:param user_agent A string with the user agent to check
:return boolean
- '''
+ """
if 'amazonwebapp' in user_agent.lower():
return True
else:
@@ -36,11 +36,11 @@ def is_amazon_webview(user_agent):
def check_request_amazon(request):
- '''
+ """
:param request:
:return: boolean
- '''
+ """
if request.META.get('HTTP_USER_AGENT'):
return is_amazon_webview(request.META.get('HTTP_USER_AGENT'))
else:
@@ -48,12 +48,12 @@ def check_request_amazon(request):
def is_android_webview(user_agent):
- '''
+ """
Check if the client is an Android WebView.
:param user_agent A string with the user agent to check
:return boolean
- '''
+ """
if 'wgerandroidwebapp' in user_agent.lower():
return True
else:
@@ -61,11 +61,11 @@ def is_android_webview(user_agent):
def check_request_android(request):
- '''
+ """
:param request:
:return: boolean
- '''
+ """
if request.META.get('HTTP_USER_AGENT'):
return is_android_webview(request.META.get('HTTP_USER_AGENT'))
else:
diff --git a/wger/utils/viewsets.py b/wger/utils/viewsets.py
index 6d005a980..07ab550ed 100644
--- a/wger/utils/viewsets.py
+++ b/wger/utils/viewsets.py
@@ -23,13 +23,13 @@ from rest_framework import (
class WgerOwnerObjectModelViewSet(viewsets.ModelViewSet):
- '''
+ """
Custom viewset that makes sure the user can only create objects for himself
- '''
+ """
def create(self, request, *args, **kwargs):
- '''
+ """
Check for creation (PUT, POST)
- '''
+ """
for entry in self.get_owner_objects():
if request.data.get(entry[1]):
pk = request.data.get(entry[1])
@@ -40,9 +40,9 @@ class WgerOwnerObjectModelViewSet(viewsets.ModelViewSet):
return super(WgerOwnerObjectModelViewSet, self).create(request, *args, **kwargs)
def update(self, request, *args, **kwargs):
- '''
+ """
Check for updates (PUT, PATCH)
- '''
+ """
for entry in self.get_owner_objects():
if request.data.get(entry[1]):
pk = request.data.get(entry[1])
diff --git a/wger/utils/widgets.py b/wger/utils/widgets.py
index 1f0064ed4..2418bebaf 100644
--- a/wger/utils/widgets.py
+++ b/wger/utils/widgets.py
@@ -47,35 +47,35 @@ logger = logging.getLogger(__name__)
#
class Html5DateInput(DateInput):
- '''
+ """
Custom Input class that is rendered with an HTML5 type="date"
This is specially useful in mobile devices
- '''
+ """
input_type = 'date'
class Html5FormDateField(fields.DateField):
- '''
+ """
HTML5 form date field
- '''
+ """
widget = Html5DateInput
class Html5TimeInput(TextInput):
- '''
+ """
Custom Input class that is rendered with an HTML5 type="time"
This is specially useful in mobile devices and not available
with older versions of django.
- '''
+ """
input_type = 'time'
class Html5FormTimeField(fields.TimeField):
- '''
+ """
HTML5 form time field
- '''
+ """
widget = Html5TimeInput
@@ -84,12 +84,12 @@ class Html5FormTimeField(fields.TimeField):
#
class Html5NumberInput(TextInput):
- '''
+ """
Custom Input class that is rendered with an HTML5 type="number"
This is specially useful in mobile devices and not available
with older versions of django.
- '''
+ """
input_type = 'number'
@@ -97,11 +97,11 @@ class Html5NumberInput(TextInput):
# Others
#
class ExerciseAjaxSelect(SelectMultiple):
- '''
+ """
Custom widget that allows to select exercises from an autocompleter
This is basically a modified MultipleSelect widget
- '''
+ """
def render(self, name, value, attrs=None, choices=(), renderer=None):
if value is None:
@@ -131,7 +131,7 @@ class ExerciseAjaxSelect(SelectMultiple):
option_value = force_text(option_value)
if option_value in selected_choices:
- return u'''
+ return u"""
<div id="a%(div_id)s" class="ajax-exercise-select">
<a href="#">
<img src="/static/images/icons/status-off.svg"
@@ -141,7 +141,7 @@ class ExerciseAjaxSelect(SelectMultiple):
</a> %(value)s
<input type="hidden" name="exercises" value="%(id)s">
</div>
- ''' % {'value': conditional_escape(force_text(option_label)),
+ """ % {'value': conditional_escape(force_text(option_label)),
'id': escape(option_value),
'div_id': uuid.uuid4()}
@@ -150,11 +150,11 @@ class ExerciseAjaxSelect(SelectMultiple):
class CheckboxChoiceInputTranslated(CheckboxInput):
- '''
+ """
Overwritten CheckboxInput
This only translated the text for the select widgets
- '''
+ """
input_type = 'checkbox'
def __init__(self, name, value, attrs, choice, index):
@@ -164,12 +164,12 @@ class CheckboxChoiceInputTranslated(CheckboxInput):
class CheckboxChoiceInputTranslatedOriginal(CheckboxInput):
- '''
+ """
Overwritten CheckboxInput
This only translated the text for the select widgets, showing the original
string as well.
- '''
+ """
input_type = 'checkbox'
def __init__(self, name, value, attrs, choice, index):
@@ -203,25 +203,25 @@ class BootstrapSelectMultipleTranslatedOriginal(CheckboxSelectMultiple):
class TranslatedSelectMultiple(BootstrapSelectMultiple):
- '''
+ """
A SelectMultiple widget that translates the options
- '''
+ """
pass
class TranslatedOriginalSelectMultiple(BootstrapSelectMultipleTranslatedOriginal):
- '''
+ """
A SelectMultiple widget that translates the options, showing the original
string as well. This is currently only used in the muscle list, where the
translated muscles as well as the latin names are shown.
- '''
+ """
pass
class TranslatedSelect(Select):
- '''
+ """
A Select widget that translates the options
- '''
+ """
def render_option(self, selected_choices, option_value, option_label):
return super(TranslatedSelect, self).render_option(selected_choices,
diff --git a/wger/weight/api/resources.py b/wger/weight/api/resources.py
index 836c3cea6..c89af539e 100644
--- a/wger/weight/api/resources.py
+++ b/wger/weight/api/resources.py
@@ -25,14 +25,14 @@ from wger.weight.models import WeightEntry
class WeightEntryResource(ModelResource):
- '''
+ """
Resource for weight entries
- '''
+ """
def authorized_read_list(self, object_list, bundle):
- '''
+ """
Filter to own objects
- '''
+ """
return object_list.filter(user=bundle.request.user)
class Meta:
diff --git a/wger/weight/api/serializers.py b/wger/weight/api/serializers.py
index 635ddeff6..a99988c54 100644
--- a/wger/weight/api/serializers.py
+++ b/wger/weight/api/serializers.py
@@ -23,9 +23,9 @@ from wger.weight.models import WeightEntry
class WeightEntrySerializer(serializers.ModelSerializer):
- '''
+ """
Weight serializer
- '''
+ """
class Meta:
model = WeightEntry
diff --git a/wger/weight/api/views.py b/wger/weight/api/views.py
index 8f8f5b615..6f0e4cb24 100644
--- a/wger/weight/api/views.py
+++ b/wger/weight/api/views.py
@@ -24,9 +24,9 @@ from wger.weight.models import WeightEntry
class WeightEntryViewSet(viewsets.ModelViewSet):
- '''
+ """
API endpoint for nutrition plan objects
- '''
+ """
serializer_class = WeightEntrySerializer
is_private = True
ordering_fields = '__all__'
@@ -34,13 +34,13 @@ class WeightEntryViewSet(viewsets.ModelViewSet):
'weight')
def get_queryset(self):
- '''
+ """
Only allow access to appropriate objects
- '''
+ """
return WeightEntry.objects.filter(user=self.request.user)
def perform_create(self, serializer):
- '''
+ """
Set the owner
- '''
+ """
serializer.save(user=self.request.user)
diff --git a/wger/weight/forms.py b/wger/weight/forms.py
index 110ab7e15..b80faa723 100644
--- a/wger/weight/forms.py
+++ b/wger/weight/forms.py
@@ -41,9 +41,9 @@ CSV_DATE_FORMAT = (('%d.%m.%Y', 'DD.MM.YYYY (30.01.2012)'),
class WeightCsvImportForm(Form):
- '''
+ """
A helper form with only a textarea
- '''
+ """
csv_input = CharField(widget=Textarea, label=_('Input'))
date_format = forms.ChoiceField(choices=CSV_DATE_FORMAT, label=_('Date format'))
diff --git a/wger/weight/helpers.py b/wger/weight/helpers.py
index 81d99817d..5947d298e 100644
--- a/wger/weight/helpers.py
+++ b/wger/weight/helpers.py
@@ -91,7 +91,7 @@ def parse_weight_csv(request, cleaned_data):
def group_log_entries(user, year, month, day=None):
- '''
+ """
Processes and regroups a list of log entries so they can be more easily
used in the different calendar pages
@@ -101,7 +101,7 @@ def group_log_entries(user, year, month, day=None):
:param day: optional, day
:return: a dictionary with grouped logs by date and exercise
- '''
+ """
if day:
log_hash = hash((user.pk, year, month, day))
else:
@@ -156,10 +156,10 @@ def group_log_entries(user, year, month, day=None):
def process_log_entries(logs):
- '''
+ """
Processes and regroups a list of log entries so they can be rendered
and passed to the D3 library to render a chart
- '''
+ """
entry_log = OrderedDict()
entry_list = {}
@@ -207,12 +207,12 @@ def process_log_entries(logs):
def get_last_entries(user, amount=5):
- '''
+ """
Get the last weight entries as well as the difference to the last
This can be used e.g. to present a list where the last entries and
their changes are presented.
- '''
+ """
last_entries = WeightEntry.objects.filter(user=user).order_by('-date')[:5]
last_entries_details = []
diff --git a/wger/weight/management/commands/email-weight-reminder.py b/wger/weight/management/commands/email-weight-reminder.py
index 8877d5046..d668d529a 100644
--- a/wger/weight/management/commands/email-weight-reminder.py
+++ b/wger/weight/management/commands/email-weight-reminder.py
@@ -32,9 +32,9 @@ from wger.weight.models import WeightEntry
class Command(BaseCommand):
- '''
+ """
Helper admin command to send out email reminders
- '''
+ """
help = 'Send out automatic emails to remind the user to enter the weight'
@@ -62,12 +62,12 @@ class Command(BaseCommand):
@staticmethod
def send_email(user, last_entry, datediff):
- '''
+ """
Notify a user to input the weight entry
:type user User
:type last_entry Date
- '''
+ """
# Compose and send the email
translation.activate(user.userprofile.notification_language.short_name)
diff --git a/wger/weight/models.py b/wger/weight/models.py
index c35c10339..2a73ca1b8 100644
--- a/wger/weight/models.py
+++ b/wger/weight/models.py
@@ -26,9 +26,9 @@ from django.utils.translation import ugettext_lazy as _
class WeightEntry(models.Model):
- '''
+ """
Model for a weight point
- '''
+ """
date = models.DateField(verbose_name=_('Date'))
weight = models.DecimalField(verbose_name=_('Weight'),
max_digits=5,
@@ -37,7 +37,7 @@ class WeightEntry(models.Model):
user = models.ForeignKey(User,
verbose_name=_('User'),
on_delete=models.CASCADE)
- '''
+ """
The user the weight entry belongs to.
NOTE: this field is neither marked as editable false nor is it excluded in
@@ -45,25 +45,25 @@ class WeightEntry(models.Model):
and ugly to validate the uniqueness of unique_together fields and one field
is excluded from the form. This does not pose any security risk because the
value from the form is ignored and the request's user always used.
- '''
+ """
class Meta:
- '''
+ """
Metaclass to set some other properties
- '''
+ """
verbose_name = _('Weight entry')
ordering = ["date", ]
get_latest_by = "date"
unique_together = ("date", "user")
def __str__(self):
- '''
+ """
Return a more human-readable representation
- '''
+ """
return u"{0}: {1:.2f} kg".format(self.date, self.weight)
def get_owner_object(self):
- '''
+ """
Returns the object that has owner information
- '''
+ """
return self
diff --git a/wger/weight/tests/test_csv_export.py b/wger/weight/tests/test_csv_export.py
index 459aaf93b..ddbfff39c 100644
--- a/wger/weight/tests/test_csv_export.py
+++ b/wger/weight/tests/test_csv_export.py
@@ -26,14 +26,14 @@ logger = logging.getLogger(__name__)
class WeightCsvExportTestCase(WorkoutManagerTestCase):
- '''
+ """
Test case for the CSV export for weight entries
- '''
+ """
def export_csv(self):
- '''
+ """
Helper function to test the CSV export
- '''
+ """
response = self.client.get(reverse('weight:export-csv'))
self.assertEqual(response.status_code, 200)
@@ -44,9 +44,9 @@ class WeightCsvExportTestCase(WorkoutManagerTestCase):
self.assertLessEqual(len(response.content), 150)
def test_export_csv_logged_in(self):
- '''
+ """
Test the CSV export for weight entries by a logged in user
- '''
+ """
self.user_login('test')
self.export_csv()
diff --git a/wger/weight/tests/test_csv_import.py b/wger/weight/tests/test_csv_import.py
index bc74e919a..26ddce874 100644
--- a/wger/weight/tests/test_csv_import.py
+++ b/wger/weight/tests/test_csv_import.py
@@ -27,21 +27,21 @@ logger = logging.getLogger(__name__)
class WeightCsvImportTestCase(WorkoutManagerTestCase):
- '''
+ """
Test case for the CSV import for weight entries
- '''
+ """
def import_csv(self):
- '''
+ """
Helper function to test the CSV import
- '''
+ """
response = self.client.get(reverse('weight:import-csv'))
self.assertEqual(response.status_code, 200)
# Do a direct post request
# 1st step
count_before = WeightEntry.objects.count()
- csv_input = '''Datum Gewicht KJ
+ csv_input = """Datum Gewicht KJ
05.01.10 error here 111
22.01.aa 69,2 222
27.01.10 69,6 222
@@ -50,7 +50,7 @@ class WeightCsvImportTestCase(WorkoutManagerTestCase):
19.02.10 71 222
26.02.10 71,9 222
26.02.10 71,9 222
-19.03.10 72 222'''
+19.03.10 72 222"""
response = self.client.post(reverse('weight:import-csv'),
{'stage': 1,
'csv_input': csv_input,
@@ -74,9 +74,9 @@ class WeightCsvImportTestCase(WorkoutManagerTestCase):
self.assertGreater(count_after, count_before)
def test_import_csv_loged_in(self):
- '''
+ """
Test deleting a category by a logged in user
- '''
+ """
self.user_login('test')
self.import_csv()
diff --git a/wger/weight/tests/test_entry.py b/wger/weight/tests/test_entry.py
index 76a58a315..5101479e2 100644
--- a/wger/weight/tests/test_entry.py
+++ b/wger/weight/tests/test_entry.py
@@ -31,26 +31,26 @@ from wger.weight.models import WeightEntry
class MealRepresentationTestCase(WorkoutManagerTestCase):
- '''
+ """
Test the representation of a model
- '''
+ """
def test_representation(self):
- '''
+ """
Test that the representation of an object is correct
- '''
+ """
self.assertEqual("{0}".format(WeightEntry.objects.get(pk=1)), '2012-10-01: 77.00 kg')
class WeightEntryAccessTestCase(WorkoutManagerTestCase):
- '''
+ """
Test accessing the weight overview page
- '''
+ """
def test_access_shared(self):
- '''
+ """
Test accessing the URL of a shared weight overview
- '''
+ """
url = reverse('weight:overview', kwargs={'username': 'admin'})
self.user_login('admin')
@@ -66,9 +66,9 @@ class WeightEntryAccessTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
def test_access_not_shared(self):
- '''
+ """
Test accessing the URL of an unshared weight overview
- '''
+ """
url = reverse('weight:overview', kwargs={'username': 'test'})
self.user_login('admin')
@@ -85,9 +85,9 @@ class WeightEntryAccessTestCase(WorkoutManagerTestCase):
class AddWeightEntryTestCase(WorkoutManagerAddTestCase):
- '''
+ """
Tests adding a weight entry
- '''
+ """
object_class = WeightEntry
url = 'weight:add'
@@ -98,9 +98,9 @@ class AddWeightEntryTestCase(WorkoutManagerAddTestCase):
class EditWeightEntryTestCase(WorkoutManagerEditTestCase):
- '''
+ """
Tests editing a weight entry
- '''
+ """
object_class = WeightEntry
url = 'weight:edit'
@@ -113,9 +113,9 @@ class EditWeightEntryTestCase(WorkoutManagerEditTestCase):
class WeightEntryTestCase(api_base_test.ApiBaseResourceTestCase):
- '''
+ """
Tests the weight entry overview resource
- '''
+ """
pk = 3
resource = WeightEntry
private_resource = True
diff --git a/wger/weight/tests/test_overview.py b/wger/weight/tests/test_overview.py
index abb70fdc6..484871dbb 100644
--- a/wger/weight/tests/test_overview.py
+++ b/wger/weight/tests/test_overview.py
@@ -26,35 +26,35 @@ logger = logging.getLogger(__name__)
class WeightOverviewTestCase(WorkoutManagerTestCase):
- '''
+ """
Test case for the weight overview page
- '''
+ """
def weight_overview(self):
- '''
+ """
Helper function to test the weight overview page
- '''
+ """
response = self.client.get(reverse('weight:overview',
kwargs={'username': self.current_user}))
self.assertEqual(response.status_code, 200)
def test_weight_overview_loged_in(self):
- '''
+ """
Test the weight overview page by a logged in user
- '''
+ """
self.user_login('test')
self.weight_overview()
class WeightExportCsvTestCase(WorkoutManagerTestCase):
- '''
+ """
Tests exporting the saved weight entries as a CSV file
- '''
+ """
def csv_export(self):
- '''
+ """
Helper function to test exporting the saved weight entries as a CSV file
- '''
+ """
response = self.client.get(reverse('weight:export-csv'))
self.assertEqual(response.status_code, 200)
@@ -63,8 +63,8 @@ class WeightExportCsvTestCase(WorkoutManagerTestCase):
self.assertLessEqual(len(response.content), 150)
def test_csv_export_loged_in(self):
- '''
+ """
Test exporting the saved weight entries as a CSV file by a logged in user
- '''
+ """
self.user_login('test')
self.csv_export()
diff --git a/wger/weight/views.py b/wger/weight/views.py
index 4e5612c6e..f42bfc0f1 100644
--- a/wger/weight/views.py
+++ b/wger/weight/views.py
@@ -62,42 +62,42 @@ logger = logging.getLogger(__name__)
class WeightAddView(WgerFormMixin, CreateView):
- '''
+ """
Generic view to add a new weight entry
- '''
+ """
model = WeightEntry
form_class = WeightForm
title = ugettext_lazy('Add weight entry')
form_action = reverse_lazy('weight:add')
def get_initial(self):
- '''
+ """
Set the initial data for the form.
Read the comment on weight/models.py WeightEntry about why we need
to pass the user here.
- '''
+ """
return {'user': self.request.user,
'date': datetime.date.today()}
def form_valid(self, form):
- '''
+ """
Set the owner of the entry here
- '''
+ """
form.instance.user = self.request.user
return super(WeightAddView, self).form_valid(form)
def get_success_url(self):
- '''
+ """
Return to overview with username
- '''
+ """
return reverse('weight:overview', kwargs={'username': self.object.user.username})
class WeightUpdateView(WgerFormMixin, UpdateView):
- '''
+ """
Generic view to edit an existing weight entry
- '''
+ """
model = WeightEntry
form_class = WeightForm
@@ -109,17 +109,17 @@ class WeightUpdateView(WgerFormMixin, UpdateView):
return context
def get_success_url(self):
- '''
+ """
Return to overview with username
- '''
+ """
return reverse('weight:overview', kwargs={'username': self.object.user.username})
@login_required
def export_csv(request):
- '''
+ """
Exports the saved weight data as a CSV file
- '''
+ """
# Prepare the response headers
response = HttpResponse(content_type='text/csv')
@@ -140,13 +140,13 @@ def export_csv(request):
def overview(request, username=None):
- '''
+ """
Shows a plot with the weight data
More info about the D3 library can be found here:
* https://github.com/mbostock/d3
* http://d3js.org/
- '''
+ """
is_owner, user = check_access(request.user, username)
template_data = {}
@@ -177,9 +177,9 @@ def overview(request, username=None):
@api_view(['GET'])
def get_weight_data(request, username=None):
- '''
+ """
Process the data to pass it to the JS libraries to generate an SVG image
- '''
+ """
is_owner, user = check_access(request.user, username)
@@ -207,9 +207,9 @@ class WeightCsvImportFormPreview(FormPreview):
form_template = 'import_csv_form.html'
def get_context(self, request, form):
- '''
+ """
Context for template rendering.
- '''
+ """
return {'form': form,
'stage_field': self.unused_name('stage'),