Merge pull request #30 from SectorLabs/subwidgets-labels

Subwidgets labels
This commit is contained in:
Swen Kooij 2017-07-15 13:56:29 +03:00 committed by GitHub
commit a38d53b609
2 changed files with 17 additions and 0 deletions

View File

@ -0,0 +1,4 @@
{% for widget in widget.subwidgets %}
<label for="{{ widget.attrs.id }}">{{ widget.attrs.lang_name }}</label>
{% include widget.template_name %}
{% endfor %}

View File

@ -10,6 +10,7 @@ from .value import LocalizedValue
class LocalizedFieldWidget(forms.MultiWidget):
"""Widget that has an input box for every language."""
template_name = 'localized_fields/multiwidget.html'
widget = forms.Textarea
def __init__(self, *args, **kwargs):
@ -22,6 +23,10 @@ class LocalizedFieldWidget(forms.MultiWidget):
super().__init__(initial_widgets, *args, **kwargs)
for ((lang_code, lang_name), widget) in zip(settings.LANGUAGES, self.widgets):
widget.attrs['lang_code'] = lang_code
widget.attrs['lang_name'] = lang_name
def decompress(self, value: LocalizedValue) -> List[str]:
"""Decompresses the specified value so
it can be spread over the internal widgets.
@ -63,13 +68,16 @@ class AdminLocalizedFieldWidget(LocalizedFieldWidget):
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id')
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
@ -77,22 +85,27 @@ class AdminLocalizedFieldWidget(LocalizedFieldWidget):
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
widget_attrs = self.build_widget_attrs(widget, widget_value, final_attrs)
output.append(widget.render(name + '_%s' % i, widget_value, widget_attrs))
context = {
'id': final_attrs.get('id'),
'name': name,
'widgets': zip([code for code, lang in settings.LANGUAGES], output),
'available_languages': settings.LANGUAGES
}
return render_to_string(self.template, context)
@staticmethod
def build_widget_attrs(widget, value, attrs):
attrs = dict(attrs) # Copy attrs to avoid modifying the argument.
if (not widget.use_required_attribute(value) or not widget.is_required) \
and 'required' in attrs:
del attrs['required']
return attrs