summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ishtar_common/menus.py6
-rw-r--r--ishtar_common/models.py30
-rw-r--r--ishtar_common/models_common.py14
-rw-r--r--ishtar_common/templatetags/date_formating.py2
-rw-r--r--ishtar_common/templatetags/inline_formset.py2
-rw-r--r--ishtar_common/templatetags/link_to_window.py10
-rw-r--r--ishtar_common/templatetags/window_field.py8
-rw-r--r--ishtar_common/utils.py38
-rw-r--r--ishtar_common/utils_migrations.py6
-rw-r--r--ishtar_common/views.py160
-rw-r--r--ishtar_common/views_item.py82
-rw-r--r--ishtar_common/widgets.py42
-rw-r--r--ishtar_common/wizards.py12
13 files changed, 206 insertions, 206 deletions
diff --git a/ishtar_common/menus.py b/ishtar_common/menus.py
index 0f0ed6d29..770990a5e 100644
--- a/ishtar_common/menus.py
+++ b/ishtar_common/menus.py
@@ -80,7 +80,7 @@ class Menu:
"""
Force cache deletion and reinitialization of menu for all
"""
- lst_cache_key = u"{}-{}".format(
+ lst_cache_key = "{}-{}".format(
settings.PROJECT_SLUG, 'menu_updated_list',
)
lst_ids = cache.get(lst_cache_key)
@@ -93,7 +93,7 @@ class Menu:
"""
Stock updated information in cache
"""
- lst_cache_key = u"{}-{}".format(
+ lst_cache_key = "{}-{}".format(
settings.PROJECT_SLUG, 'menu_updated_list',
)
lst_ids = cache.get(lst_cache_key)
@@ -120,7 +120,7 @@ class Menu:
self.user = User.objects.get(pk=user_id)
except User.DoesNotExist:
return
- cache_key = u"{}-{}-{}".format(
+ cache_key = "{}-{}-{}".format(
settings.PROJECT_SLUG, 'menu_updated',
user_id
)
diff --git a/ishtar_common/models.py b/ishtar_common/models.py
index 3cecb1655..79fa8f6c0 100644
--- a/ishtar_common/models.py
+++ b/ishtar_common/models.py
@@ -796,11 +796,11 @@ class IshtarSiteProfile(models.Model, Cached):
"will appear. Use the markdown syntax. {random_image} "
"can be used to display a random image."))
operation_prefix = models.CharField(
- _("Main operation code prefix"), default=u'OA', null=True, blank=True,
+ _("Main operation code prefix"), default='OA', null=True, blank=True,
max_length=20
)
default_operation_prefix = models.CharField(
- _("Default operation code prefix"), default=u'OP', null=True,
+ _("Default operation code prefix"), default='OP', null=True,
blank=True, max_length=20
)
operation_region_code = models.CharField(
@@ -1575,7 +1575,7 @@ class DocumentTemplate(models.Model):
def publish(self, c_object):
tempdir = tempfile.mkdtemp("-ishtardocs")
output_name = tempdir + os.path.sep + \
- slugify(self.name.replace(' ', '_').lower()) + u'-' + \
+ slugify(self.name.replace(' ', '_').lower()) + '-' + \
datetime.date.today().strftime('%Y-%m-%d') + \
"." + self.template.name.split('.')[-1]
"""
@@ -1643,7 +1643,7 @@ class DocumentTemplate(models.Model):
return
tempdir = tempfile.mkdtemp("-ishtarlabels")
main_output_name = tempdir + os.path.sep + \
- slugify(self.name.replace(' ', '_').lower()) + u'-' + \
+ slugify(self.name.replace(' ', '_').lower()) + '-' + \
datetime.datetime.now().strftime('%Y-%m-%d-%H%M%S')
suffix = "." + self.template.name.split('.')[-1]
len_objects = len(objects)
@@ -1825,7 +1825,7 @@ class Organization(Address, Merge, OwnPerms, BaseGenderedType, ValueGetter,
}
QA_EDIT = QuickAction(
url="organization-qa-bulk-update", icon_class="fa fa-pencil",
- text=_(u"Bulk update"), target="many",
+ text=_("Bulk update"), target="many",
rights=['change_organization'])
QUICK_ACTIONS = [
QA_EDIT
@@ -2014,11 +2014,11 @@ class Person(Address, Merge, OwnPerms, ValueGetter, MainItem):
SLUG = "person"
_prefix = 'person_'
TYPE = (
- ('Mr', _(u'Mr')),
- ('Ms', _(u'Miss')),
- ('Mr and Miss', _(u'Mr and Mrs')),
- ('Md', _(u'Mrs')),
- ('Dr', _(u'Doctor')),
+ ('Mr', _('Mr')),
+ ('Ms', _('Miss')),
+ ('Mr and Miss', _('Mr and Mrs')),
+ ('Md', _('Mrs')),
+ ('Dr', _('Doctor')),
)
TABLE_COLS = ('name', 'surname', 'raw_name', 'email', 'person_types_list',
'attached_to', 'town')
@@ -2074,7 +2074,7 @@ class Person(Address, Merge, OwnPerms, ValueGetter, MainItem):
}
QA_EDIT = QuickAction(
url="person-qa-bulk-update", icon_class="fa fa-pencil",
- text=_(u"Bulk update"), target="many",
+ text=_("Bulk update"), target="many",
rights=['change_person'])
QUICK_ACTIONS = [
QA_EDIT
@@ -2195,7 +2195,7 @@ class Person(Address, Merge, OwnPerms, ValueGetter, MainItem):
if self.attached_to:
attached_to = str(self.attached_to)
if values:
- values.append(u'-')
+ values.append('-')
values.append(attached_to)
return " ".join(values)
@@ -2222,8 +2222,8 @@ class Person(Address, Merge, OwnPerms, ValueGetter, MainItem):
def generate_merge_key(self):
if self.name and self.name.strip():
self.merge_key = slugify(self.name.strip()) + \
- ((u'-' + slugify(self.surname.strip()))
- if self.surname else u'')
+ (('-' + slugify(self.surname.strip()))
+ if self.surname else '')
elif self.raw_name and self.raw_name.strip():
self.merge_key = slugify(self.raw_name.strip())
elif self.attached_to:
@@ -3170,7 +3170,7 @@ class Document(BaseHistorizedItem, CompleteIdentifierItem, OwnPerms, ImageModel,
}
QA_EDIT = QuickAction(
url="document-qa-bulk-update", icon_class="fa fa-pencil",
- text=_(u"Bulk update"), target="many",
+ text=_("Bulk update"), target="many",
rights=['change_document', 'change_own_document'])
QUICK_ACTIONS = [
QA_EDIT,
diff --git a/ishtar_common/models_common.py b/ishtar_common/models_common.py
index 6d8db23e0..2d8966066 100644
--- a/ishtar_common/models_common.py
+++ b/ishtar_common/models_common.py
@@ -295,7 +295,7 @@ class GeneralType(Cached, models.Model):
c_rank += 1
if c_rank:
help_items += c_rank * "</dl>"
- if help_text or help_items != u'\n':
+ if help_text or help_items != '\n':
help_text = help_text + help_items
else:
help_text = ""
@@ -1195,11 +1195,11 @@ class BaseHistorizedItem(StatisticItem, TemplateItem, FullSearch, Imported,
ALT_NAMES = {
'history_creator': SearchAltName(
- pgettext_lazy("key for text search", u"created-by"),
+ pgettext_lazy("key for text search", "created-by"),
'history_creator__ishtaruser__person__cached_label__iexact'
),
'history_modifier': SearchAltName(
- pgettext_lazy("key for text search", u"modified-by"),
+ pgettext_lazy("key for text search", "modified-by"),
'history_modifier__ishtaruser__person__cached_label__iexact'
),
'modified_before': SearchAltName(
@@ -2041,7 +2041,7 @@ class Address(BaseHistorizedItem):
return lbl
def address_lbl(self):
- lbl = u''
+ lbl = ''
prefix = ''
if self.alt_address_is_prefered:
prefix = 'alt_'
@@ -2529,11 +2529,11 @@ class GeoItem(models.Model):
x = models.FloatField(_('X'), blank=True, null=True)
y = models.FloatField(_('Y'), blank=True, null=True)
z = models.FloatField(_('Z'), blank=True, null=True)
- estimated_error_x = models.FloatField(_(u'Estimated error for X'),
+ estimated_error_x = models.FloatField(_('Estimated error for X'),
blank=True, null=True)
- estimated_error_y = models.FloatField(_(u'Estimated error for Y'),
+ estimated_error_y = models.FloatField(_('Estimated error for Y'),
blank=True, null=True)
- estimated_error_z = models.FloatField(_(u'Estimated error for Z'),
+ estimated_error_z = models.FloatField(_('Estimated error for Z'),
blank=True, null=True)
spatial_reference_system = models.ForeignKey(
SpatialReferenceSystem, verbose_name=_("Spatial Reference System"),
diff --git a/ishtar_common/templatetags/date_formating.py b/ishtar_common/templatetags/date_formating.py
index ca54692f9..fce714495 100644
--- a/ishtar_common/templatetags/date_formating.py
+++ b/ishtar_common/templatetags/date_formating.py
@@ -13,7 +13,7 @@ register = Library()
def date_formating(value):
try:
d = datetime.strptime(str(value), '%Y-%m-%d')
- return _(d.strftime("%b")).capitalize() + u" %d" % d.year
+ return _(d.strftime("%b")).capitalize() + " %d" % d.year
except ValueError:
# could be passed to non date value: on error return value
return value
diff --git a/ishtar_common/templatetags/inline_formset.py b/ishtar_common/templatetags/inline_formset.py
index 5e833c06f..9e3bfe9c9 100644
--- a/ishtar_common/templatetags/inline_formset.py
+++ b/ishtar_common/templatetags/inline_formset.py
@@ -8,7 +8,7 @@ register = template.Library()
@register.inclusion_tag('blocks/inline_formset.html')
def inline_formset(caption, formset, header=True, skip=False):
- u"""
+ """
Render a formset as an inline table.
For i18n of the caption be carreful to add manualy the caption label to
the translated fields
diff --git a/ishtar_common/templatetags/link_to_window.py b/ishtar_common/templatetags/link_to_window.py
index 77d743ea0..c971ded26 100644
--- a/ishtar_common/templatetags/link_to_window.py
+++ b/ishtar_common/templatetags/link_to_window.py
@@ -18,9 +18,9 @@ def simple_link_to_window(item, caption=""):
if getattr(item, "locked", None):
lock = '&nbsp;<i class="fa fa-lock text-danger" aria-hidden="true"></i>'
return mark_safe(
- u' <a class="display_details" href="#" '
- u'onclick="load_window(\'{}\')">'
- u'<i class="fa fa-info-circle" aria-hidden="true"></i>{}{}</a>'.format(
+ ' <a class="display_details" href="#" '
+ 'onclick="load_window(\'{}\')">'
+ '<i class="fa fa-info-circle" aria-hidden="true"></i>{}{}</a>'.format(
reverse("show-" + item.SLUG, args=[item.pk, '']), lock, caption))
@@ -72,8 +72,8 @@ def add_links(items, extra_attr=''):
lbl = item.fancy_str()
else:
lbl = str(item)
- html.append(u"{} {}".format(lbl, simple_link_to_window(item_lnk)))
- return mark_safe(u"<br/>".join(html))
+ html.append("{} {}".format(lbl, simple_link_to_window(item_lnk)))
+ return mark_safe("<br/>".join(html))
@register.inclusion_tag('ishtar/blocks/modify_toolbar.html',
diff --git a/ishtar_common/templatetags/window_field.py b/ishtar_common/templatetags/window_field.py
index f9f8bcab8..0a1914556 100644
--- a/ishtar_common/templatetags/window_field.py
+++ b/ishtar_common/templatetags/window_field.py
@@ -14,13 +14,13 @@ register = template.Library()
def field(caption, data, pre_data='', post_data='', li=False, size=None):
if data is True:
data = mark_safe(
- u'<i class="text-success fa fa-check" title="{}"></i>'.format(
- _(u"Yes"))
+ '<i class="text-success fa fa-check" title="{}"></i>'.format(
+ _("Yes"))
)
elif data is False:
data = mark_safe(
- u'<i class="text-danger fa fa-times" title="{}"></i>'.format(
- _(u"No"))
+ '<i class="text-danger fa fa-times" title="{}"></i>'.format(
+ _("No"))
)
# fix bad conversion
if data == 'None':
diff --git a/ishtar_common/utils.py b/ishtar_common/utils.py
index d86c94d86..aad995198 100644
--- a/ishtar_common/utils.py
+++ b/ishtar_common/utils.py
@@ -140,12 +140,12 @@ def import_class(full_path_classname):
elif 'models' not in mods and 'models_finds' not in mods \
and 'models_treatments' not in mods:
raise SuspiciousOperation(
- u"Try to import a non model from a string")
+ "Try to import a non model from a string")
module = import_module('.'.join(mods[:-1]))
model = getattr(module, mods[-1])
if not issubclass(model, models.Model):
raise SuspiciousOperation(
- u"Try to import a non model from a string")
+ "Try to import a non model from a string")
return model
@@ -172,7 +172,7 @@ def check_rights(rights=None, redirect_url='/'):
return view_func(request, *args, **kwargs)
put_session_message(
request.session.session_key,
- _(u"You don't have sufficient permissions to do this action."),
+ _("You don't have sufficient permissions to do this action."),
'warning'
)
return HttpResponseRedirect(redirect_url)
@@ -243,7 +243,7 @@ def update_data(data_1, data_2, merge=False):
if not merge:
return data_1
if data_2 and data_2 != data_1:
- return data_1 + u" ; " + data_2
+ return data_1 + " ; " + data_2
return data_1
for k in data_1:
if k not in data_2:
@@ -301,7 +301,7 @@ def clean_empty_data(data):
Clean empty branches of a data dict
"""
for key in data.keys():
- if data[key] in [{}, None, u""]:
+ if data[key] in [{}, None, ""]:
data.pop(key)
continue
if isinstance(data[key], dict):
@@ -348,7 +348,7 @@ def get_current_year():
def get_cache(cls, extra_args=tuple(), app_label=None):
if not app_label:
app_label = cls._meta.app_label
- cache_key = u"{}-{}-{}".format(
+ cache_key = "{}-{}-{}".format(
settings.PROJECT_SLUG, app_label, cls.__name__)
for arg in extra_args:
if not arg:
@@ -607,7 +607,7 @@ def _get_image_link(doc):
if item.__class__.__name__ == "ArchaeologicalSite":
item_class_name = str(IshtarSiteProfile.get_default_site_label())
- return mark_safe(u"""
+ return mark_safe("""
<div class="col col-lg-3">
<div class="card">
<div id="lightgallery-rand-img">
@@ -635,8 +635,8 @@ def _get_image_link(doc):
item_class_name,
str(item),
reverse(item.SHOW_URL, args=[item.pk, '']),
- str(_(u"Information")),
- str(_(u"Load another random image?"))))
+ str(_("Information")),
+ str(_("Load another random image?"))))
def get_random_item_image_link(request):
@@ -682,8 +682,8 @@ def get_srid_obj_from_point(point):
return SpatialReferenceSystem.objects.create(
srid=int(point.srid),
auth_name='EPSG',
- label=u"EPSG-{}".format(point.srid),
- txt_idx=u"epsg-{}".format(point.srid),
+ label="EPSG-{}".format(point.srid),
+ txt_idx="epsg-{}".format(point.srid),
)
@@ -1257,7 +1257,7 @@ def generate_relation_graph(obj, highlight_current=True,
style = 'label="{}"'.format(obj.relation_label)
if highlight_current:
style += ',style=filled,fillcolor="#C6C0C0"'
- dot_str += u'item{}[{},href="{}"];\n'.format(
+ dot_str += 'item{}[{},href="{}"];\n'.format(
obj.pk, style,
reverse('display-item',
args=[model.SLUG, obj.pk])
@@ -1276,7 +1276,7 @@ def generate_relation_graph(obj, highlight_current=True,
style = 'label="{}"'.format(left.relation_label)
if left.pk == obj.pk and highlight_current:
style += ',style=filled,fillcolor="#C6C0C0"'
- dot_str += u'item{}[{},href="{}"];\n'.format(
+ dot_str += 'item{}[{},href="{}"];\n'.format(
left.pk, style,
reverse('display-item', args=[model.SLUG, left.pk])
)
@@ -1286,17 +1286,17 @@ def generate_relation_graph(obj, highlight_current=True,
style = 'label="{}"'.format(right.relation_label)
if right.pk == obj.pk and highlight_current:
style += ',style=filled,fillcolor="#C6C0C0"'
- dot_str += u'item{}[{},href="{}"];\n'.format(
+ dot_str += 'item{}[{},href="{}"];\n'.format(
right.pk, style,
reverse('display-item', args=[model.SLUG, right.pk])
)
if not directed: # on the same level
- rel_str += u"{{rank = same; item{}; item{};}}\n".format(
+ rel_str += "{{rank = same; item{}; item{};}}\n".format(
left_pk, right_pk)
style = ""
if (left_pk, right_pk) in styles:
style = " [{}]".format(", ".join(styles[(left_pk, right_pk)]))
- rel_str += u'item{} -> item{}{};\n'.format(left_pk, right_pk, style)
+ rel_str += 'item{} -> item{}{};\n'.format(left_pk, right_pk, style)
rel_str += "}\n"
dot_str += rel_str + "\n}"
@@ -1361,7 +1361,7 @@ def generate_relation_graph(obj, highlight_current=True,
getattr(obj, attr).save("relations.png", django_file, save=True)
if debug:
- print(u"DOT file: {}. Tmp SVG file: {}.".format(dot_name, svg_tmp_name))
+ print("DOT file: {}. Tmp SVG file: {}.".format(dot_name, svg_tmp_name))
return
shutil.rmtree(tempdir)
@@ -1393,7 +1393,7 @@ def create_default_json_fields(model):
JsonDataField.objects.get_or_create(
content_type=content_type, key=key,
defaults={
- 'name': u" ".join(key.split('__')).capitalize(),
+ 'name': " ".join(key.split('__')).capitalize(),
'value_type': 'T',
'display': False
}
@@ -1471,7 +1471,7 @@ def m2m_historization_changed(sender, **kwargs):
def max_size_help():
- msg = str(_(u"The maximum supported file size is {} Mo.")).format(
+ msg = str(_("The maximum supported file size is {} Mo.")).format(
settings.MAX_UPLOAD_SIZE
)
return msg
diff --git a/ishtar_common/utils_migrations.py b/ishtar_common/utils_migrations.py
index bbe308f4e..57d75077e 100644
--- a/ishtar_common/utils_migrations.py
+++ b/ishtar_common/utils_migrations.py
@@ -151,9 +151,9 @@ def m2m_historization_init(obj):
# not clean... but json fields seems to be not well managed by
# cursor.execute
cursor.execute(
- u"UPDATE \"" + obj.__class__._meta.db_table + u"\" SET "
- u"history_m2m = '" + json.dumps(hist_values).replace(u"'", u"''") +
- u"'::json WHERE id = %s", [obj.pk]
+ "UPDATE \"" + obj.__class__._meta.db_table + "\" SET "
+ "history_m2m = '" + json.dumps(hist_values).replace("'", "''") +
+ "'::json WHERE id = %s", [obj.pk]
)
diff --git a/ishtar_common/views.py b/ishtar_common/views.py
index d5b38ebed..874252962 100644
--- a/ishtar_common/views.py
+++ b/ishtar_common/views.py
@@ -96,7 +96,7 @@ def wizard_is_available(wizard, request, model, pk):
except IndexError: # no step available
put_session_message(
request.session.session_key,
- _(u"You don't have sufficient permissions to do this action."),
+ _("You don't have sufficient permissions to do this action."),
'warning'
)
return
@@ -122,8 +122,8 @@ def index(request):
dct = {'warnings': []}
if settings.PROJECT_SLUG == 'default':
dct['warnings'].append(_(
- u"PROJECT_SLUG is set to \"default\". Change it in your "
- u"local_settings (or ask your admin to do it)."))
+ "PROJECT_SLUG is set to \"default\". Change it in your "
+ "local_settings (or ask your admin to do it)."))
profile = get_current_profile()
if profile.slug == 'default':
dct['warnings'].append(_(
@@ -146,14 +146,14 @@ def index(request):
person_search_wizard = wizards.PersonSearch.as_view(
[('general-person_search', forms.PersonFormSelection)],
- label=_(u"Person search"),
+ label=_("Person search"),
url_name='person_search',)
person_creation_wizard = wizards.PersonWizard.as_view(
[('identity-person_creation', forms.SimplePersonForm),
('person_type-person_creation', forms.PersonTypeForm),
('final-person_creation', FinalForm)],
- label=_(u"New person"),
+ label=_("New person"),
url_name='person_creation')
person_modification_wizard = wizards.PersonModifWizard.as_view(
@@ -161,7 +161,7 @@ person_modification_wizard = wizards.PersonModifWizard.as_view(
('identity-person_modification', forms.SimplePersonForm),
('person_type-person_creation', forms.PersonTypeForm),
('final-person_modification', FinalForm)],
- label=_(u"Person modification"),
+ label=_("Person modification"),
url_name='person_modification')
@@ -178,7 +178,7 @@ def person_modify(request, pk):
person_deletion_wizard = wizards.PersonDeletionWizard.as_view(
[('selec-person_deletion', forms.PersonFormMultiSelection),
('final-person_deletion', FinalDeleteForm)],
- label=_(u"Person deletion"),
+ label=_("Person deletion"),
url_name='person_deletion',)
@@ -193,20 +193,20 @@ def person_delete(request, pk):
organization_search_wizard = wizards.OrganizationSearch.as_view(
[('general-organization_search', forms.OrganizationFormSelection)],
- label=_(u"Organization search"),
+ label=_("Organization search"),
url_name='organization_search',)
organization_creation_wizard = wizards.OrganizationWizard.as_view(
[('identity-organization_creation', forms.OrganizationForm),
('final-organization_creation', FinalForm)],
- label=_(u"New organization"),
+ label=_("New organization"),
url_name='organization_creation')
organization_modification_wizard = wizards.OrganizationModifWizard.as_view(
[('selec-organization_modification', forms.OrganizationFormSelection),
('identity-organization_modification', forms.OrganizationForm),
('final-organization_modification', FinalForm)],
- label=_(u"Organization modification"),
+ label=_("Organization modification"),
url_name='organization_modification')
@@ -224,7 +224,7 @@ def organization_modify(request, pk):
organization_deletion_wizard = wizards.OrganizationDeletionWizard.as_view(
[('selec-organization_deletion', forms.OrganizationFormMultiSelection),
('final-organization_deletion', FinalDeleteForm)],
- label=_(u"Organization deletion"),
+ label=_("Organization deletion"),
url_name='organization_deletion',)
@@ -247,13 +247,13 @@ account_wizard_steps = [
account_management_wizard = wizards.AccountWizard.as_view(
account_wizard_steps,
- label=_(u"Account management"),
+ label=_("Account management"),
url_name='account_management',)
account_deletion_wizard = wizards.IshtarUserDeletionWizard.as_view(
[('selec-account_deletion', forms.AccountFormSelection),
('final-account_deletion', FinalDeleteForm)],
- label=_(u"Account deletion"),
+ label=_("Account deletion"),
url_name='account_deletion',)
@@ -320,19 +320,19 @@ def shortcut_menu(request):
profile = get_current_profile()
CURRENT_ITEMS = []
if profile.files:
- CURRENT_ITEMS.append((_(u"Archaeological file"), File))
- CURRENT_ITEMS.append((_(u"Operation"), Operation))
+ CURRENT_ITEMS.append((_("Archaeological file"), File))
+ CURRENT_ITEMS.append((_("Operation"), Operation))
if profile.archaeological_site:
CURRENT_ITEMS.append((profile.get_site_label(), ArchaeologicalSite))
if profile.context_record:
- CURRENT_ITEMS.append((_(u"Context record"), ContextRecord))
+ CURRENT_ITEMS.append((_("Context record"), ContextRecord))
if profile.warehouse:
- CURRENT_ITEMS.append((_(u"Warehouse"), Warehouse))
+ CURRENT_ITEMS.append((_("Warehouse"), Warehouse))
if profile.find:
- CURRENT_ITEMS.append((_(u"Find"), Find))
+ CURRENT_ITEMS.append((_("Find"), Find))
if profile.warehouse:
- CURRENT_ITEMS.append((_(u"Treatment request"), TreatmentFile))
- CURRENT_ITEMS.append((_(u"Treatment"), Treatment))
+ CURRENT_ITEMS.append((_("Treatment request"), TreatmentFile))
+ CURRENT_ITEMS.append((_("Treatment"), Treatment))
if hasattr(request.user, 'ishtaruser') and \
request.user.ishtaruser.advanced_shortcut_menu:
dct = {
@@ -848,7 +848,7 @@ def action(request, action_slug, obj_id=None, *args, **kwargs):
Action management
"""
if not check_permission(request, action_slug, obj_id):
- not_permitted_msg = ugettext(u"Operation not permitted.")
+ not_permitted_msg = ugettext("Operation not permitted.")
return HttpResponse(not_permitted_msg)
request.session['CURRENT_ACTION'] = action_slug
dct = {}
@@ -865,15 +865,15 @@ def dashboard_main(request, dct, obj_id=None, *args, **kwargs):
app_list = []
profile = models.get_current_profile()
if profile.files:
- app_list.append((_(u"Archaeological files"), 'files'))
- app_list.append((_(u"Operations"), 'operations'))
+ app_list.append((_("Archaeological files"), 'files'))
+ app_list.append((_("Operations"), 'operations'))
if profile.context_record:
- app_list.append((_(u"Context records"), 'contextrecords'))
+ app_list.append((_("Context records"), 'contextrecords'))
if profile.find:
- app_list.append((_(u"Finds"), 'finds'))
+ app_list.append((_("Finds"), 'finds'))
if profile.warehouse:
- app_list.append((_(u"Treatment requests"), 'treatmentfiles'))
- app_list.append((_(u"Treatments"), 'treatments'))
+ app_list.append((_("Treatment requests"), 'treatmentfiles'))
+ app_list.append((_("Treatments"), 'treatments'))
dct = {'app_list': app_list}
return render(request, 'ishtar/dashboards/dashboard_main.html', dct)
@@ -923,29 +923,29 @@ def dashboard_main_detail(request, item_name):
if date_source:
dashboard_kwargs['date_source'] = date_source
if item_name == 'files' and profile.files:
- lbl, dashboard = (_(u"Archaeological files"),
+ lbl, dashboard = (_("Archaeological files"),
models.Dashboard(File, **dashboard_kwargs))
elif item_name == 'operations':
from archaeological_operations.models import Operation
- lbl, dashboard = (_(u"Operations"),
+ lbl, dashboard = (_("Operations"),
models.Dashboard(Operation, **dashboard_kwargs))
elif item_name == 'contextrecords' and profile.context_record:
lbl, dashboard = (
- _(u"Context records"),
+ _("Context records"),
models.Dashboard(ContextRecord, slice=slicing, fltr=fltr))
elif item_name == 'finds' and profile.find:
- lbl, dashboard = (_(u"Finds"), models.Dashboard(Find,
+ lbl, dashboard = (_("Finds"), models.Dashboard(Find,
slice=slicing,
fltr=fltr))
elif item_name == 'treatmentfiles' and profile.warehouse:
lbl, dashboard = (
- _(u"Treatment requests"),
+ _("Treatment requests"),
models.Dashboard(TreatmentFile, **dashboard_kwargs))
elif item_name == 'treatments' and profile.warehouse:
if 'date_source' not in dashboard_kwargs:
dashboard_kwargs['date_source'] = 'start'
lbl, dashboard = (
- _(u"Treatments"),
+ _("Treatments"),
models.Dashboard(Treatment, **dashboard_kwargs))
if not lbl:
raise Http404
@@ -1116,7 +1116,7 @@ class ProfileEdit(LoginRequiredMixin, FormView):
def get_context_data(self, **kwargs):
data = super(ProfileEdit, self).get_context_data(**kwargs)
- data['page_name'] = _(u"Current profile")
+ data['page_name'] = _("Current profile")
return data
def form_valid(self, form):
@@ -1234,7 +1234,7 @@ class GlobalVarEdit(IshtarMixin, AdminLoginRequiredMixin, ModelFormSetView):
'extra': 1,
'can_delete': True
}
- page_name = _(u"Global variables")
+ page_name = _("Global variables")
fields = ['slug', 'value', 'description']
@@ -1242,7 +1242,7 @@ class NewImportView(IshtarMixin, LoginRequiredMixin, CreateView):
template_name = 'ishtar/form.html'
model = models.Import
form_class = forms.NewImportForm
- page_name = _(u"New import")
+ page_name = _("New import")
def get_success_url(self):
return reverse('current_imports')
@@ -1261,7 +1261,7 @@ class NewImportView(IshtarMixin, LoginRequiredMixin, CreateView):
class ImportListView(IshtarMixin, LoginRequiredMixin, ListView):
template_name = 'ishtar/import_list.html'
model = models.Import
- page_name = _(u"Current imports")
+ page_name = _("Current imports")
current_url = 'current_imports'
def get_queryset(self):
@@ -1325,7 +1325,7 @@ class ImportListView(IshtarMixin, LoginRequiredMixin, ListView):
class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
template_name = 'ishtar/import_step_by_step.html'
- page_name = _(u"Import step by step")
+ page_name = _("Import step by step")
current_url = 'import_step_by_step'
def get_import(self):
@@ -1420,7 +1420,7 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
if not data or not data[0]:
self.errors = self.imprt.errors
if not self.errors:
- self.errors = [("", "", _(u"No data provided"))]
+ self.errors = [("", "", _("No data provided"))]
else:
self.new_data = data[:]
return super(ImportStepByStepView, self).get(request, *args, **kwargs)
@@ -1474,18 +1474,18 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
if previous:
dct['page_numbers'].insert(0,
- (_(u"Previous"), previous + 1, True, False,
+ (_("Previous"), previous + 1, True, False,
True)
)
else:
dct['page_numbers'].insert(0,
- (_(u"Previous"), self.imprt_obj.skip_lines, False, False, True)
+ (_("Previous"), self.imprt_obj.skip_lines, False, False, True)
)
if has_next:
- dct['page_numbers'].append((_(u"Next"), has_next + 1, True, False,
+ dct['page_numbers'].append((_("Next"), has_next + 1, True, False,
True))
else:
- dct['page_numbers'].append((_(u"Next"), total_line_nb, False,
+ dct['page_numbers'].append((_("Next"), total_line_nb, False,
False, True))
def get_context_data(self, **kwargs):
@@ -1498,7 +1498,7 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
dct['errors'] = self.errors
if self.errors:
if self.imprt.current_csv_line:
- headers = [f.label if f else _(u"Not imported")
+ headers = [f.label if f else _("Not imported")
for f in self.imprt.get_formaters()]
dct['values'] = zip(
range(1, len(headers) + 1), headers,
@@ -1508,16 +1508,16 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
headers, self.path_to_column, interpreted_values = [], {}, []
for idx, formater in enumerate(self.imprt.get_formaters()):
if not formater:
- headers.append(_(u"Not imported"))
- interpreted_values.append(u"&ndash;")
+ headers.append(_("Not imported"))
+ interpreted_values.append("&ndash;")
continue
lbl = formater.label
if formater.comment:
- lbl += u' <i data-toggle="tooltip" class="fa '
- lbl += u'fa-question-circle"'
- lbl += u' aria-hidden="true" title="{}">'.format(
- formater.comment.replace(u'"', u'&quot;'))
- lbl += u'</i>'
+ lbl += ' <i data-toggle="tooltip" class="fa '
+ lbl += 'fa-question-circle"'
+ lbl += ' aria-hidden="true" title="{}">'.format(
+ formater.comment.replace('"', '&quot;'))
+ lbl += '</i>'
headers.append(lbl)
field_name = ""
@@ -1527,10 +1527,10 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
field_name = formater.export_field_name[0]
value = self.new_data[0].copy()
- field_name_tuple = field_name.split(u'__')
+ field_name_tuple = field_name.split('__')
# associate each path level to this column
while field_name_tuple:
- current_field_name = u'__'.join(field_name_tuple)
+ current_field_name = '__'.join(field_name_tuple)
if current_field_name not in self.path_to_column:
self.path_to_column[current_field_name] = []
self.path_to_column[current_field_name].append(idx)
@@ -1585,7 +1585,7 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
new_objects[key] = ([label], cls, value_dct)
dct['new_objects'] = [
- [u" &ndash; ".join(lbls), cls, new_dct]
+ [" &ndash; ".join(lbls), cls, new_dct]
for lbls, cls, new_dct in new_objects.values()
]
@@ -1647,7 +1647,7 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
return dct
def transform_path_to_label(self, cls, path):
- label = u" > ".join(
+ label = " > ".join(
str(l)
for l in get_field_labels_from_path(cls, path)
)
@@ -1664,31 +1664,31 @@ class ImportStepByStepView(IshtarMixin, LoginRequiredMixin, TemplateView):
else:
label = k
- concat_path = u"__".join(list(path) + [k])
+ concat_path = "__".join(list(path) + [k])
if concat_path in self.path_to_column:
for col in self.path_to_column[concat_path]:
col += 1
- label += u" <a href=\"#col-{}\">"\
- u"<span class=\"badge badge-info\"> {} {} </span>"\
- u"</a>".format(col, _(u"Col. "), col)
+ label += " <a href=\"#col-{}\">"\
+ "<span class=\"badge badge-info\"> {} {} </span>"\
+ "</a>".format(col, _("Col. "), col)
value_dct[label] = dct[k]
return value_dct
def list_to_html(self, lst):
if not lst:
- return _(u"* empty *")
- return u"<ul class='list-group'><li class='list-group-item'>" + \
- u"</li><li class='list-group-item'>".join([
+ return _("* empty *")
+ return "<ul class='list-group'><li class='list-group-item'>" + \
+ "</li><li class='list-group-item'>".join([
self.get_value(item) for item in lst
- ]) + u"</li></ul>"
+ ]) + "</li></ul>"
def get_value(self, item):
if hasattr(item, 'SHOW_URL'):
- return u"{}{}".format(str(item), simple_link_to_window(item))
+ return "{}{}".format(str(item), simple_link_to_window(item))
if hasattr(item, 'explicit_label'):
return item.explicit_label
if item in (None, [], [None]):
- return _(u"* empty *")
+ return _("* empty *")
if isinstance(item, list):
return self.list_to_html(item)
return str(item)
@@ -1715,7 +1715,7 @@ class ImportListTableView(ImportListView):
class ImportOldListView(ImportListView):
- page_name = _(u"Old imports")
+ page_name = _("Old imports")
current_url = 'old_imports'
def get_queryset(self):
@@ -1764,7 +1764,7 @@ class ImportLinkView(IshtarMixin, LoginRequiredMixin, ModelFormSetView):
class ImportDeleteView(IshtarMixin, LoginRequiredMixin, DeleteView):
template_name = 'ishtar/import_delete.html'
model = models.Import
- page_name = _(u"Delete import")
+ page_name = _("Delete import")
def get_success_url(self):
return reverse('current_imports')
@@ -1796,14 +1796,14 @@ class ManualMergeMixin(object):
def get_success_url(self):
return reverse(
self.redir_url,
- args=[u"_".join([str(item.pk) for item in self.items])])
+ args=["_".join([str(item.pk) for item in self.items])])
class PersonManualMerge(ManualMergeMixin, IshtarMixin, LoginRequiredMixin,
FormView):
form_class = forms.PersonMergeFormSelection
template_name = 'ishtar/form.html'
- page_name = _(u"Merge persons")
+ page_name = _("Merge persons")
current_url = 'person-manual-merge'
redir_url = 'person_manual_merge_items'
@@ -1827,7 +1827,7 @@ class PersonManualMergeItems(
LoginRequiredMixin, FormView):
form_class = forms.PersonMergeIntoForm
template_name = 'ishtar/form.html'
- page_name = _(u"Select the main person")
+ page_name = _("Select the main person")
current_url = 'person-manual-merge-items'
item_type = 'person'
@@ -1836,7 +1836,7 @@ class OrgaManualMerge(ManualMergeMixin, IshtarMixin, LoginRequiredMixin,
FormView):
form_class = forms.OrgaMergeFormSelection
template_name = 'ishtar/form.html'
- page_name = _(u"Merge organization")
+ page_name = _("Merge organization")
current_url = 'orga-manual-merge'
redir_url = 'orga_manual_merge_items'
@@ -1846,7 +1846,7 @@ class OrgaManualMergeItems(
LoginRequiredMixin, FormView):
form_class = forms.OrgaMergeIntoForm
template_name = 'ishtar/form.html'
- page_name = _(u"Select the main organization")
+ page_name = _("Select the main organization")
current_url = 'orga-manual-merge-items'
item_type = 'organization'
@@ -2045,7 +2045,7 @@ document_deletion_steps = [
document_deletion_wizard = wizards.DocumentDeletionWizard.as_view(
document_deletion_steps,
- label=_(u"Document deletion"),
+ label=_("Document deletion"),
url_name='document_deletion',)
@@ -2187,7 +2187,7 @@ class QRCodeForSearchView(LoginRequiredMixin, FormView):
class SearchQueryDelete(LoginRequiredMixin, DeleteView):
model = models.SearchQuery
template_name = 'ishtar/forms/bookmark_delete.html'
- page_name = _(u"Delete bookmark")
+ page_name = _("Delete bookmark")
def dispatch(self, request, *args, **kwargs):
if not request.user.pk:
@@ -2210,8 +2210,8 @@ class SearchQueryDelete(LoginRequiredMixin, DeleteView):
def get_context_data(self, **kwargs):
data = super(SearchQueryDelete, self).get_context_data(**kwargs)
data['modal_size'] = "small"
- data['page_name'] = _(u"Bookmark - Delete")
- data['action_name'] = _(u"Delete")
+ data['page_name'] = _("Bookmark - Delete")
+ data['action_name'] = _("Delete")
data['item'] = self.search_query.label
data['url'] = reverse('bookmark-delete', args=[self.search_query.pk])
return data
@@ -2326,7 +2326,7 @@ class QAItemForm(IshtarMixin, LoginRequiredMixin, FormView):
data['url'] = self.url
data['items'] = self.items
data['modal_size'] = self.modal_size
- data['page_name'] = u"{} &ndash; {}".format(
+ data['page_name'] = "{} &ndash; {}".format(
self.model._meta.verbose_name, self.page_name)
return data
@@ -2363,13 +2363,13 @@ class QAItemEditForm(QAItemForm):
def get_context_data(self, **kwargs):
data = super(QAItemEditForm, self).get_context_data(**kwargs)
- data['page_name'] = u"{} &ndash; {}".format(
+ data['page_name'] = "{} &ndash; {}".format(
self.model._meta.verbose_name, self.model.QA_EDIT.text)
if self.confirm:
if 'confirm' not in self.url:
data['url'] = self.url.split('?')[0] + "confirm/"
data['confirm'] = True
- data['action_name'] = _(u"Confirm")
+ data['action_name'] = _("Confirm")
return data
def form_valid(self, form):
@@ -2444,7 +2444,7 @@ class QADocumentPackagingFormView(QAItemForm):
template_name = 'ishtar/forms/qa_document_packaging.html'
model = models.Document
form_class = forms.QADocumentPackagingForm
- page_name = _(u"Packaging")
+ page_name = _("Packaging")
base_url = "document-qa-packaging"
def dispatch(self, request, *args, **kwargs):
diff --git a/ishtar_common/views_item.py b/ishtar_common/views_item.py
index 636ad26f0..f5c5f3b06 100644
--- a/ishtar_common/views_item.py
+++ b/ishtar_common/views_item.py
@@ -154,7 +154,7 @@ def new_qa_item(model, frm, many=False,
if model.SLUG == "site":
slug = "archaeologicalsite"
url_slug = "new-" + slug
- dct = {'page_name': str(_(u'New %s' % model_name.lower())),
+ dct = {'page_name': str(_('New %s' % model_name.lower())),
'url': reverse(url_slug, args=[parent_name]),
'slug': slug,
'parent_name': parent_name,
@@ -271,8 +271,8 @@ def show_item(model, name, extra_dct=None, model_for_perms=None):
except (ObjectDoesNotExist, ValueError):
return HttpResponse('')
doc_type = 'type' in dct and dct.pop('type')
- url_name = u"/".join(reverse('show-' + name, args=['0', '']
- ).split('/')[:-2]) + u"/"
+ url_name = "/".join(reverse('show-' + name, args=['0', '']
+ ).split('/')[:-2]) + "/"
profile = get_current_profile()
dct['PROFILE'] = profile
dct['CURRENCY'] = profile.currency
@@ -288,7 +288,7 @@ def show_item(model, name, extra_dct=None, model_for_perms=None):
# list current perms
if hasattr(request.user, 'ishtaruser') and request.user.ishtaruser:
- cache_key = u"{}-{}-{}".format(
+ cache_key = "{}-{}-{}".format(
settings.PROJECT_SLUG, "current-perms",
request.session.session_key,
)
@@ -457,16 +457,16 @@ def _push_to_list(obj, current_group, depth):
current_group.append(obj)
-true_strings = [u"1", u"true"]
+true_strings = ["1", "true"]
for language_code, language_lbl in settings.LANGUAGES:
activate(language_code)
- true_strings.append(str(_(u"Yes")).lower())
- true_strings.append(str(_(u"True")).lower())
+ true_strings.append(str(_("Yes")).lower())
+ true_strings.append(str(_("True")).lower())
deactivate()
def is_true_string(val):
- val = str(val).lower().replace(u'"', u"")
+ val = str(val).lower().replace('"', "")
if val in true_strings:
return True
@@ -482,13 +482,13 @@ def _parse_parentheses(s):
inside_quote = False
for char in s:
- if char == u'"':
+ if char == '"':
inside_quote = not inside_quote
if not inside_quote:
- if char == u'(':
+ if char == '(':
_push_to_list([], groups, depth)
depth += 1
- elif char == u')':
+ elif char == ')':
if depth > 0:
depth -= 1
else:
@@ -499,8 +499,8 @@ def _parse_parentheses(s):
return groups
-FORBIDDEN_CHAR = [u":"]
-RESERVED_CHAR = [u"|", u"&"]
+FORBIDDEN_CHAR = [":"]
+RESERVED_CHAR = ["|", "&"]
RE_FACET = re.compile('([-a-zA-Z]+)="([^"]+)"(?:;"([^"]+)")*')
@@ -557,7 +557,7 @@ def _parse_query_string(string, query_parameters, current_dct, exc_dct,
if query_parameters[base_term].extra_query:
dct.update(query_parameters[base_term].extra_query)
if term in dct:
- dct[term] += u";" + query
+ dct[term] += ";" + query
else:
dct[term] = query
if query_parameters[base_term].distinct_query:
@@ -569,10 +569,10 @@ def _parse_query_string(string, query_parameters, current_dct, exc_dct,
~Q(**dct) if excluded else Q(**dct)
return ""
for reserved_char in FORBIDDEN_CHAR:
- string = string.replace(reserved_char, u"")
+ string = string.replace(reserved_char, "")
if len(string) != 1:
for reserved_char in RESERVED_CHAR:
- string = string.replace(reserved_char, u"")
+ string = string.replace(reserved_char, "")
if not string:
return ""
if string.endswith('*'):
@@ -609,20 +609,20 @@ def _parse_parentheses_groups(groups, query_parameters, current_dct=None,
extra_distinct_q = []
if type(groups) is not list:
string = groups.strip()
- if string.startswith(u'"') and string.endswith(u'"') and \
- string.count(u'"') == 2:
+ if string.startswith('"') and string.endswith('"') and \
+ string.count('"') == 2:
string = string[1:-1]
# split into many groups if spaces
# do not split inside quotes
current_index = 0
found = string.find('"', current_index)
- SEP = u"?ç;?" # replace spaces inside quote with this characters
+ SEP = "?ç;?" # replace spaces inside quote with this characters
previous_quote = None
while found != -1:
if previous_quote is not None:
string = string[0:previous_quote] + \
- string[previous_quote:found].replace(u' ', SEP) + \
+ string[previous_quote:found].replace(' ', SEP) + \
string[found:]
previous_quote = None
# SEP is larger than a space
@@ -632,7 +632,7 @@ def _parse_parentheses_groups(groups, query_parameters, current_dct=None,
current_index = found + 1
found = string.find('"', current_index)
- string_groups = [gp.replace(SEP, u" ") for gp in string.split(u" ")]
+ string_groups = [gp.replace(SEP, " ") for gp in string.split(" ")]
if len(string_groups) == 1:
return _parse_query_string(
string_groups[0], query_parameters, current_dct, exc_dct,
@@ -661,9 +661,9 @@ def _parse_parentheses_groups(groups, query_parameters, current_dct=None,
query += q
has_item = True
previous_sep = None
- query += u")"
- if query == u"()":
- query = u""
+ query += ")"
+ if query == "()":
+ query = ""
query = unidecode(query)
return query, current_dct, exc_dct, extra_distinct_q
@@ -1071,8 +1071,8 @@ def _construct_query(relation_types, dct, or_reqs, and_reqs):
# manage multi value not already managed
for key in list(dct.keys()):
- if type(dct[key]) == str and u";" in dct[key]:
- values = [v for v in dct[key].split(u';') if v]
+ if type(dct[key]) == str and ";" in dct[key]:
+ values = [v for v in dct[key].split(';') if v]
if not values:
dct.pop(key)
continue
@@ -1134,7 +1134,7 @@ def _manage_default_search(dct, request, model, default_name, my_base_request,
else:
try:
dct = {"pk": request.session[default_name]}
- pinned_search = u'"{}"'.format(
+ pinned_search = '"{}"'.format(
model.objects.get(pk=dct["pk"])
)
except model.DoesNotExist:
@@ -1163,7 +1163,7 @@ def _manage_default_search(dct, request, model, default_name, my_base_request,
else:
req_key, up_attr = model.UP_MODEL_QUERY[
up_item.SLUG]
- pinned_search = u'{}="{}"'.format(
+ pinned_search = '{}="{}"'.format(
req_key,
getattr(up_item, up_attr)
)
@@ -1175,12 +1175,12 @@ def _manage_default_search(dct, request, model, default_name, my_base_request,
def _format_val(val):
if val is None:
- return u""
+ return ""
if type(val) == bool:
if val:
- return str(_(u"True"))
+ return str(_("True"))
else:
- return str(_(u"False"))
+ return str(_("False"))
return str(val)
@@ -1209,8 +1209,8 @@ def _format_geojson(rows, link_template):
'type': 'Feature',
'properties': feat,
'geometry': {
- u'type': u'Point',
- u'coordinates': [x, y]
+ 'type': 'Point',
+ 'coordinates': [x, y]
}
}
data['features'].append(feature)
@@ -1320,14 +1320,14 @@ def _get_data_from_query_old(items, query_table_cols, request,
new_vals = []
if not vals:
for idx, my_v in enumerate(my_vals):
- new_vals.append(u"{}{}{}".format(
- my_v, u' - ', ''))
+ new_vals.append("{}{}{}".format(
+ my_v, ' - ', ''))
else:
for idx, v in enumerate(vals):
- new_vals.append(u"{}{}{}".format(
- vals[idx], u' - ', _format_val(v)))
+ new_vals.append("{}{}{}".format(
+ vals[idx], ' - ', _format_val(v)))
my_vals = new_vals[:]
- data.append(u" & ".join(my_vals) or u"")
+ data.append(" & ".join(my_vals) or "")
if has_lock:
data.append(item.locked)
data.append(item.lock_user_id)
@@ -1857,7 +1857,7 @@ def get_item(model, func_name, default_name, extra_request_keys=None,
sorts[num] = ['', ''] # sign, col_num
if k.endswith('[dir]'):
order = request_items[k]
- sign = order and order == u'desc' and "-" or ''
+ sign = order and order == 'desc' and "-" or ''
sorts[num][0] = sign
if k.endswith('[column]'):
sorts[num][1] = request_items[k]
@@ -2051,7 +2051,7 @@ def get_item(model, func_name, default_name, extra_request_keys=None,
elif data_type == "csv":
response = HttpResponse(content_type='text/csv', charset=ENCODING)
n = datetime.datetime.now()
- filename = u'%s_%s.csv' % (
+ filename = '%s_%s.csv' % (
default_name, n.strftime('%Y%m%d-%H%M%S'))
response['Content-Disposition'] = 'attachment; filename=%s' \
% filename
@@ -2062,7 +2062,7 @@ def get_item(model, func_name, default_name, extra_request_keys=None,
col_names = []
for field_name in table_cols:
if type(field_name) in (list, tuple):
- field_name = u" & ".join(field_name)
+ field_name = " & ".join(field_name)
if hasattr(model, 'COL_LABELS') and \
field_name in model.COL_LABELS:
field = model.COL_LABELS[field_name]
diff --git a/ishtar_common/widgets.py b/ishtar_common/widgets.py
index 724e5d08c..67a16e4b7 100644
--- a/ishtar_common/widgets.py
+++ b/ishtar_common/widgets.py
@@ -138,26 +138,26 @@ class Select2Dynamic(Select2Media, forms.Select):
else:
attrs['style'] = "width: 370px"
options = [
- u"tags: true",
+ "tags: true",
]
'''
msg = str(
- _(u"Are you sure you want to add this term? (the addition is "
- u"effective after registration of the element)")
+ _("Are you sure you want to add this term? (the addition is "
+ "effective after registration of the element)")
)
- options.append(u"""createTag: function (params) {{
+ options.append("""createTag: function (params) {{
return confirm("{}");
}}""".format(msg))
'''
if attrs.get('full-width', None):
- options.append(u"containerCssClass: 'full-width'")
+ options.append("containerCssClass: 'full-width'")
html = super(Select2Dynamic, self).render(name, value, attrs)
html += """<script type="text/javascript">
$(document).ready(function() {{
$("#id_{}").select2({{ {} }});
}});</script>
- """.format(name, u", ".join(options))
+ """.format(name, ", ".join(options))
return mark_safe(html)
@@ -169,9 +169,9 @@ class Select2DynamicField(forms.ChoiceField):
Key can be added dynamically. Only check that the character " is not
used.
"""
- if value and u'"' in value:
+ if value and '"' in value:
raise ValidationError(
- _(u"The character \" is not accepted.")
+ _("The character \" is not accepted.")
)
def to_python(self, value):
@@ -268,7 +268,7 @@ class Select2Base(Select2Media):
new, html = "", ""
if self.new:
- html = u"<div class='input-group'>"
+ html = "<div class='input-group'>"
url_new = 'new-' + self.model.SLUG
url_new = reverse(url_new, args=["id_" + name])
# WARNING: the modal for the form must be in the main template
@@ -383,7 +383,7 @@ class DeleteWidget(forms.CheckboxInput):
attrs, {"name": name, "value": '1',
'class': "btn btn-danger"})
)
- output = u"<button%s>%s</button>" % (final_attrs, _("Delete"))
+ output = "<button%s>%s</button>" % (final_attrs, _("Delete"))
return mark_safe(output)
@@ -407,7 +407,7 @@ class SwitchWidget(forms.CheckboxInput):
if self.extra_label:
extra_label = '<label for="{}">{}</label>'.format(attrs['id'],
self.extra_label)
- output = u"""<span class="switch{}">
+ output = """<span class="switch{}">
<input{}>{}
</span>""".format(extra_class, final_attrs, extra_label)
return mark_safe(output)
@@ -415,7 +415,7 @@ class SwitchWidget(forms.CheckboxInput):
class DeleteSwitchWidget(SwitchWidget):
extra_class = "danger"
- extra_label = _(u"Delete")
+ extra_label = _("Delete")
class ImageFileInput(ClearableFileInput):
@@ -481,7 +481,7 @@ class CustomWidget(forms.TextInput):
def render(self, name, value, attrs=None, renderer=None):
if not value:
- value = u""
+ value = ""
final_attrs = flatatt(
self.build_attrs(attrs, {"name": name, "value": value}))
dct = {'final_attrs': final_attrs,
@@ -561,7 +561,7 @@ class ModelFieldMixin(object):
except self.model.DoesNotExist:
raise ValidationError(
str(
- _(u"{} is not a valid key for {}")
+ _("{} is not a valid key for {}")
).format(v, self.model)
)
if not self.multiple:
@@ -680,7 +680,7 @@ class JQueryAutoComplete(forms.TextInput):
def render(self, name, value, attrs=None, renderer=None):
attrs_hidden = self.build_attrs(attrs, {"name": name})
attrs_select = self.build_attrs(attrs)
- attrs_select['placeholder'] = _(u"Search...")
+ attrs_select['placeholder'] = _("Search...")
values = []
if value:
hiddens = []
@@ -798,7 +798,7 @@ class JQueryAutoComplete(forms.TextInput):
attrs_hidden_previous = attrs_hidden.copy()
attrs_hidden_previous['name'] += "_previous"
attrs_hidden_previous['id'] += "_previous"
- old_value += u"<input type='hidden'{}>".format(
+ old_value += "<input type='hidden'{}>".format(
flatatt(attrs_hidden_previous))
pk = None
if values:
@@ -857,7 +857,7 @@ class JQueryTown(forms.TextInput):
def render(self, name, value, attrs=None, renderer=None):
attrs_hidden = self.build_attrs(attrs, {"name": name})
attrs_select = self.build_attrs(attrs)
- attrs_select['placeholder'] = _(u"Search...")
+ attrs_select['placeholder'] = _("Search...")
selected = ''
selected_state = ''
selected_department = ''
@@ -972,7 +972,7 @@ class JQueryPersonOrganization(forms.TextInput):
def render(self, name, value, attrs=None, renderer=None):
attrs_hidden = self.build_attrs(attrs, {'name': name})
attrs_select = self.build_attrs(attrs)
- attrs_select['placeholder'] = _(u"Search...")
+ attrs_select['placeholder'] = _("Search...")
selected = ''
if value:
hiddens = []
@@ -1145,7 +1145,7 @@ class DataTable(Select2Media, forms.RadioSelect):
col_idx = []
for k in form.get_input_ids():
- col_idx.append(u'"%s"' % k)
+ col_idx.append('"%s"' % k)
col_idx = col_idx and ", ".join(col_idx) or ""
dct['encoding'] = settings.ENCODING or 'utf-8'
@@ -1183,13 +1183,13 @@ class DataTable(Select2Media, forms.RadioSelect):
'col_idx': col_idx,
'no_result': str(_("No results")),
'loading': str(_("Loading...")),
- 'remove': str(_(u"Remove")),
+ 'remove': str(_("Remove")),
'sname': name.replace('-', ''),
'gallery': self.gallery,
'use_map': self.map() if callable(self.map) else self.map,
'multiple': self.multiple,
'multiple_select': self.multiple_select,
- 'multi_cols': ",".join((u'"%d"' % col
+ 'multi_cols': ",".join(('"%d"' % col
for col in self.multiple_cols))})
t = loader.get_template('blocks/DataTables.html')
rendered += t.render(dct)
diff --git a/ishtar_common/wizards.py b/ishtar_common/wizards.py
index 9ee0c5896..b23069d36 100644
--- a/ishtar_common/wizards.py
+++ b/ishtar_common/wizards.py
@@ -186,7 +186,7 @@ class Wizard(IshtarWizard):
if not is_own:
messages.add_message(
request, messages.WARNING,
- _(u"Permission error: you cannot do this action.")
+ _("Permission error: you cannot do this action.")
)
self.session_reset(request, self.url_name)
return
@@ -1003,7 +1003,7 @@ class Wizard(IshtarWizard):
int(idx)
except:
continue
- if items[-1] == u'DELETE':
+ if items[-1] == 'DELETE':
to_delete.add(idx)
if idx in not_to_delete:
not_to_delete.remove(idx)
@@ -1043,7 +1043,7 @@ class Wizard(IshtarWizard):
items = key.split('-')
if len(items) > 2 and number == items[-2]:
items[-2] = str(idx)
- k = u'-'.join(items)
+ k = '-'.join(items)
data[k] = data.pop(key)[0]
# get a form key
frm = form.form
@@ -1070,8 +1070,8 @@ class Wizard(IshtarWizard):
not hasattr(self, 'form_initialized') or
not self.form_initialized):
total_field = max((total_field, len(init)))
- data[step + u'-INITIAL_FORMS'] = str(total_field)
- data[step + u'-TOTAL_FORMS'] = str(total_field + 1)
+ data[step + '-INITIAL_FORMS'] = str(total_field)
+ data[step + '-TOTAL_FORMS'] = str(total_field + 1)
# TODO:remove form_initialized?
# update initialization
# if request.POST and init and hasattr(self,
@@ -1941,7 +1941,7 @@ class AccountWizard(Wizard):
}
t = loader.get_template('account_activation_email.txt')
msg = t.render(context, self.request)
- subject = _(u"[%(app_name)s] Account creation/modification") % {
+ subject = _("[%(app_name)s] Account creation/modification") % {
"app_name": app_name}
send_mail(subject, msg, settings.ADMINS[0][1],
[dct['email']], fail_silently=True)