Passed
Pull Request — master (#1)
by
unknown
01:42
created

LocalizedTextFieldForm

Complexity

Total Complexity 0

Size/Duplication

Total Lines 3
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
c 1
b 1
f 0
wmc 0
1 1
from typing import List
2
3 1
from django import forms
4 1
from django.conf import settings
5
6 1
from .widgets import LocalizedFieldWidget, LocalizedCharFieldWidget
7 1
from .fields.localized_value import LocalizedValue, LocalizedStingValue
8
9
10 1
class LocalizedFieldForm(forms.MultiValueField):
11
    """Form for a localized field, allows editing
12
    the field in multiple languages."""
13
14 1
    widget = LocalizedFieldWidget
15 1
    value_class = LocalizedValue
16
17 1
    def __init__(self, *args, **kwargs):
18
        """Initializes a new instance of :see:LocalizedFieldForm."""
19
20 1
        fields = []
21
22 1
        for lang_code, _ in settings.LANGUAGES:
23 1
            field_options = {'required': False}
24
25 1
            if lang_code == settings.LANGUAGE_CODE:
26 1
                field_options['required'] = True
27
28 1
            field_options['label'] = lang_code
29 1
            fields.append(forms.fields.CharField(**field_options))
30
31 1
        super(LocalizedFieldForm, self).__init__(
32
            fields,
33
            require_all_fields=False,
34
            *args, **kwargs
35
        )
36
37 1
    def compress(self, value: List[str]) -> value_class:
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'value_class'
Loading history...
38
        """Compresses the values from individual fields
39
        into a single :see:LocalizedValue instance.
40
41
        Arguments:
42
            value:
43
                The values from all the widgets.
44
45
        Returns:
46
            A :see:LocalizedValue containing all
47
            the value in several languages.
48
        """
49
50 1
        localized_value = self.value_class()
51
52 1
        for (lang_code, _), value in zip(settings.LANGUAGES, value):
53 1
            localized_value.set(lang_code, value)
54
55 1
        return localized_value
56
57
58 1
class LocalizedCharFieldForm(LocalizedFieldForm):
59
60 1
    widget = LocalizedCharFieldWidget
61 1
    value_class = LocalizedStingValue
62
63
64 1
class LocalizedTextFieldForm(LocalizedFieldForm):
65
66
    value_class = LocalizedStingValue
67