Skip to content

Commit

Permalink
Merge pull request #613 from deschler/black
Browse files Browse the repository at this point in the history
Use Black
  • Loading branch information
last-partizan committed Sep 18, 2021
2 parents e3c5213 + 03b81da commit 26b9a78
Show file tree
Hide file tree
Showing 26 changed files with 1,204 additions and 505 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/github-actions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ jobs:
- name: Install flake8
run: |
python -m pip install --upgrade pip
pip install flake8
- name: Lint with flake8
pip install flake8 black
- name: Lint with flake8 and black
run: |
flake8 modeltranslation
black --check modeltranslation *.py
Test:
runs-on: ubuntu-latest
strategy:
Expand Down
10 changes: 7 additions & 3 deletions modeltranslation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,13 @@ def get_git_changeset():

repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen(
'git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True, cwd=repo_dir,
universal_newlines=True)
'git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=repo_dir,
universal_newlines=True,
)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
Expand Down
93 changes: 59 additions & 34 deletions modeltranslation/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@
from modeltranslation import settings as mt_settings
from modeltranslation.translator import translator
from modeltranslation.utils import (
get_translation_fields, build_css_class, build_localized_fieldname, get_language,
get_language_bidi, unique)
get_translation_fields,
build_css_class,
build_localized_fieldname,
get_language,
get_language_bidi,
unique,
)
from modeltranslation.widgets import ClearableWidgetWrapper

from django.contrib.contenttypes.admin import GenericTabularInline
Expand Down Expand Up @@ -56,9 +61,7 @@ def patch_translation_field(self, db_field, field, request, **kwargs):
except AttributeError:
pass
else:
orig_formfield = self.formfield_for_dbfield(
orig_field, request, **kwargs
)
orig_formfield = self.formfield_for_dbfield(orig_field, request, **kwargs)
field.widget = deepcopy(orig_formfield.widget)
attrs = field.widget.attrs
# if any widget attrs are defined on the form they should be copied
Expand All @@ -71,32 +74,33 @@ def patch_translation_field(self, db_field, field, request, **kwargs):
# field.widget = deepcopy(orig_formfield.widget)
if orig_field.name in self.both_empty_values_fields:
from modeltranslation.forms import NullableField, NullCharField

form_class = field.__class__
if issubclass(form_class, NullCharField):
# NullableField don't work with NullCharField
form_class.__bases__ = tuple(
b for b in form_class.__bases__ if b != NullCharField)
b for b in form_class.__bases__ if b != NullCharField
)
field.__class__ = type(
'Nullable%s' % form_class.__name__, (NullableField, form_class), {})
'Nullable%s' % form_class.__name__, (NullableField, form_class), {}
)
if (
(
db_field.empty_value == 'both' or
orig_field.name in self.both_empty_values_fields
) and isinstance(field.widget, (forms.TextInput, forms.Textarea))
):
db_field.empty_value == 'both' or orig_field.name in self.both_empty_values_fields
) and isinstance(field.widget, (forms.TextInput, forms.Textarea)):
field.widget = ClearableWidgetWrapper(field.widget)
css_classes = field.widget.attrs.get('class', '').split(' ')
css_classes.append('mt')
# Add localized fieldname css class
css_classes.append(build_css_class(db_field.name, 'mt-field'))
# Add mt-bidi css class if language is bidirectional
if(get_language_bidi(db_field.language)):
if get_language_bidi(db_field.language):
css_classes.append('mt-bidi')
if db_field.language == mt_settings.DEFAULT_LANGUAGE:
# Add another css class to identify a default modeltranslation widget
css_classes.append('mt-default')
if (orig_formfield.required or self._orig_was_required.get(
'%s.%s' % (orig_field.model._meta, orig_field.name))):
if orig_formfield.required or self._orig_was_required.get(
'%s.%s' % (orig_field.model._meta, orig_field.name)
):
# In case the original form field was required, make the
# default translation field required instead.
orig_formfield.required = False
Expand Down Expand Up @@ -146,11 +150,12 @@ def replace_orig_field(self, option):
for opt in option:
if opt in self.trans_opts.fields:
index = option_new.index(opt)
option_new[index:index + 1] = get_translation_fields(opt)
option_new[index : index + 1] = get_translation_fields(opt)
elif isinstance(opt, (tuple, list)) and (
[o for o in opt if o in self.trans_opts.fields]):
[o for o in opt if o in self.trans_opts.fields]
):
index = option_new.index(opt)
option_new[index:index + 1] = self.replace_orig_field(opt)
option_new[index : index + 1] = self.replace_orig_field(opt)
option = option_new
return option

Expand All @@ -166,10 +171,12 @@ def _patch_fieldsets(self, fieldsets):
def _patch_prepopulated_fields(self):
def localize(sources, lang):
"Append lang suffix (if applicable) to field list"

def append_lang(source):
if source in self.trans_opts.fields:
return build_localized_fieldname(source, lang)
return source

return tuple(map(append_lang, sources))

prepopulated_fields = {}
Expand Down Expand Up @@ -263,8 +270,8 @@ def _patch_list_editable(self):
index = editable_new.index(field)
display_index = display_new.index(field)
translation_fields = get_translation_fields(field)
editable_new[index:index + 1] = translation_fields
display_new[display_index:display_index + 1] = translation_fields
editable_new[index : index + 1] = translation_fields
display_new[display_index : display_index + 1] = translation_fields
self.list_editable = editable_new
self.list_display = display_new

Expand All @@ -279,21 +286,32 @@ def _group_fieldsets(self, fieldsets):
# Create a fieldset to group each translated field's localized fields
fields = sorted((f for f in self.opts.get_fields() if f.concrete))
untranslated_fields = [
f.name for f in fields if (
f.name
for f in fields
if (
# Exclude the primary key field
f is not self.opts.auto_field and
f is not self.opts.auto_field
# Exclude non-editable fields
f.editable and
and f.editable
# Exclude the translation fields
not hasattr(f, 'translated_field') and
and not hasattr(f, 'translated_field')
# Honour field arguments. We rely on the fact that the
# passed fieldsets argument is already fully filtered
# and takes options like exclude into account.
f.name in flattened_fieldsets
and f.name in flattened_fieldsets
)
]
# TODO: Allow setting a label
fieldsets = [('', {'fields': untranslated_fields},)] if untranslated_fields else []
fieldsets = (
[
(
'',
{'fields': untranslated_fields},
)
]
if untranslated_fields
else []
)

temp_fieldsets = {}
for orig_field, trans_fields in self.trans_opts.fields.items():
Expand All @@ -303,13 +321,16 @@ def _group_fieldsets(self, fieldsets):
# fieldset's label - using gettext_lazy in your model
# declaration can make that translatable.
label = self.model._meta.get_field(orig_field).verbose_name.capitalize()
temp_fieldsets[orig_field] = (label, {
'fields': trans_fieldnames,
'classes': ('mt-fieldset',)
})

fields_order = unique(f.translated_field.name for f in self.opts.fields if
hasattr(f, 'translated_field') and f.name in flattened_fieldsets)
temp_fieldsets[orig_field] = (
label,
{'fields': trans_fieldnames, 'classes': ('mt-fieldset',)},
)

fields_order = unique(
f.translated_field.name
for f in self.opts.fields
if hasattr(f, 'translated_field') and f.name in flattened_fieldsets
)
for field_name in fields_order:
fieldsets.append(temp_fieldsets.pop(field_name))
assert not temp_fieldsets # cleaned
Expand All @@ -323,7 +344,9 @@ def get_form(self, request, obj=None, **kwargs):
def get_fieldsets(self, request, obj=None):
return self._get_fieldsets_pre_form_or_formset(request, obj) or self._group_fieldsets(
self._get_fieldsets_post_form_or_formset(
request, self.get_form(request, obj, fields=None), obj))
request, self.get_form(request, obj, fields=None), obj
)
)


class TranslationInlineModelAdmin(TranslationBaseModelAdmin, InlineModelAdmin):
Expand Down Expand Up @@ -363,6 +386,7 @@ class TabbedDjangoJqueryTranslationAdmin(TranslationAdmin):
Convenience class which includes the necessary media files for tabbed
translation fields. Reuses Django's internal jquery version.
"""

class Media:
js = (
'admin/js/jquery.init.js',
Expand All @@ -380,6 +404,7 @@ class TabbedExternalJqueryTranslationAdmin(TranslationAdmin):
Convenience class which includes the necessary media files for tabbed
translation fields. Loads recent jquery version from a cdn.
"""

class Media:
js = (
mt_settings.JQUERY_URL,
Expand Down
1 change: 1 addition & 0 deletions modeltranslation/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ class ModeltranslationConfig(AppConfig):

def ready(self):
from modeltranslation.models import handle_translation_registrations

handle_translation_registrations()

0 comments on commit 26b9a78

Please sign in to comment.