|
| 1 | +import regex |
1 | 2 | from rest_framework import serializers
|
2 |
| - |
| 3 | +from .models import CustomTag |
3 | 4 |
|
4 | 5 |
|
5 | 6 | class TagsSerializerField(serializers.ModelField):
|
6 | 7 |
|
7 | 8 | child = serializers.CharField()
|
| 9 | + |
8 | 10 | default_error_messages = {
|
9 |
| - 'not_a_list': ('Expected a list of tag names but got type "{input_type}".'), |
10 |
| - 'not_a_string': ('All list items must be type str.') |
| 11 | + 'not_a_list': ('Expected a list of tag names but got type {input_type}.'), |
| 12 | + 'not_a_string': ('All tags must be of type str.'), |
| 13 | + 'emoji or symbol': ('Emoji, pictograps, and symbols are not supported in tags.') |
11 | 14 | }
|
12 | 15 |
|
| 16 | + class Meta: |
| 17 | + model = CustomTag |
| 18 | + fields = ('name',) |
| 19 | + |
13 | 20 | def __init__(self, **kwargs):
|
14 | 21 | super(TagsSerializerField, self).__init__(**kwargs)
|
15 | 22 |
|
16 |
| - def to_internal_value(self, value): |
| 23 | + def validate(self, value): |
17 | 24 | if not value:
|
18 | 25 | value = []
|
19 | 26 |
|
20 | 27 | if not isinstance(value, list):
|
21 |
| - self.fail('not_a_list', input_type=type(value).__name__) |
| 28 | + raise serializers.ValidationError(self.fail('not_a_list', input_type=type(value).__name__)) |
22 | 29 |
|
23 | 30 | for tag in value:
|
24 | 31 | if not isinstance(tag, str):
|
25 |
| - self.fail('not_a_string') |
| 32 | + raise serializers.ValidationError(self.fail('not_a_string')) |
| 33 | + |
| 34 | + if self.unsupported_characters(tag): |
| 35 | + raise serializers.ValidationError(self.fail('emoji or symbol')) |
26 | 36 |
|
27 | 37 | self.child.run_validation(tag)
|
28 | 38 |
|
29 | 39 | return value
|
30 | 40 |
|
| 41 | + def unsupported_characters(self, tag): |
| 42 | + ''' |
| 43 | + Everything NOT a letter, whitespace or combining mark in any unicode language |
| 44 | + additionally, miscellaneous mathematical and general symbols are also not allowed. |
| 45 | + ''' |
| 46 | + |
| 47 | + disallowed_characters = regex.compile( |
| 48 | + u"([\p{InMiscellaneous_Mathematical_Symbols-A}" |
| 49 | + u"\p{InMiscellaneous_Mathematical_Symbols-B}\p{So}]+)" |
| 50 | + u"|([^\p{L}\p{M}\p{Z}\p{N}\p{P}]+)", |
| 51 | + regex.VERBOSE) |
| 52 | + |
| 53 | + return True if regex.search(disallowed_characters, tag) else False |
| 54 | + |
| 55 | + def to_internal_value(self, value): |
| 56 | + return self.validate(value) |
| 57 | + |
31 | 58 | def to_representation(self, instance):
|
32 | 59 |
|
33 | 60 | all_fields = instance.tags.all_fields()
|
|
0 commit comments