-
Notifications
You must be signed in to change notification settings - Fork 0
/
frontend_rich_text_field.py
53 lines (42 loc) · 1.28 KB
/
frontend_rich_text_field.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
from enum import Enum
import bleach
from django.db import models
class HTMLTags(Enum):
A = "a"
ABBR = "abbr"
ACRONYM = "acronym"
B = "b"
BLOCKQUOTE = "blockquote"
CODE = "code"
EM = "em"
Italic = "i"
LI = "li"
OL = "ol"
STRONG = "strong"
UL = "ul"
H1 = "h1"
H2 = "h2"
H3 = "h3"
H4 = "h4"
H5 = "h5"
H6 = "h6"
P = "p"
ALLOWED_TAGS = [HTMLTag.value for HTMLTag in HTMLTags]
class FrontendRichTextField(models.TextField):
"""Field that validates text with bleach to prevent XSS attacks."""
def __init__(self, *args, db_collation=None, **kwargs):
self.allowed_tags = kwargs.pop("allowed_tags", ALLOWED_TAGS)
super().__init__(*args, db_collation=db_collation, **kwargs)
def clean_value(self, value):
return bleach.clean(value, tags=self.allowed_tags)
# Update model on save method
def pre_save(self, model_instance, add):
value = getattr(model_instance, self.attname)
if value:
setattr(model_instance, self.attname, self.clean_value(value))
return value
# Update db and allow to clean on update method
def get_prep_value(self, value):
if value:
value = self.clean_value(value)
return super().get_prep_value(value)