1
1
import copy
2
+ import datetime
2
3
import logging
3
4
from collections import Counter
4
5
7
8
from rest_framework .exceptions import ValidationError
8
9
from rest_framework .fields import CharField , empty
9
10
10
- from zds .api .serializers import ZdSModelSerializer
11
11
from zds .tutorialv2 .api .view_models import ChildrenViewModel , ChildrenListViewModel , UpdateChildrenListViewModel
12
- from gettext import gettext as _
12
+ from django . utils . translation import ugettext as _
13
13
14
14
from zds .tutorialv2 .models .database import PublishableContent
15
15
from zds .tutorialv2 .utils import init_new_repo
16
16
from zds .utils .forms import TagValidator
17
+ from zds .utils .models import SubCategory
17
18
18
19
logger = logging .getLogger (__name__ )
19
20
@@ -26,6 +27,14 @@ def __init__(self, *, filter_function=None, **kwargs):
26
27
super ().__init__ (** kwargs )
27
28
self .filter_method = filter_function
28
29
30
+ def __deepcopy__ (self , memodict ):
31
+ args = []
32
+ kwargs = {
33
+ key : (copy .deepcopy (value ) if (key not in ('validators' , 'regex' , 'filter_function' )) else value )
34
+ for key , value in self ._kwargs .items ()
35
+ }
36
+ return self .__class__ (* args , ** kwargs )
37
+
29
38
def to_internal_value (self , data ):
30
39
if isinstance (data , (list , tuple )):
31
40
return super ().to_internal_value (',' .join (str (value ) for value in data ))
@@ -54,7 +63,7 @@ def decorated(*args, **kwargs):
54
63
try :
55
64
return func (* args , ** kwargs )
56
65
except exception1 :
57
- logger .warning ('Error translated fril %s to %s' , exception1 , exception2 (message ))
66
+ logger .warning ('Error translated from %s to %s' , exception1 , exception2 (message ))
58
67
raise exception2 (message )
59
68
return decorated
60
69
return wrapper
@@ -73,9 +82,6 @@ class ChildrenListSerializer(serializers.Serializer):
73
82
Serialize children list so that api can handle them
74
83
"""
75
84
76
- def update (self , instance , validated_data ):
77
- pass
78
-
79
85
extracts = serializers .ListField (child = ChildrenSerializer (), source = 'extracts' )
80
86
containers = serializers .ListField (child = ChildrenSerializer (), source = 'containers' )
81
87
extract_number = serializers .IntegerField (source = 'extracts.__len__' )
@@ -118,16 +124,21 @@ def is_valid(self, raise_exception=False):
118
124
self ._validated_data [field_name ] = value
119
125
if self ._validated_data .get ('extracts' , None ):
120
126
self ._validated_data ['extracts' ] = [ChildrenViewModel (** v ) for v in self ._validated_data ['extracts' ]]
127
+ has_error = self .validate_extracts_structure (has_error , messages )
121
128
if self .initial_data .get ('containers' , None ):
122
129
self ._validated_data ['containers' ] = [ChildrenViewModel (** v ) for v in self ._validated_data ['containers' ]]
123
- if not all (c .child_type .lower () == 'extract' for c in self ._validated_data .get ('extracts' , [])):
124
- has_error = True
125
- messages ['extracts' ] = _ ('un extrait est mal configuré' )
126
- if len (self ._validated_data ['extracts' ]) != len (set (e .title for e in self ._validated_data ['extracts' ])):
130
+ has_error = self .validate_container_structure (has_error , messages )
131
+ self ._validated_data ['conclusion' ] = self .initial_data .get ('conclusion' , '' )
132
+ if not self ._validated_data ['extracts' ] and not self ._validated_data ['containers' ]:
127
133
has_error = True
128
- titles = Counter (list (e .title for e in self ._validated_data ['extracts' ]))
129
- doubly = [key for key , v in titles .items () if v > 1 ]
130
- messages ['extracts' ] = _ ('Certains titres sont en double : {}' ).format (',' .join (doubly ))
134
+ messages ['extracts' ] = _ ('Le contenu semble vide.' )
135
+ if raise_exception and has_error :
136
+ self ._errors .update (messages )
137
+ raise ValidationError (self .errors )
138
+
139
+ return not has_error
140
+
141
+ def validate_container_structure (self , has_error , messages ):
131
142
if len (self ._validated_data ['containers' ]) != len (set (e .title for e in self ._validated_data ['containers' ])):
132
143
has_error = True
133
144
titles = Counter (list (e .title for e in self ._validated_data ['containers' ]))
@@ -137,15 +148,18 @@ def is_valid(self, raise_exception=False):
137
148
has_error = True
138
149
messages ['containers' ] = _ ('Un conteneur est mal configuré' )
139
150
self ._validated_data ['introduction' ] = self .initial_data .get ('introduction' , '' )
140
- self ._validated_data ['conclusion' ] = self .initial_data .get ('conclusion' , '' )
141
- if not self ._validated_data ['extracts' ] and not self ._validated_data ['containers' ]:
142
- has_error = True
143
- messages ['extracts' ] = _ ('Le contenu semble vide.' )
144
- if raise_exception and has_error :
145
- self ._errors .update (messages )
146
- raise ValidationError (self .errors )
151
+ return has_error
147
152
148
- return not has_error
153
+ def validate_extracts_structure (self , has_error , messages ):
154
+ if not all (c .child_type .lower () == 'extract' for c in self ._validated_data .get ('extracts' , [])):
155
+ has_error = True
156
+ messages ['extracts' ] = _ ('un extrait est mal configuré' )
157
+ if len (self ._validated_data ['extracts' ]) != len (set (e .title for e in self ._validated_data ['extracts' ])):
158
+ has_error = True
159
+ titles = Counter (list (e .title for e in self ._validated_data ['extracts' ]))
160
+ doubly = [key for key , v in titles .items () if v > 1 ]
161
+ messages ['extracts' ] = _ ('Certains titres sont en double : {}' ).format (',' .join (doubly ))
162
+ return has_error
149
163
150
164
def to_representation (self , instance ):
151
165
dic_repr = {}
@@ -176,7 +190,7 @@ class Meta:
176
190
'introduction' , 'conclusion' , 'original_sha' )
177
191
178
192
def is_valid (self , raise_exception = False ):
179
- error = not super (ChildrenListModifySerializer , self ).is_valid (raise_exception )
193
+ error = not super ().is_valid (raise_exception )
180
194
messages = {}
181
195
if not self ._validated_data ['original_sha' ]:
182
196
messages ['original_sha' ] = _ ("Vous n'avez pas fourni de marqueur de version" )
@@ -193,27 +207,32 @@ def create(self, validated_data):
193
207
return UpdateChildrenListViewModel (** validated_data )
194
208
195
209
196
- class PublishableMetaDataSerializer (ZdSModelSerializer ):
197
- tags = CommaSeparatedCharField (source = 'tags' , required = False , filter_function = TagValidator ().validate_one_element )
210
+ class PublishableMetaDataSerializer (serializers . ModelSerializer ):
211
+ tags = CommaSeparatedCharField (required = False , filter_function = TagValidator ().validate_one_element )
198
212
199
213
class Meta :
200
214
model = PublishableContent
201
- exclude = ('is_obsolete' , 'must_reindex' , 'last_note' , 'helps' , 'beta_topic' , 'image' , 'content_type_attribute' )
202
- read_only_fields = ('authors' , 'gallery' , 'public_version' , 'js_support' , ' is_locked' , 'relative_images_path' ,
215
+ exclude = ('is_obsolete' , 'must_reindex' , 'last_note' , 'helps' , 'beta_topic' , 'image' )
216
+ read_only_fields = ('authors' , 'gallery' , 'public_version' , 'is_locked' , 'relative_images_path' ,
203
217
'sha_picked' , 'sha_draft' , 'sha_validation' , 'sha_beta' , 'sha_public' , 'picked_date' ,
204
218
'update_date' , 'pubdate' , 'creation_date' , 'slug' )
205
219
depth = 2
206
220
207
221
def create (self , validated_data ):
208
222
# default db values
209
- validated_data ['is_js' ] = False # Always false when we create
223
+ validated_data ['js_support' ] = False # Always false when we create
224
+ validated_data ['creation_date' ] = datetime .datetime .now ()
210
225
211
226
# links to other entities
212
227
tags = validated_data .pop ('tags' , '' )
213
228
content = super ().create (validated_data )
229
+ content .save ()
214
230
content .add_tags (tags )
215
- content .add_author (self .context ['author' ])
216
231
init_new_repo (content , '' , '' , _ ('Création de {}' ).format (content .title ), do_commit = True )
232
+ content .authors .add (self .context ['author' ])
233
+ content .create_gallery ()
234
+ content .save ()
235
+ content .ensure_author_gallery ()
217
236
return content
218
237
219
238
def update (self , instance , validated_data ):
@@ -240,3 +259,9 @@ def update(self, instance, validated_data):
240
259
do_commit = True
241
260
)
242
261
return super .update (instance , working_dictionary )
262
+
263
+
264
+ class ContentCategorySerializer (serializers .ModelSerializer ):
265
+ class Meta :
266
+ model = SubCategory
267
+ depth = 1
0 commit comments