File: types.py

package info (click to toggle)
django-dynamic-preferences 1.17.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 476 kB
  • sloc: python: 3,040; makefile: 3
file content (525 lines) | stat: -rw-r--r-- 14,191 bytes parent folder | download
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
"""
You'll find here the final, concrete classes of preferences you can use
in your own project.

"""
from django import forms
from django.db.models.signals import pre_delete

from django.core.files.storage import default_storage

from .preferences import AbstractPreference, Section
from .exceptions import MissingModel
from dynamic_preferences.serializers import *
from dynamic_preferences.settings import preferences_settings


class BasePreferenceType(AbstractPreference):
    """
    Used as a base for all other preference classes. You should subclass
    this one if you want to implement your own preference.
    """

    field_class = None
    """
    A form field that will be used to display and edit the preference
    use a class, not an instance.

    :Example:

    .. code-block:: python

        from django import forms

        class MyPreferenceType(BasePreferenceType):
            field_class = forms.CharField
    """

    #: A serializer class (see dynamic_preferences.serializers)
    serializer = None

    field_kwargs = {}
    """
    Additional kwargs to be passed to the form field.

    :Example:

    .. code-block:: python

        class MyPreference(StringPreference):

            field_kwargs = {
                'required': False,
                'initial': 'Hello there'
            }
    """

    @property
    def initial(self):
        return self.get_initial()

    def get_initial(self):
        """
        :return:
            initial data for form field
            from field_attribute['initial'] or default
        """
        return self.field_kwargs.get("initial", self.get("default"))

    @property
    def field(self):
        """
        :return:
            an instance of a form field for this preference, with
            the correct configuration (widget, initial value, validators...)
        """
        return self.setup_field()

    def setup_field(self, **kwargs):
        field_class = self.get("field_class")
        field_kwargs = self.get_field_kwargs()
        field_kwargs.update(kwargs)
        return field_class(**field_kwargs)

    def get_field_kwargs(self):
        """
        Return a dict of arguments to use as parameters for the field
        class instianciation.

        This will use :py:attr:`field_kwargs` as a starter,
        and use sensible defaults for a few attributes:

        - :py:attr:`instance.verbose_name` for the field label
        - :py:attr:`instance.help_text` for the field help text
        - :py:attr:`instance.widget` for the field widget
        - :py:attr:`instance.required` defined if the value is required or not
        - :py:attr:`instance.initial` defined if the initial value
        """
        kwargs = self.field_kwargs.copy()
        kwargs.setdefault("label", self.get("verbose_name"))
        kwargs.setdefault("help_text", self.get("help_text"))
        kwargs.setdefault("widget", self.get("widget"))
        kwargs.setdefault("required", self.get("required"))
        kwargs.setdefault("initial", self.initial)
        kwargs.setdefault("validators", [])
        kwargs["validators"].append(self.validate)
        return kwargs

    def api_repr(self, value):
        """
        Used only to represent a preference value using Rest Framework
        """
        return value

    def get_api_additional_data(self):
        """
        Additional data to serialize for use on front-end side, for example
        """
        return {}

    def get_api_field_data(self):
        """
        Field data to serialize for use on front-end side, for example
        will include choices available for a choice field
        """
        field = self.setup_field()
        d = {
            "class": field.__class__.__name__,
            "widget": {"class": field.widget.__class__.__name__},
        }

        try:
            d["input_type"] = field.widget.input_type
        except AttributeError:
            # some widgets, such as Select do not have an input type
            # in django < 1.11
            d["input_type"] = None

        return d

    def validate(self, value):
        """
        Used to implement custom cleaning logic for use in forms
        and serializers. The method will be passed as a validator to
        the preference form field.

        :Example:

        .. code-block:: python

            def validate(self, value):
                if value == '42':
                    raise ValidationError('Wrong value!')
        """
        return


class BooleanPreference(BasePreferenceType):
    """
    A preference type that stores a boolean.
    """

    field_class = forms.BooleanField
    serializer = BooleanSerializer
    required = False


class IntegerPreference(BasePreferenceType):
    """
    A preference type that stores an integer.
    """

    field_class = forms.IntegerField
    serializer = IntegerSerializer


IntPreference = IntegerPreference


class DecimalPreference(BasePreferenceType):
    """
    A preference type that stores a :py:class:`decimal.Decimal`.
    """

    field_class = forms.DecimalField
    serializer = DecimalSerializer


class FloatPreference(BasePreferenceType):
    """
    A preference type that stores a float.
    """

    field_class = forms.FloatField
    serializer = FloatSerializer


class StringPreference(BasePreferenceType):
    """
    A preference type that stores a string.
    """

    field_class = forms.CharField
    serializer = StringSerializer


class LongStringPreference(StringPreference):
    """
    A preference type that stores a string, but with a textarea widget.
    """

    widget = forms.Textarea


class ChoicePreference(BasePreferenceType):
    """
    A preference type that stores a string among a list of choices.
    """

    choices = ()
    """
    Expects the same values as for django :py:class:`forms.ChoiceField`.

    :Example:

    .. code-block:: python

        class MyChoicePreference(ChoicePreference):
            choices = [
                ('c', 'Carrot'),
                ('t', 'Tomato'),
            ]
    """
    field_class = forms.ChoiceField
    serializer = StringSerializer

    def get_field_kwargs(self):
        field_kwargs = super(ChoicePreference, self).get_field_kwargs()
        field_kwargs["choices"] = self.get("choices") or self.field_attribute["initial"]
        return field_kwargs

    def get_api_additional_data(self):
        d = super(ChoicePreference, self).get_api_additional_data()
        d["choices"] = self.get("choices")
        return d

    def get_choice_values(self):
        return [c[0] for c in self.get("choices")]

    def validate(self, value):
        if value not in self.get_choice_values():
            raise forms.ValidationError("{} is not a valid choice".format(value))


def create_deletion_handler(preference):
    """
    Will generate a dynamic handler to purge related preference
    on instance deletion
    """

    def delete_related_preferences(sender, instance, *args, **kwargs):
        queryset = preference.registry.preference_model.objects.filter(
            name=preference.name, section=preference.section
        )
        related_preferences = queryset.filter(
            raw_value=preference.serializer.serialize(instance)
        )
        related_preferences.delete()

    return delete_related_preferences


class ModelChoicePreference(BasePreferenceType):
    """
    A preference type that stores a reference to a model instance.

    :Example:

    .. code-block:: python

        from myapp.blog.models import BlogEntry

        @registry.register
        class FeaturedEntry(ModelChoicePreference):
            section = Section('blog')
            name = 'featured_entry'
            queryset = BlogEntry.objects.filter(status='published')

        blog_entry = BlogEntry.objects.get(pk=12)
        manager['blog__featured_entry'] = blog_entry

        # accessing the value will return the model instance
        assert manager['blog__featured_entry'].pk == 12

    .. note::

        You should provide either the :py:attr:`queryset` or :py:attr:`model`
        attribute
    """

    field_class = forms.ModelChoiceField
    serializer_class = ModelSerializer

    model = None
    """
    Which model class to link the preference to. You can skip this if you
    define the :py:attr:`queryset` attribute.
    """

    queryset = None
    """
    A queryset to filter available model instances.
    """
    signals_handlers = {}

    def __init__(self, *args, **kwargs):
        super(ModelChoicePreference, self).__init__(*args, **kwargs)

        if self.model is not None:
            # Set queryset following model attribute
            self.queryset = self.model.objects.all()
        elif self.queryset is not None:
            # Set model following queryset attribute
            self.model = self.queryset.model
        else:
            raise MissingModel

        self.serializer = self.serializer_class(self.model)

        self._setup_signals()

    def _setup_signals(self):
        handler = create_deletion_handler(self)
        # We need to keep a reference to the handler or it will cause
        # weakref to die and our handler will not be called
        self.signals_handlers["pre_delete"] = [handler]
        pre_delete.connect(handler, sender=self.model)

    def get_field_kwargs(self):
        kw = super(ModelChoicePreference, self).get_field_kwargs()
        kw["queryset"] = self.get("queryset")
        return kw

    def api_repr(self, value):
        if not value:
            return None
        if value.__class__.__name__ == "QuerySet":
            return [val.pk for val in value]
        return value.pk


class ModelMultipleChoicePreference(ModelChoicePreference):
    """
    A preference type that stores a reference list to the model instances.

    :Example:

    .. code-block:: python

        from myapp.blog.models import BlogEntry

        @registry.register
        class FeaturedEntries(ModelMultipleChoicePreference):
            section = Section('blog')
            name = 'featured_entries'
            queryset = BlogEntry.objects.all()

        blog_entries = BlogEntry.objects.filter(status='published')
        manager['blog__featured_entries'] = blog_entries

        # accessing the value will return the model queryset
        assert manager['blog__featured_entries'] == blog_entries

    .. note::

        You should provide either the :py:attr:`queryset` or :py:attr:`model`
        attribute
    """

    serializer_class = ModelMultipleSerializer
    field_class = forms.ModelMultipleChoiceField

    def _setup_signals(self):
        pass


class FilePreference(BasePreferenceType):
    """
    A preference type that stores a a reference to a model.

    :Example:

    .. code-block:: python

        from django.core.files.uploadedfile import SimpleUploadedFile

        @registry.register
        class Logo(FilePreference):
            section = Section('blog')
            name = 'logo'

        logo = SimpleUploadedFile(
            "logo.png", b"file_content", content_type="image/png")
        manager['blog__logo'] = logo

        # accessing the value will return a FieldFile object, just as
        # django.db.models.FileField
        assert manager['blog__logo'].read() == b'file_content'

        manager['blog__logo'].delete()

    """

    field_class = forms.FileField
    serializer_class = FileSerializer
    default = None

    @property
    def serializer(self):
        """
        The serializer need additional data about the related preference
        to upload file to correct directory
        """
        return self.serializer_class(self)

    def get_field_kwargs(self):
        kwargs = super(FilePreference, self).get_field_kwargs()
        kwargs["required"] = self.get("required", False)
        return kwargs

    def get_upload_path(self):
        return os.path.join(
            preferences_settings.FILE_PREFERENCE_UPLOAD_DIR, self.identifier()
        )

    def get_file_storage(self):
        """
        Override this method if you want to use a custom storage
        """
        return default_storage

    def api_repr(self, value):
        if value:
            return value.url


class DurationPreference(BasePreferenceType):
    """
    A preference type that stores a timedelta.
    """

    field_class = forms.DurationField
    serializer = DurationSerializer

    def api_repr(self, value):
        return duration_string(value)


class DatePreference(BasePreferenceType):
    """
    A preference type that stores a date.
    """

    field_class = forms.DateField
    serializer = DateSerializer

    def api_repr(self, value):
        return value.isoformat()


class DateTimePreference(BasePreferenceType):
    """
    A preference type that stores a datetime.
    """

    field_class = forms.DateTimeField
    serializer = DateTimeSerializer

    def api_repr(self, value):
        return value.isoformat()


class TimePreference(BasePreferenceType):
    """
    A preference type that stores a time.
    """

    field_class = forms.TimeField
    serializer = TimeSerializer

    def api_repr(self, value):
        return value.isoformat()


class MultipleChoicePreference(ChoicePreference):
    """
    A preference type that stores multiple strings among a list of choices.

    :Example:

    .. code-block:: python

        @registry.register
        class FeaturedEntries(MultipleChoicePreference):
            section = Section('blog')
            name = 'featured_entries'
            choices = [
                ('c', 'Carrot'),
                ('t', 'Tomato'),
            ]

    .. note::

       Internally, the selected choices are stored as a string, separated by a
       separator. The separator defaults to ','. The way this is implemented still
       is sae also on keys that cotain the separator, but if in doubt, you can still
       set the :py:attr:`separator` to any other character.
    """

    widget = forms.CheckboxSelectMultiple
    field_class = forms.MultipleChoiceField
    serializer = MultipleSerializer

    def validate(self, value):
        for v in value:
            super().validate(v)