Skip to content

Commit

Permalink
replace .format() with f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
rolandgeider committed Jan 27, 2024
1 parent 2baa28f commit a434c73
Show file tree
Hide file tree
Showing 55 changed files with 119 additions and 161 deletions.
4 changes: 2 additions & 2 deletions wger/config/models/gym_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return 'Default gym {0}'.format(self.default_gym)
return f'Default gym {self.default_gym}'

def save(self, *args, **kwargs):
"""
Expand All @@ -83,6 +83,6 @@ def save(self, *args, **kwargs):
config.gym = self.default_gym
config.user = user
config.save()
logger.debug('Creating GymUserConfig for user {0}'.format(user.username))
logger.debug(f'Creating GymUserConfig for user {user.username}')

return super(GymConfig, self).save(*args, **kwargs)
2 changes: 1 addition & 1 deletion wger/core/management/commands/dummy-generator-users.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def handle(self, **options):
last_name = faker.last_name()

username = slugify(f"{first_name}, {last_name} - {str(uid).split('-')[1]}")
email = '{0}@example.com'.format(username)
email = f'{username}@example.com'
password = username

try:
Expand Down
9 changes: 3 additions & 6 deletions wger/core/views/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,7 @@ def trainer_login(request, user_pk):
# Changing is only allowed between the same gym
if request.user.userprofile.gym != user.userprofile.gym:
return HttpResponseNotFound(
'There are no users in gym "{}" with user ID "{}".'.format(
request.user.userprofile.gym,
user_pk,
)
f'There are no users in gym "{request.user.userprofile.gym}" with user ID "{user_pk}".'
)

# Check if we're switching back to our original account
Expand Down Expand Up @@ -565,7 +562,7 @@ def get_context_data(self, **kwargs):
request_user = self.request.user # type: User
same_gym_id = request_user.userprofile.gym_id == page_user.userprofile.gym_id
context['enable_login_button'] = request_user.has_perm('gym.gym_trainer') and same_gym_id
context['gym_name'] = request_user.userprofile.gym.name
context['gym_name'] = None # request_user.userprofile.gym.name
return context


Expand All @@ -585,7 +582,7 @@ def get_queryset(self):
out = {'admins': [], 'members': []}

for u in User.objects.select_related('usercache', 'userprofile__gym').all():
out['members'].append({'obj': u, 'last_log': u.usercache.last_activity})
out['members'].append({'obj': u, 'last_log': None}) # u.usercache.last_activity

return out

Expand Down
6 changes: 2 additions & 4 deletions wger/exercises/management/commands/read-exercise-cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,8 @@ def process_new_exercises(self, options):

for language in [l.short_name for l in languages]:
for column in columns:
name = '{0}:{1}'.format(language, column)
assert name in file_reader.fieldnames, '{0} not in {1}'.format(
name, file_reader.fieldnames
)
name = f'{language}:{column}'
assert name in file_reader.fieldnames, f'{name} not in {file_reader.fieldnames}'

default_license = License.objects.get(pk=CC_BY_SA_4_ID)

Expand Down
2 changes: 1 addition & 1 deletion wger/exercises/tests/test_categories.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual('{0}'.format(ExerciseCategory.objects.get(pk=1)), 'Category')
self.assertEqual(str(ExerciseCategory.objects.get(pk=1)), 'Category')


class CategoryOverviewTestCase(WgerAccessTestCase):
Expand Down
2 changes: 1 addition & 1 deletion wger/exercises/tests/test_equipment.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual('{0}'.format(Equipment.objects.get(pk=1)), 'Dumbbells')
self.assertEqual(str(Equipment.objects.get(pk=1)), 'Dumbbells')


class AddEquipmentTestCase(WgerAddTestCase):
Expand Down
2 changes: 1 addition & 1 deletion wger/exercises/tests/test_exercise_comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual('{0}'.format(ExerciseComment.objects.get(pk=1)), 'test 123')
self.assertEqual(str(ExerciseComment.objects.get(pk=1)), 'test 123')


class ExerciseCommentApiTestCase(ExerciseCrudApiTestCase):
Expand Down
2 changes: 1 addition & 1 deletion wger/exercises/tests/test_exercise_translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual('{0}'.format(Exercise.objects.get(pk=1)), 'An exercise')
self.assertEqual(str(Exercise.objects.get(pk=1)), 'An exercise')


class ExercisesTestCase(WgerTestCase):
Expand Down
2 changes: 1 addition & 1 deletion wger/exercises/tests/test_muscles.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual('{0}'.format(Muscle.objects.get(pk=1)), 'Anterior testoid')
self.assertEqual(str(Muscle.objects.get(pk=1)), 'Anterior testoid')

# Check image URL properties
self.assertIn('images/muscles/main/muscle-2.svg', Muscle.objects.get(pk=2).image_url_main)
Expand Down
6 changes: 1 addition & 5 deletions wger/gallery/models/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ def gallery_upload_dir(instance, filename):
"""
Returns the upload target for exercise images
"""
return 'gallery/{0}/{1}{2}'.format(
instance.user.id,
uuid.uuid4(),
pathlib.Path(filename).suffix,
)
return f'gallery/{instance.user.id}/{uuid.uuid4()}{pathlib.Path(filename).suffix}'


class Image(models.Model):
Expand Down
2 changes: 1 addition & 1 deletion wger/gym/management/commands/dummy-generator-gyms.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def handle(self, **options):
gym.name = name
gym_list.append(gym)

self.stdout.write(' - {0}'.format(gym.name))
self.stdout.write(f' - {gym.name}')

# Bulk-create the entries
Gym.objects.bulk_create(gym_list)
2 changes: 1 addition & 1 deletion wger/gym/management/commands/inactive-members.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def handle(self, **options):

for gym in Gym.objects.all():
if int(options['verbosity']) >= 2:
self.stdout.write("* Processing gym '{}' ".format(gym))
self.stdout.write(f"* Processing gym '{gym}' ")

user_list = []
trainer_list = []
Expand Down
6 changes: 3 additions & 3 deletions wger/gym/models/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return '{}'.format(self.name)
return self.name

def get_owner_object(self):
"""
Expand Down Expand Up @@ -118,7 +118,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return '{}'.format(self.name)
return self.name

def get_owner_object(self):
"""
Expand Down Expand Up @@ -314,7 +314,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return '#{}'.format(self.id)
return f'#{self.id}'

def get_absolute_url(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion wger/gym/models/gym_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return gettext('Configuration for {}'.format(self.gym.name))
return gettext(f'Configuration for {self.gym.name}')

def get_owner_object(self):
"""
Expand Down
10 changes: 3 additions & 7 deletions wger/gym/models/user_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@ 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(),
)
return f'gym/documents/{instance.member.userprofile.gym.id}/{instance.member.id}/{uuid.uuid4()}'


class UserDocument(m.Model):
Expand Down Expand Up @@ -107,9 +103,9 @@ def __str__(self):
Return a more human-readable representation
"""
if self.name != self.original_name:
return '{} ({})'.format(self.name, self.original_name)
return f'{self.name} ({self.original_name})'
else:
return '{}'.format(self.name)
return self.name

def get_owner_object(self):
"""
Expand Down
4 changes: 1 addition & 3 deletions wger/gym/tests/test_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ def export_csv(self, fail=True):
filename = 'User-data-gym-{gym}-{t.year}-{t.month:02d}-{t.day:02d}.csv'.format(
t=today, gym=gym.id
)
self.assertEqual(
response['Content-Disposition'], 'attachment; filename={0}'.format(filename)
)
self.assertEqual(response['Content-Disposition'], f'attachment; filename={filename}')
self.assertGreaterEqual(len(response.content), 1000)
self.assertLessEqual(len(response.content), 1300)

Expand Down
2 changes: 1 addition & 1 deletion wger/gym/tests/test_gym.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual('{0}'.format(Gym.objects.get(pk=1)), 'Test 123')
self.assertEqual(str(Gym.objects.get(pk=1)), 'Test 123')


class GymOverviewTest(WgerAccessTestCase):
Expand Down
4 changes: 1 addition & 3 deletions wger/gym/tests/test_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,7 @@ def new_user_data_export(self, fail=False):
self.assertEqual(response['Content-Type'], 'text/csv')
today = datetime.date.today()
filename = 'User-data-{t.year}-{t.month:02d}-{t.day:02d}-cletus.csv'.format(t=today)
self.assertEqual(
response['Content-Disposition'], 'attachment; filename={}'.format(filename)
)
self.assertEqual(response['Content-Disposition'], f'attachment; filename={filename}')
self.assertGreaterEqual(len(response.content), 90)
self.assertLessEqual(len(response.content), 120)

Expand Down
2 changes: 1 addition & 1 deletion wger/gym/views/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,6 @@ def users(request, gym_pk):
filename = 'User-data-gym-{gym}-{t.year}-{t.month:02d}-{t.day:02d}.csv'.format(
t=today, gym=gym.id
)
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
response['Content-Disposition'] = f'attachment; filename={filename}'
response['Content-Length'] = len(response.content)
return response
2 changes: 1 addition & 1 deletion wger/gym/views/gym.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def gym_new_user_info_export(request):
filename = 'User-data-{t.year}-{t.month:02d}-{t.day:02d}-{user}.csv'.format(
t=today, user=new_username
)
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
response['Content-Disposition'] = f'attachment; filename={filename}'
response['Content-Length'] = len(response.content)
return response

Expand Down
10 changes: 5 additions & 5 deletions wger/manager/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,13 +238,13 @@ def formatday(self, day, weekday):
formatted_date = date_obj.strftime('%Y-%m-%d')
body = []
body.append(
'<a href="{0}" '
'data-log="log-{1}" '
'class="btn btn-block {2} calendar-link">'.format(url, formatted_date, background_css)
f'<a href="{url}" '
f'data-log="log-{formatted_date}" '
f'class="btn btn-block {background_css} calendar-link">'
)
body.append(repr(day))
body.append('</a>')
return self.day_cell(cssclass, '{0}'.format(''.join(body)))
return self.day_cell(cssclass, ''.join(body))

def formatmonth(self, year, month):
"""
Expand All @@ -268,4 +268,4 @@ def day_cell(self, cssclass, body):
"""
Renders a day cell
"""
return '<td class="{0}" style="vertical-align: middle;">{1}</td>'.format(cssclass, body)
return f'<td class="{cssclass}" style="vertical-align: middle;">{body}</td>'
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def handle(self, **options):
start_date = datetime.date.today() - datetime.timedelta(days=random.randint(0, 100))
workout = Workout(
user=user,
name='Dummy workout - {0}'.format(uid[1]),
name=f'Dummy workout - {uid[1]}',
creation_date=start_date,
)
workout.save()
Expand All @@ -95,7 +95,7 @@ def handle(self, **options):

day = Day(
training=workout,
description='Dummy day - {0}'.format(uid[0]),
description=f'Dummy day - {uid[0]}',
)
day.save()
day.day.add(weekday)
Expand Down
6 changes: 3 additions & 3 deletions wger/manager/management/commands/email-reminders.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def handle(self, **options):

if datetime.timedelta(days=profile.workout_reminder) > delta:
if int(options['verbosity']) >= 3:
self.stdout.write("* Workout '{0}' overdue".format(current_workout))
self.stdout.write(f"* Workout '{current_workout}' overdue")
counter += 1

self.send_email(
Expand All @@ -86,14 +86,14 @@ def handle(self, **options):
if datetime.timedelta(days=profile.workout_reminder) > delta:
if int(options['verbosity']) >= 3:
self.stdout.write(
"* Workout '{0}' overdue - schedule".format(schedule_step.workout)
f"* Workout '{schedule_step.workout}' overdue - schedule"
)

counter += 1
self.send_email(profile.user, current_workout, delta)

if counter and int(options['verbosity']) >= 2:
self.stdout.write('Sent {0} email reminders'.format(counter))
self.stdout.write(f'Sent {counter} email reminders')

@staticmethod
def send_email(user, workout, delta):
Expand Down
2 changes: 1 addition & 1 deletion wger/manager/models/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return 'Log entry: {0} - {1} kg on {2}'.format(self.reps, self.weight, self.date)
return f'Log entry: {self.reps} - {self.weight} kg on {self.date}'

def get_owner_object(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion wger/manager/models/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return '{0} - {1}'.format(self.workout, self.date)
return f'{self.workout} - {self.date}'

class Meta:
"""
Expand Down
8 changes: 4 additions & 4 deletions wger/manager/models/set.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __str__(self):
"""
Return a more human-readable representation
"""
return 'Set-ID {0}'.format(self.id)
return f'Set-ID {self.id}'

def get_owner_object(self):
"""
Expand Down Expand Up @@ -174,7 +174,7 @@ def get_reps_reprentation(setting, rep_unit):
"Until Failure" unit
"""
if setting.repetition_unit_id != 2:
reps = '{0} {1}'.format(setting.reps, rep_unit).strip()
reps = f'{setting.reps} {rep_unit}'.strip()
else:
reps = '∞'
return reps
Expand Down Expand Up @@ -211,12 +211,12 @@ def get_setting_text(current_setting, multi=False):
weight_unit = settings[0].weight_unit.name
weight = normalize_weight(current_setting)
rir = get_rir_representation(current_setting)
out = '{0} × {1}'.format(self.sets, reps).strip() if not multi else reps
out = f'{self.sets} × {reps}'.strip() if not multi else reps
if weight:
rir_text = f', {rir}' if rir else ''
out += f' ({weight} {weight_unit}{rir_text})'
else:
out += ' ({0})'.format(rir) if rir else ''
out += f' ({rir})' if rir else ''

return out

Expand Down
2 changes: 1 addition & 1 deletion wger/manager/models/workout.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def __str__(self):
if self.name:
return self.name
else:
return '{0} ({1})'.format(_('Workout'), self.creation_date)
return f'{_("Workout")} ({self.creation_date})'

def clean(self):
if self.is_public and not self.is_template:
Expand Down
2 changes: 1 addition & 1 deletion wger/manager/tests/test_day.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual('{0}'.format(Day.objects.get(pk=1)), 'A day')
self.assertEqual(str(Day.objects.get(pk=1)), 'A day')


class AddWorkoutDayTestCase(WgerAddTestCase):
Expand Down
Loading

0 comments on commit a434c73

Please sign in to comment.