|
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'] = kwargs.get('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
|
|
|
# set 'required' attribute for each widget separately |
|
37
|
1 |
|
for f, w in zip(self.fields, self.widget.widgets): |
|
38
|
1 |
|
w.is_required = f.required |
|
39
|
|
|
|
|
40
|
1 |
|
def compress(self, value: List[str]) -> value_class: |
|
|
|
|
|
|
41
|
|
|
"""Compresses the values from individual fields |
|
42
|
|
|
into a single :see:LocalizedValue instance. |
|
43
|
|
|
|
|
44
|
|
|
Arguments: |
|
45
|
|
|
value: |
|
46
|
|
|
The values from all the widgets. |
|
47
|
|
|
|
|
48
|
|
|
Returns: |
|
49
|
|
|
A :see:LocalizedValue containing all |
|
50
|
|
|
the value in several languages. |
|
51
|
|
|
""" |
|
52
|
|
|
|
|
53
|
1 |
|
localized_value = self.value_class() |
|
54
|
|
|
|
|
55
|
1 |
|
for (lang_code, _), value in zip(settings.LANGUAGES, value): |
|
56
|
1 |
|
localized_value.set(lang_code, value) |
|
57
|
|
|
|
|
58
|
1 |
|
return localized_value |
|
59
|
|
|
|
|
60
|
|
|
|
|
61
|
1 |
|
class LocalizedCharFieldForm(LocalizedFieldForm): |
|
62
|
|
|
|
|
63
|
1 |
|
widget = LocalizedCharFieldWidget |
|
64
|
1 |
|
value_class = LocalizedStingValue |
|
65
|
|
|
|
|
66
|
|
|
|
|
67
|
1 |
|
class LocalizedTextFieldForm(LocalizedFieldForm): |
|
68
|
|
|
|
|
69
|
|
|
value_class = LocalizedStingValue |
|
70
|
|
|
|