django-swingcms / swingcms / cms / forms.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
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime, sys, os
from sys import getsizeof # required python 2.6 or higher

from django import forms
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.utils.html import escape, conditional_escape
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
from django.forms.util import flatatt

import settings
from loading import swingcache
from cms.code import list_to_choices, strip_tags, thumbify
from cms import models



class FormSorter(object):
    """
    Mix-in class to add sorting capabilities in Form and ModelForm subclassing case.
    """
    def sort_fields(self, order=None):

        order = getattr(self.Meta, 'fields', None)
        if order: self.fields.keyOrder = order


FILE_INPUT_CONTRADICTION = object()

class ClearableFileInput(forms.widgets.ClearableFileInput):

    initial_text = ''
    input_text = _('change')
    clear_checkbox_label = _('clear')

    template_with_initial = u"""
    %(initial_text)s%(initial)s<br /><br /><table><tr><td>%(let)s:</td><td>%(make_none)s</td></tr>%(clear_template)s
    <tr><td>%(input_text)s:</td><td>%(input)s</td></tr></table>
    """
    template_with_clear = u"""
    <tr><td><label for='%(clear_checkbox_id)s'>%(clear_checkbox_label)s:</label></td>
    <td>%(clear)s<br /></td></tr>
    """

    def render(self, name, value, attrs=None):

        substitutions = {
            'let': _('let'),
            'make_none': _('make none'),
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = u'%(input)s'
        substitutions['input'] = super(forms.widgets.ClearableFileInput, self).render(name, value, attrs)

        try:
            thumb_value = getattr(value.instance, '%s_thumb' % value.field.name)
            substitutions['initial'] = (u"<img src='%s'>" % escape(thumb_value.url))
        except (ValueError, AttributeError):
            try:
                substitutions['initial'] = (u"<a href='%s'>%s</a>" % (escape(value.url), escape(value.name)))
            except (ValueError, AttributeError):
                pass

        if 'initial' in substitutions:
            template = self.template_with_initial
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = forms.widgets.CheckboxInput().render(checkbox_name,
                                                                              False,
                                                                              attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)

    def value_from_datadict(self, data, files, name):

        upload = super(forms.widgets.ClearableFileInput, self).value_from_datadict(data, files, name)
        if not self.is_required and forms.widgets.CheckboxInput().value_from_datadict(
            data, files, self.clear_checkbox_name(name)):
            if upload:
                # If the user contradicts themselves (uploads a new file AND
                # checks the "clear" checkbox), we return a unique marker
                # object that FileField will turn into a ValidationError.
                return FILE_INPUT_CONTRADICTION
            # False signals to clear any existing value, as opposed to just None
            return False
        return upload


class SizerValidator(object):

    def __init__(self, max_size):

        self.max_size = max_size

    def __call__(self, value):

        if self.max_size and getattr(value, 'size', 0) > self.max_size:
            raise ValidationError(_("Size exceed limit of %s.") % self.max_size)


class SmartFileFormField(forms.FileField):

    widget = ClearableFileInput

    def __init__(self, *args, **kwargs):

        self.max_size = kwargs.pop('max_size', None)
        if self.max_size and not kwargs['help_text']:
            kwargs['help_text'] = _("Max %(max_size)s Kb.") % {'max_size':self.max_size/1000}
        super(SmartFileFormField, self).__init__(*args, **kwargs)
        self.validators.append(SizerValidator(self.max_size))

    def bound_data(self, data, initial):
        """
        Patch for returning always initial value for more sense and
        because new generated form not keep the uploaded file.
        """
        return initial


class SmartImageFormField(forms.ImageField):

    widget = ClearableFileInput

    def __init__(self, *args, **kwargs):

        self.max_size = kwargs.pop('max_size', None)
        if self.max_size and not kwargs['help_text']:
            kwargs['help_text'] = _("Max %(max_size)s Kb.") % {'max_size':self.max_size/1000}
        super(SmartImageFormField, self).__init__(*args, **kwargs)
        self.validators.append(SizerValidator(self.max_size))

    def bound_data(self, data, initial):
        """
        Patch for returning always initial value for more sense and
        because new generated form not keep the uploaded file.
        """
        return initial


class BaseObjForm(forms.ModelForm):

    required_css_class = 'required'

    def __init__(self, user, *args, **kwargs):

        super(BaseObjForm, self).__init__(*args, **kwargs)
        self.user = user
        self.changing = kwargs.get('instance') is not None

    def clean(self):

        # annotate orphan files for deferred deletion
        self.orphan_files = []
        for field_name, field in self.fields.items():

            # if file field or derivated subclass
            if isinstance(field, forms.FileField):
                new_file = self.cleaned_data.get(field_name)
                old_file = getattr(self.instance, field_name)

                # guess the action and attach it to form field
                if new_file == False:
                    action = 'CLEAR'
                elif old_file and not (old_file == new_file):
                    action = 'CHANGE'
                elif new_file and not old_file:
                    action = 'ADD'
                else:
                    action = 'LET'
                field.action = action

                # remember orphan filenames for deferred deleting
                if action in ('CLEAR', 'CHANGE'):
                    try:
                        self.orphan_files.append(''.join(old_file.file.name))
                    except:
                        pass
                    if isinstance(field, forms.ImageField):
                        thumb_field_name = '%s_thumb' % field_name
                        if hasattr(self.instance, thumb_field_name):
                            old_thumb = getattr(self.instance, thumb_field_name)
                            try:
                                self.orphan_files.append(''.join(old_thumb.file.name))
                            except:
                                pass

        return self.cleaned_data

    def save(self, *args, **kwargs):

        # workaround clear widget mechanism (old fields and old thumb fields if exists aren't
        # previously cleaned) and thumbify if needed
        for field_name, field in self.fields.items():
            if isinstance(field, forms.FileField):
                file_field = getattr(self.instance, field_name)
                thumb_field_name = '%s_thumb' % field_name
                if field.action == 'CLEAR':
                    file_field = None
                    if isinstance(field, forms.ImageField):
                        try:
                            setattr(self.instance, thumb_field_name, None)
                        except AttributeError:
                            pass
                elif field.action in ('ADD', 'CHANGE') and settings.THUMBIFY and hasattr(self.instance, thumb_field_name):
                    try:
                        thumb_field = thumbify(file_field)
                    except Exception, e:
                        print e
                        thumb_field = None
                    setattr(self.instance, thumb_field_name, thumb_field)
                    try:
                        thumb_field.close()
                    except:
                        pass

        # remove orphan files from disk
        for filename in self.orphan_files:
            try:
                os.remove(os.path.join(filename))
            except:
                pass

        return super(BaseObjForm, self).save(*args, **kwargs)


class BaseHierarchicObjForm(BaseObjForm):

    required_css_class = 'required'

    def __init__(self, user, max_size, *args, **kwargs):

        super(BaseHierarchicObjForm, self).__init__(user, *args, **kwargs)
        self.max_size = max_size

    def clean(self):

        cleaned_data = super(BaseHierarchicObjForm, self).clean()

        # check obj oversize
        size = 0
        for field_name, field in self.fields.items():

            # if file field or subclass
            if isinstance(field, forms.FileField):
                new_file = cleaned_data.get(field_name)
                old_file = getattr(self.instance, field_name)

                # compute size
                try:
                    if field.action == 'LET' and old_file:
                        size += old_file.size
                    elif field.action == 'CHANGE':
                        size += new_file.size
                except:
                    pass

            # calculate file field or derivated subclass size
            else:
                if field_name in cleaned_data:
                    size += getsizeof(cleaned_data[field_name])

        # check obj size
        if self.max_size and size > self.max_size:
            raise forms.ValidationError(_("The size of these obj exceed the max size of his parent container."))

        return cleaned_data


VISUALEDITOR_TAG = """
<textarea%s>%s</textarea>
<script type="text/javascript">
    $(document).ready(function() {
        visualeditor('id_%s', '%s');
    });
</script>
"""

class VisualEditor(forms.widgets.Textarea):
    """
    Implement visual editor (CKEditor) in textareas, require visualeditor js function.
    """
    def render(self, name, value, attrs=None):

        value = value or ""
        final_attrs = self.build_attrs(attrs, name=name)
        toolbar = final_attrs.pop('toolbar')
        return mark_safe(VISUALEDITOR_TAG % (flatatt(final_attrs),
                                             conditional_escape(force_unicode(value)),
                                             name,
                                             toolbar))


class HtmlField(forms.CharField):

    def __init__(self, *args, **kwargs):

        self.permitted_tags = kwargs.pop('permitted_tags', ())
        super(HtmlField, self).__init__(*args, **kwargs)

    def clean(self, value):

        value = strip_tags(value, permitted_tags=self.permitted_tags)
        value = super(HtmlField, self).clean(value)
        return value


################
##  CONTENTS  ##
################


class BaseContentForm(BaseHierarchicObjForm):

    title = forms.CharField(label=_('title'), max_length=128, required=False,
                            help_text=_("Max 128 characters, used also as title tag in head section."),
                            widget=forms.TextInput({'maxlength':128,'size':64}))
    template = forms.ChoiceField(label=_('template for view'), required=False, choices=())
    layout = forms.ChoiceField(label=_('layout for rendering'), required=False, choices=())
    dt_validity = forms.DateTimeField(label=_('public at'), required=False,
                                      help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE,
                                      input_formats=settings.DATETIME_INPUT_FORMATS,
                                      widget=forms.DateTimeInput(format=settings.DATETIME_INPUT_FORMATS[0]))
    dt_expired = forms.DateTimeField(label=_('expire at'), required=False,
                                     help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE,
                                     input_formats=settings.DATETIME_INPUT_FORMATS,
                                     widget=forms.DateTimeInput(format=settings.DATETIME_INPUT_FORMATS[0]))
    keywords = forms.CharField(label=_('keywords'), max_length=256, required=False,
                               help_text=_("Max 256 characters, used as meta tag in head section."),
                               widget=forms.Textarea({'rows':5,'cols':80}))
    description = forms.CharField(label=_('description'), max_length=1024, required=False,
                                  help_text=_("Max 1024 characters, used as meta tag in head section."),
                                  widget=forms.Textarea({'rows':12,'cols':80}))

    def __init__(self, user, max_size, *args, **kwargs):

        super(BaseContentForm, self).__init__(user, max_size, *args, **kwargs)

        # initialize categories and category choices
        if 'categories' in self.fields:
            all_categories = models.Category.objects.filter(scope__in=('content', self.instance.model_name))
            if all_categories:
                choices = all_categories.values_list('id', 'name')
                self.fields['categories'] = forms.MultipleChoiceField(label=_("categories"),
                                                                      choices=choices,
                                                                      widget=forms.CheckboxSelectMultiple,
                                                                      required=False)
            else:
                del(self.fields['categories'])

        # initialize template choices
        if 'template' in self.fields:
            choices = [('','')]
            choices.extend(settings.TEMPLATES[self.instance.model_name]['view'])
            self.fields['template'].choices = choices

        # initialize layout choices
        if 'layout' in self.fields:
            choices = [('','')]
            choices.extend(list_to_choices(models.LAYOUTS.keys()))
            self.fields['layout'].choices = choices

    def save(self, *args, **kwargs):

        # owner is the first contributor and changes need revision
        if self.changing:
            self.instance.status = "revision"
        else:
            self.instance.owner = self.user

        return super(BaseContentForm, self).save(*args, **kwargs)


class EventForm(BaseContentForm):

    text = forms.CharField(label=_('text'), help_text=_("Max 16384 characters."), max_length=16384,
                           widget=VisualEditor({'toolbar':'Mini','rows':50,'cols':80}))
    dt_start = forms.DateTimeField(label=_('start at'), input_formats=settings.DATETIME_INPUT_FORMATS,
                                   widget=forms.DateTimeInput(format=settings.DATETIME_INPUT_FORMATS[0]),
                                   help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE,)
    dt_stop = forms.DateTimeField(label=_('stop at'), input_formats=settings.DATETIME_INPUT_FORMATS,
                                  help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE,
                                  widget=forms.DateTimeInput(format=settings.DATETIME_INPUT_FORMATS[0]))
    class Meta:

        model = models.Event
        fields = ('name', 'title', 'dt_start', 'dt_stop', 'location', 'map', 'referent_name',
                  'referent_email', 'referent_cell', "text", 'dt_validity', 'dt_expired', 'language', 'categories',
                  'in_navigation', 'in_sitemap', 'template', "keywords", 'description')


class ImageForm(BaseContentForm):

    class Meta:

        model = models.Image
        fields = ('name', 'title', 'image', "notes", 'dt_validity', 'dt_expired', 'language',
                  'categories', 'in_navigation', 'in_sitemap', 'template', "keywords", 'description')


class FileForm(BaseContentForm):

    class Meta:

        model = models.File
        fields = ('name', 'title', 'file', "notes", 'dt_validity', 'dt_expired', 'language',
                  'categories', 'download_immediately', 'in_navigation', 'in_sitemap', 'template', "keywords",
                  'description')


class ArticleForm(BaseContentForm):

    subtitle = forms.CharField(label=_('subtitle'), help_text=_("Max 256 characters."), max_length=256,
                               required=False, widget=forms.Textarea({'rows':2,'cols':80}))
    introduction = forms.CharField(label=_('introduction'), help_text=_("Max 2048 characters."),
                                   max_length=2048, required=False,
                                   widget=forms.Textarea({'rows':20,'cols':80}))
    text = HtmlField(label=_('text'), help_text=_("Max 65536 characters."), max_length=65536,
                     widget=VisualEditor({'toolbar':'Small','rows':50,'cols':80}),
                     permitted_tags=settings.PERMITTED_TAGS4)

    class Meta:

        model = models.Article
        fields = ('name', 'title', 'image', 'image_caption', 'subtitle', 'introduction', 'dt_validity',
                  'dt_expired', 'language', 'text', 'categories', 'in_navigation', 'in_sitemap', 'template',
                  "keywords", 'description')


class LinkForm(BaseContentForm):

    class Meta:

        model = models.Link
        fields = ('name', 'title', 'dt_validity', 'dt_expired', 'link', "notes", 'open_immediately',
                  "no_follow", 'language', 'categories', 'in_navigation', 'in_sitemap', 'template', "keywords",
                  'description')


class PageForm(BaseContentForm):

    text = HtmlField(label=_('text'), widget=VisualEditor({'toolbar':'Full','rows':50,'cols':80}),
                     help_text=_("Max 65536 characters."), permitted_tags=settings.PERMITTED_TAGS1)

    class Meta:

        model = models.Page
        fields = ('name', 'title', 'dt_validity', 'dt_expired', 'language', 'text',
                  'categories', 'in_navigation', 'in_sitemap', 'template', "keywords", 'description')


class HtmlForm(BaseContentForm):

    html = forms.CharField(label=_('html'), help_text=_("Max 65536 characters."),
                           widget=forms.Textarea({'rows':50,'cols':80}))

    class Meta:

        model = models.Html
        fields = ('name', 'title', 'dt_validity', 'dt_expired', 'language', 'html', 'categories',
                  'in_navigation', 'in_sitemap', 'template', 'layout', "keywords", 'description')


class FolderForm(BaseContentForm):

    introduction = HtmlField(label=_('introduction'), help_text=_("Max 16384 characters."),
                             required=False, widget=VisualEditor({'toolbar':'Mini','rows':50,'cols':80}),
                             permitted_tags=settings.PERMITTED_TAGS5)
    notes = HtmlField(label=_('notes'), help_text=_("Max 16384 characters."), required=False,
                      widget=VisualEditor({'toolbar':'Mini','rows':50,'cols':80}),
                      permitted_tags=settings.PERMITTED_TAGS5)

    class Meta:

        model = models.Folder
        fields = ('name', 'title', 'max_size', 'dt_validity', 'dt_expired', 'language', 'introduction', 'image',
                  'notes', 'categories', 'in_navigation', 'in_sitemap', 'template', 'layout', "keywords", 'description')


###############
##  COLLAGE  ##
###############


class CollageForm(BaseContentForm):

    class Meta:

        model = models.Collage
        fields = ('name', 'title', 'dt_validity', 'dt_expired', 'render_as_layout', 'categories',
                  'in_navigation', 'in_sitemap', 'template', "keywords", 'description')


#################
##  COLLECTOR  ##
#################


class CollectorForm(BaseContentForm):

    subtitle = forms.CharField(label=_('subtitle'), help_text=_("Max 256 characters."), max_length=256,
                               required=False, widget=forms.Textarea({'rows':2,'cols':80}))
    introduction = forms.CharField(label=_('introduction'), help_text=_("Max 2048 characters."),
                                   max_length=2048, required=False,
                                   widget=forms.Textarea({'rows':20,'cols':80}))
    order_field = forms.ChoiceField(choices=(), initial='dt_addition')
    param_dt_field = forms.ChoiceField(choices=(), initial='dt_addition', required=False)

    def __init__(self, *args, **kwargs):

        super(CollectorForm, self).__init__(*args, **kwargs)
        self.fields['order_field'].choices = list_to_choices(swingcache.FIELD_NAMES)
        self.fields['param_dt_field'].choices = list_to_choices(swingcache.DATETIME_FIELD_NAMES)
        self.fields['param_folders'].choices = models.Folder.objects.all().values_list('id','name')
        collectible = ContentType.objects.filter(model__in=settings.COLLECTIBLE)
        self.fields['param_contenttypes'].choices = collectible.values_list('id','name')

    class Meta:

        model = models.Collector
        fields = ('name', 'title', 'subtitle', 'introduction', 'language', 'order_field',
                  'order_direction', 'limit', 'dt_validity', 'dt_expired', 'categories',
                  'template', "keywords", 'description', 'layout',

                  'datetime_criterion', 'param_dt_field', 'param_dt_operator', 'param_delta_year',
                  'param_delta_month', 'param_delta_day',

                  'category_criterion', 'param_categories',

                  'contenttype_criterion', 'param_contenttypes',

                  'localization_criterion', 'param_folders', 'param_recursion',

                  'status_criterion','param_statuses')


#############
##  OTHER  ##
#############


class CategoryForm(forms.ModelForm):

    required_css_class = 'required'

    class Meta:

        model = models.Category
        fields = ("name",)

    def __init__(self, scopes, *args, **kwargs):

        self.scopes = scopes
        self.is_multiple = len(self.scopes) > 1
        super(CategoryForm, self).__init__(*args, **kwargs)

        # only if multiple scope display choices
        if self.is_multiple:
            self.fields['scopes'] = forms.MultipleChoiceField(label=_("apply to"), widget=forms.CheckboxSelectMultiple)
            self.fields['scopes'].choices = list_to_choices(self.scopes)

    def clean(self):

        # if not multiple scope set mandatory value
        if not self.is_multiple:
            self.cleaned_data['scopes'] = self.scopes
        return self.cleaned_data


class EdittextForm(forms.Form):

    text = forms.CharField(label='',
                           max_length=65536,
                           widget=forms.Textarea({'rows':50,'cols':80}))


class MassinsertForm(forms.Form):

    required_css_class = 'required'

    content_type = forms.ChoiceField(label=_('content type'), choices=(('image','image'), ('file','file')),
                                     initial='file', widget=forms.RadioSelect)
    folder = forms.ChoiceField(label=_('folder'), choices=())
    status = forms.ChoiceField(label=_('status'), choices=list_to_choices(settings.STATUSES),
                               initial='public')

    def __init__(self, *args, **kwargs):

        super(MassinsertForm, self).__init__(*args, **kwargs)
        self.fields['folder'].choices = models.Folder.objects.all().values_list('id','name')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.