Create the admin's body weight category, refuse client-made ones

See https://github.com/wger-project/react/pull/1311
This commit is contained in:
Roland Geider
2026-09-26 23:23:44 +02:00
parent 7fe6f2e889
commit 7f79d781e8
3 changed files with 39 additions and 1 deletions

View File

@@ -93,6 +93,10 @@ class CategorySerializer(serializers.ModelSerializer):
"""
if self.instance and metric_type != self.instance.metric_type:
raise serializers.ValidationError('The metric type of a category cannot be changed')
# The server creates the official category itself
if self.instance is None and metric_type == MetricType.BODY_WEIGHT:
raise serializers.ValidationError('The body weight category is managed by the server')
return metric_type
def validate_dynamic_type(self, dynamic_type):

View File

@@ -458,6 +458,27 @@ class OfficialCategoryTestCase(WgerTestCase):
self.assertEqual(category.metric_type, MetricType.BODY_WEIGHT)
self.assertEqual(category.unit, user.userprofile.weight_unit)
def test_create_body_weight_forbidden(self):
"""
Test that a body weight category cannot be created over the API, also
not by a user who has no official one
"""
Category.objects.filter(pk=self.official).delete()
response = self.client.post(
reverse('measurement-category-list'),
{'name': 'Weight', 'unit': 'kg', 'metric_type': MetricType.BODY_WEIGHT},
content_type='application/json',
)
self.assertEqual(response.status_code, 400)
self.assertIn('metric_type', response.data)
self.assertFalse(
Category.objects.filter(
user__username='test', metric_type=MetricType.BODY_WEIGHT
).exists()
)
def test_delete_official_forbidden(self):
"""
Test that the official category cannot be deleted over the API

View File

@@ -136,7 +136,7 @@ def load_fixtures(context, settings_path: str = None):
# Core
call_command('loaddata', 'languages.json')
call_command('loaddata', 'groups.json')
call_command('loaddata', 'users.json')
load_admin_fixture()
call_command('loaddata', 'licenses.json')
call_command('loaddata', 'setting_repetition_units.json')
call_command('loaddata', 'setting_weight_units.json')
@@ -270,8 +270,21 @@ def load_admin_fixture():
current_dir = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(current_dir, 'core', 'fixtures/')
# can't be imported in global scope as it already requires
# the settings module during import
# Django
from django.contrib.auth.models import User
# wger
from wger.measurements.models import Category
call_command('loaddata', path + 'users.json')
# loaddata skips the signal that gives every user the official body
# weight category
admin = User.objects.get(username='admin')
Category.get_or_create_body_weight(admin, unit=admin.userprofile.weight_unit)
class WgerConfig(Config):
"""