patch userdetails without unnecessary double verification

This commit is contained in:
Jochen Saalfeld 2018-02-14 12:18:48 +01:00
parent 2a1b0a645a
commit d525f2d7d2
No known key found for this signature in database
GPG Key ID: 8ACD4E8264B67DF4

View File

@ -57,19 +57,23 @@ class UserFullSerializer(ModelSerializer):
def validate(self, data): def validate(self, data):
""" """
Checks that first_name or last_name is given. Generates the Checks if the given data is empty. Generates the
username if it is empty. username if it is empty.
""" """
if not (data.get('username') or data.get('first_name') or data.get('last_name')):
raise ValidationError({'detail': _('Username, given name and surname can not all be empty.')})
# Generate username. But only if it is not set and the serializer is not
# called in a PATCH context (partial_update).
try: try:
action = self.context['view'].action action = self.context['view'].action
except (KeyError, AttributeError): except (KeyError, AttributeError):
action = None action = None
# Check if we are in Patch context, if not, check if we have the mandatory fields
if action != 'partial_update':
if not (data.get('username') or data.get('first_name') or data.get('last_name')):
raise ValidationError({'detail': _('Username, given name and surname can not all be empty.')})
# Generate username. But only if it is not set and the serializer is not
# called in a PATCH context (partial_update).
if not data.get('username') and action != 'partial_update': if not data.get('username') and action != 'partial_update':
data['username'] = User.objects.generate_username( data['username'] = User.objects.generate_username(
data.get('first_name', ''), data.get('first_name', ''),