-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add format
argument to UUIDField
#2788
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -639,20 +639,37 @@ def __init__(self, **kwargs): | |
|
||
|
||
class UUIDField(Field): | ||
valid_formats = ('hex_verbose', 'hex', 'int', 'urn') | ||
|
||
default_error_messages = { | ||
'invalid': _('"{value}" is not a valid UUID.'), | ||
} | ||
|
||
def __init__(self, **kwargs): | ||
self.uuid_format = kwargs.pop('format', 'hex_verbose') | ||
if self.uuid_format not in self.valid_formats: | ||
raise ValueError( | ||
'Invalid format for uuid representation. ' | ||
'Must be one of "{0}"'.format('", "'.join(self.valid_formats)) | ||
) | ||
super(UUIDField, self).__init__(**kwargs) | ||
|
||
def to_internal_value(self, data): | ||
if not isinstance(data, uuid.UUID): | ||
try: | ||
return uuid.UUID(data) | ||
if isinstance(data, six.integer_types): | ||
return uuid.UUID(int=data) | ||
else: | ||
return uuid.UUID(hex=data) | ||
except (ValueError, TypeError): | ||
self.fail('invalid', value=data) | ||
return data | ||
|
||
def to_representation(self, value): | ||
return str(value) | ||
if self.uuid_format == 'hex_verbose': | ||
return str(value) | ||
else: | ||
return getattr(value, self.uuid_format) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are we always going to be handling the int case correctly here? Any cases where that can just be an int, rather than a UUID instance? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not entirely sure what potential problem you foresee here. Which |
||
|
||
|
||
# Number types... | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we have examples here?