|
1 | 1 | import json |
| 2 | +from uuid import uuid4 |
2 | 3 | from django.utils.functional import cached_property |
3 | 4 | from django.utils.html import format_html_join |
4 | 5 | from django.template import loader |
@@ -123,10 +124,17 @@ def from_json(self): |
123 | 124 | else: |
124 | 125 | return self.value |
125 | 126 |
|
| 127 | + def copy(self): |
| 128 | + return StreamObject( |
| 129 | + value=json.dumps(self._iterate_over_models(_copy)), |
| 130 | + model_list=self.model_list |
| 131 | + ) |
| 132 | + |
126 | 133 | @cached_property |
127 | 134 | def to_json(self): |
128 | 135 | return self.value |
129 | 136 |
|
| 137 | + |
130 | 138 | def _get_block_tmpl(model_class, model_str): |
131 | 139 | if hasattr(model_class, 'block_template'): |
132 | 140 | return model_class.block_template |
@@ -168,6 +176,39 @@ def _get_data_list(model_class, model_str, content, ctx): |
168 | 176 | 'template': _get_block_tmpl(model_class, model_str) |
169 | 177 | } |
170 | 178 |
|
| 179 | +def _copy(model_class, model_str, content, ctx): |
| 180 | + as_list = ctx['as_list'] |
| 181 | + if as_list: |
| 182 | + id = [] |
| 183 | + for obj in content: |
| 184 | + obj.pk = None |
| 185 | + obj.save() |
| 186 | + id.append(obj.pk) |
| 187 | + else: |
| 188 | + content.pk = None |
| 189 | + content.save() |
| 190 | + id = content.pk |
| 191 | + |
| 192 | + # check if have subblocks |
| 193 | + changed = False |
| 194 | + for f in content._meta.fields: |
| 195 | + # isinstance(f, StreamField) |
| 196 | + if hasattr(f, 'model_list'): |
| 197 | + changed = True |
| 198 | + value = getattr(content, f.name) |
| 199 | + # value is StreamObject |
| 200 | + new_value = value.copy() |
| 201 | + setattr(content, f.name, new_value) |
| 202 | + if changed: |
| 203 | + content.save() |
| 204 | + |
| 205 | + return dict( |
| 206 | + unique_id=uuid4().hex[:6], |
| 207 | + model_name=model_str, |
| 208 | + id=id, |
| 209 | + options=ctx['options'] |
| 210 | + ) |
| 211 | + |
171 | 212 | def get_streamblocks_models(): |
172 | 213 | streamblock_models = [] |
173 | 214 |
|
|
0 commit comments