@@ -28,10 +28,24 @@ def active(self):
28
28
return self .filter (is_active = True )
29
29
30
30
31
- CONTENT_FORMAT_CHOICES = (
32
- ("reST" , "reStructuredText" ),
33
- ("html" , "Raw HTML" ),
34
- )
31
+ class ContentFormat (models .TextChoices ):
32
+ REST = "reST" , "reStructuredText"
33
+ HTML = "html" , "Raw HTML"
34
+
35
+ @classmethod
36
+ def to_html (cls , fmt , source ):
37
+ """
38
+ Convert the given source from the given format to HTML
39
+ """
40
+ if not fmt or fmt == cls .HTML :
41
+ return source
42
+ if fmt == cls .REST :
43
+ return publish_parts (
44
+ source = source ,
45
+ writer_name = "html" ,
46
+ settings_overrides = BLOG_DOCUTILS_SETTINGS ,
47
+ )["fragment" ]
48
+ raise ValueError (f"Unsupported format { fmt } " )
35
49
36
50
37
51
class Entry (models .Model ):
@@ -52,7 +66,7 @@ class Entry(models.Model):
52
66
"publication date must be in the past."
53
67
),
54
68
)
55
- content_format = models .CharField (choices = CONTENT_FORMAT_CHOICES , max_length = 50 )
69
+ content_format = models .CharField (choices = ContentFormat . choices , max_length = 50 )
56
70
summary = models .TextField ()
57
71
summary_html = models .TextField ()
58
72
body = models .TextField ()
@@ -88,20 +102,8 @@ def is_published(self):
88
102
is_published .boolean = True
89
103
90
104
def save (self , * args , ** kwargs ):
91
- if self .content_format == "html" :
92
- self .summary_html = self .summary
93
- self .body_html = self .body
94
- elif self .content_format == "reST" :
95
- self .summary_html = publish_parts (
96
- source = self .summary ,
97
- writer_name = "html" ,
98
- settings_overrides = BLOG_DOCUTILS_SETTINGS ,
99
- )["fragment" ]
100
- self .body_html = publish_parts (
101
- source = self .body ,
102
- writer_name = "html" ,
103
- settings_overrides = BLOG_DOCUTILS_SETTINGS ,
104
- )["fragment" ]
105
+ self .summary_html = ContentFormat .to_html (self .content_format , self .summary )
106
+ self .body_html = ContentFormat .to_html (self .content_format , self .body )
105
107
super ().save (* args , ** kwargs )
106
108
self .invalidate_cached_entry ()
107
109
0 commit comments