Skip to content

Commit

Permalink
Default to current user on timer POST (#134)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdubz committed Jun 19, 2020
1 parent d6c2b48 commit 4e5153d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
13 changes: 12 additions & 1 deletion api/serializers.py
Expand Up @@ -135,13 +135,24 @@ class TimerSerializer(CoreModelSerializer):
child = serializers.PrimaryKeyRelatedField(
allow_null=True, allow_empty=True, queryset=models.Child.objects.all(),
required=False)
user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
user = serializers.PrimaryKeyRelatedField(
allow_null=True, allow_empty=True, queryset=User.objects.all(),
required=False)

class Meta:
model = models.Timer
fields = ('id', 'child', 'name', 'start', 'end', 'duration', 'active',
'user')

def validate(self, attrs):
attrs = super(TimerSerializer, self).validate(attrs)

# Set user to current user if no value is provided.
if 'user' not in attrs or attrs['user'] is None:
attrs['user'] = self.context['request'].user

return attrs


class TummyTimeSerializer(CoreModelWithDurationSerializer):
class Meta(CoreModelWithDurationSerializer.Meta):
Expand Down
7 changes: 7 additions & 0 deletions api/tests.py
Expand Up @@ -368,6 +368,13 @@ def test_post(self):
obj = models.Timer.objects.get(pk=response.data['id'])
self.assertEqual(obj.name, data['name'])

def test_post_default_user(self):
user = User.objects.first()
response = self.client.post(self.endpoint)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
obj = models.Timer.objects.get(pk=response.data['id'])
self.assertEqual(obj.user, user)

def test_patch(self):
endpoint = '{}{}/'.format(self.endpoint, 1)
response = self.client.get(endpoint)
Expand Down

0 comments on commit 4e5153d

Please sign in to comment.