-
Notifications
You must be signed in to change notification settings - Fork 31
/
language_code.py
59 lines (44 loc) · 1.8 KB
/
language_code.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
need full model and form fields
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyleft: 2010-2016 by the django-tools team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from django import forms
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_tools import validators
class LanguageCodeFormField(forms.CharField):
"""
Language Code form field in Accept-Language header format (RFC 2616)
>>> LanguageCodeFormField().clean('en')
'en'
>>> LanguageCodeFormField().clean('en-GB')
'en-GB'
>>> try:
... LanguageCodeFormField().clean("this is wrong")
... except Exception as err:
... print(err.__class__.__name__, err)
ValidationError ['Enter a valid language code (Accept-Language header format, see RFC2616)']
>>> try:
... LanguageCodeFormField().clean(None)
... except Exception as err:
... print(err.__class__.__name__, err)
ValidationError ['This field is required.']
>>> LanguageCodeFormField(required=False).clean(None)
''
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.validators.append(validators.validate_language_code)
class LanguageCodeModelField(models.CharField):
"""
>>> LanguageCodeModelField(max_length=20).run_validators('en-GB')
>>> try:
... LanguageCodeModelField(max_length=20).run_validators("this is wrong")
... except Exception as err:
... print(err.__class__.__name__, err)
ValidationError ['Enter a valid language code (Accept-Language header format, see RFC2616)']
"""
default_validators = [validators.validate_language_code]
description = _("Language Code in Accept-Language header format defined in RFC 2616")