2016-09-18 02:29:00 +03:00
|
|
|
import binascii
|
|
|
|
|
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from django.forms import CharField, Field, MultipleChoiceField
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
|
|
|
|
from graphql_relay import from_global_id
|
|
|
|
|
|
|
|
|
|
|
|
class GlobalIDFormField(Field):
|
2018-07-20 02:51:33 +03:00
|
|
|
default_error_messages = {"invalid": _("Invalid ID specified.")}
|
2016-09-18 02:29:00 +03:00
|
|
|
|
|
|
|
def clean(self, value):
|
|
|
|
if not value and not self.required:
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
_type, _id = from_global_id(value)
|
|
|
|
except (TypeError, ValueError, UnicodeDecodeError, binascii.Error):
|
2018-07-20 02:51:33 +03:00
|
|
|
raise ValidationError(self.error_messages["invalid"])
|
2016-09-18 02:29:00 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
CharField().clean(_id)
|
|
|
|
CharField().clean(_type)
|
|
|
|
except ValidationError:
|
2018-07-20 02:51:33 +03:00
|
|
|
raise ValidationError(self.error_messages["invalid"])
|
2016-09-18 02:29:00 +03:00
|
|
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
class GlobalIDMultipleChoiceField(MultipleChoiceField):
|
|
|
|
default_error_messages = {
|
2018-07-20 02:51:33 +03:00
|
|
|
"invalid_choice": _("One of the specified IDs was invalid (%(value)s)."),
|
|
|
|
"invalid_list": _("Enter a list of values."),
|
2016-09-18 02:29:00 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
def valid_value(self, value):
|
|
|
|
# Clean will raise a validation error if there is a problem
|
|
|
|
GlobalIDFormField().clean(value)
|
|
|
|
return True
|