Maintenance will be performed on,,, and tomorrow, 2020/08/04, starting at approximately 9am PDT. It is expected to take around 15 minutes and there will be a short period of downtime towards the end of the maintenance window. Please direct any comments, questions or concerns to

Commit 9aa430c8 authored by Tanner Prestegard's avatar Tanner Prestegard Committed by GraceDB

api: add better validation to EventGraceidField

parent 752e89f5
from __future__ import absolute_import
import logging
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from events.models import Event
......@@ -11,10 +14,47 @@ logger = logging.getLogger(__name__)
class EventGraceidField(GenericField, serializers.RelatedField):
default_error_messages = {
'invalid': _('Event graceid must be a string.'),
'bad_graceid': _('Not a valid graceid.'),
trim_whitespace = True
to_repr = 'graceid'
lookup_field = 'id'
lookup_field = 'pk'
model = Event
queryset = Event.objects.all()
def _validate_graceid(self, data):
# data should be a string at this point
prefix = data[0]
suffix = data[1:]
if not prefix in 'GEHMT':'bad_graceid')
suffix = int(suffix)
except ValueError:'bad_graceid')
def to_internal_value(self, data):
# Add string validation
if not isinstance(data, six.string_types):'invalid')
value = six.text_type(data)
if self.trim_whitespace:
value = value.strip()
# Convert to uppercase (allows g1234 to work)
value = value.upper()
# Graceid validation
return super(EventGraceidField, self).to_internal_value(value)
def get_model_dict(self, data):
return {self.lookup_field: data[1:]}
def get_does_not_exist_error(self, graceid):
err_msg = "Event with graceid {graceid} does not exist.".format(
return err_msg
......@@ -121,10 +121,14 @@ class GenericField(fields.Field):
return self.model.objects.get(**model_dict)
except self.model.DoesNotExist:
error_msg = '{model} with {lf}={data} does not exist' \
.format(model=self.model.__name__, lf=model_dict.keys()[0],
raise exceptions.ValidationError(error_msg)
if hasattr(self, 'get_does_not_exist_error'):
err_msg = self.get_does_not_exist_error(data)
err_msg = '{model} with {lf}={data} does not exist'.format(
model=self.model.__name__, lf=model_dict.keys()[0],
raise exceptions.ValidationError(err_msg)
def get_model_dict(self, data):
return {self.lookup_field: data}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment