Various style fixes (#5797)

* removed unused imports

* use f-string where applicable

* string format changes
This commit is contained in:
Matthias Mair 2023-10-27 00:06:48 +02:00 committed by GitHub
parent 82b376de5b
commit 20d1fa847e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 53 additions and 103 deletions

View File

@ -67,10 +67,10 @@ class HelperForm(forms.ModelForm):
# Look for font-awesome icons
if prefix and prefix.startswith('fa-'):
prefix = r"<i class='fas {fa}'/>".format(fa=prefix)
prefix = f"<i class='fas {prefix}'/>"
if suffix and suffix.startswith('fa-'):
suffix = r"<i class='fas {fa}'/>".format(fa=suffix)
suffix = f"<i class='fas {suffix}'/>"
if prefix and suffix:
layouts.append(

View File

@ -520,7 +520,7 @@ def extract_serial_numbers(input_string, expected_quantity: int, starting_value=
if a == b:
# Invalid group
add_error(_("Invalid group range: {g}").format(g=group))
add_error(_(f"Invalid group range: {group}"))
continue
group_items = []
@ -549,13 +549,13 @@ def extract_serial_numbers(input_string, expected_quantity: int, starting_value=
break
if len(group_items) > remaining:
add_error(_("Group range {g} exceeds allowed quantity ({q})".format(g=group, q=expected_quantity)))
add_error(_(f"Group range {group} exceeds allowed quantity ({expected_quantity})"))
elif len(group_items) > 0 and group_items[0] == a and group_items[-1] == b:
# In this case, the range extraction looks like it has worked
for item in group_items:
add_serial(item)
else:
add_error(_("Invalid group range: {g}").format(g=group))
add_error(_(f"Invalid group range: {group}"))
else:
# In the case of a different number of hyphens, simply add the entire group
@ -573,14 +573,14 @@ def extract_serial_numbers(input_string, expected_quantity: int, starting_value=
sequence_count = max(0, expected_quantity - len(serials))
if len(items) > 2 or len(items) == 0:
add_error(_("Invalid group sequence: {g}").format(g=group))
add_error(_(f"Invalid group sequence: {group}"))
continue
elif len(items) == 2:
try:
if items[1]:
sequence_count = int(items[1]) + 1
except ValueError:
add_error(_("Invalid group sequence: {g}").format(g=group))
add_error(_(f"Invalid group sequence: {group}"))
continue
value = items[0]
@ -595,7 +595,7 @@ def extract_serial_numbers(input_string, expected_quantity: int, starting_value=
for item in sequence_items:
add_serial(item)
else:
add_error(_("Invalid group sequence: {g}").format(g=group))
add_error(_(f"Invalid group sequence: {group}"))
else:
# At this point, we assume that the 'group' is just a single serial value
@ -608,7 +608,7 @@ def extract_serial_numbers(input_string, expected_quantity: int, starting_value=
raise ValidationError([_("No serial numbers found")])
if len(errors) == 0 and len(serials) != expected_quantity:
raise ValidationError([_("Number of unique serial numbers ({s}) must match quantity ({q})").format(s=len(serials), q=expected_quantity)])
raise ValidationError([_(f"Number of unique serial numbers ({len(serials)}) must match quantity ({expected_quantity})")])
return serials
@ -646,7 +646,7 @@ def validateFilterString(value, model=None):
if len(pair) != 2:
raise ValidationError(
"Invalid group: {g}".format(g=group)
f"Invalid group: {group}"
)
k, v = pair
@ -656,7 +656,7 @@ def validateFilterString(value, model=None):
if not k or not v:
raise ValidationError(
"Invalid group: {g}".format(g=group)
f"Invalid group: {group}"
)
results[k] = v

View File

@ -762,7 +762,7 @@ class InvenTreeTree(MPTTModel):
def __str__(self):
"""String representation of a category is the full path to that category."""
return "{path} - {desc}".format(path=self.pathstring, desc=self.description)
return f"{self.pathstring} - {self.description}"
class InvenTreeNotesMixin(models.Model):

View File

@ -50,7 +50,7 @@ def rename_company_image(instance, filename):
else:
ext = ''
fn = 'company_{pk}_img'.format(pk=instance.pk)
fn = f'company_{instance.pk}_img'
if ext:
fn += '.' + ext
@ -185,7 +185,7 @@ class Company(InvenTreeNotesMixin, MetadataMixin, models.Model):
def __str__(self):
"""Get string representation of a Company."""
return "{n} - {d}".format(n=self.name, d=self.description)
return f"{self.name} - {self.description}"
def get_absolute_url(self):
"""Get the web URL for the detail view for this Company."""

View File

@ -25,7 +25,7 @@ from plugin.registry import registry
try:
from django_weasyprint import WeasyTemplateResponseMixin
except OSError as err: # pragma: no cover
print("OSError: {e}".format(e=err))
print(f"OSError: {err}")
print("You may require some further system packages to be installed.")
sys.exit(1)
@ -109,10 +109,7 @@ class LabelTemplate(MetadataMixin, models.Model):
def __str__(self):
"""Format a string representation of a label instance"""
return "{n} - {d}".format(
n=self.name,
d=self.description
)
return f"{self.name} - {self.description}"
name = models.CharField(
blank=False, max_length=100,

View File

@ -306,11 +306,7 @@ class PurchaseOrderExport(AjaxView):
export_format = request.GET.get('format', 'csv')
filename = '{order} - {company}.{fmt}'.format(
order=str(order),
company=order.supplier.name,
fmt=export_format
)
filename = f'{str(order)} - {order.supplier.name}.{export_format}'
dataset = PurchaseOrderLineItemResource().export(queryset=order.lines.all())

View File

@ -518,10 +518,7 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel)
try:
if self.pk == parent.pk:
raise ValidationError({'sub_part': _("Part '{p1}' is used in BOM for '{p2}' (recursive)").format(
p1=str(self),
p2=str(parent)
)})
raise ValidationError({'sub_part': _(f"Part '{self}' is used in BOM for '{parent}' (recursive)")})
bom_items = self.get_bom_items()
@ -530,10 +527,7 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel)
# Check for simple match
if item.sub_part == parent:
raise ValidationError({'sub_part': _("Part '{p1}' is used in BOM for '{p2}' (recursive)").format(
p1=str(parent),
p2=str(self)
)})
raise ValidationError({'sub_part': _(f"Part '{parent}' is used in BOM for '{self}' (recursive)")})
# And recursively check too
if recursive:
@ -600,7 +594,7 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel)
match = re.search(pattern, self.IPN)
if match is None:
raise ValidationError(_('IPN must match regex pattern {pat}').format(pat=pattern))
raise ValidationError(_(f'IPN must match regex pattern {pattern}'))
def validate_serial_number(self, serial: str, stock_item=None, check_duplicates=True, raise_error=False, **kwargs):
"""Validate a serial number against this Part instance.
@ -1799,7 +1793,7 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel)
min_price = normalize(min_price)
max_price = normalize(max_price)
return "{a} - {b}".format(a=min_price, b=max_price)
return f"{min_price} - {max_price}"
def get_supplier_price_range(self, quantity=1):
"""Return the supplier price range of this part:
@ -3358,7 +3352,7 @@ class PartParameterTemplate(MetadataMixin, models.Model):
"""Return a string representation of a PartParameterTemplate instance"""
s = str(self.name)
if self.units:
s += " ({units})".format(units=self.units)
s += f" ({self.units})"
return s
def clean(self):
@ -3498,12 +3492,7 @@ class PartParameter(MetadataMixin, models.Model):
def __str__(self):
"""String representation of a PartParameter (used in the admin interface)"""
return "{part} : {param} = {data} ({units})".format(
part=str(self.part.full_name),
param=str(self.template.name),
data=str(self.data),
units=str(self.template.units)
)
return f"{self.part.full_name} : {self.template.name} = {self.data} ({self.template.units})"
def save(self, *args, **kwargs):
"""Custom save method for the PartParameter model."""
@ -3726,10 +3715,7 @@ class BomItem(DataImportMixin, MetadataMixin, models.Model):
def __str__(self):
"""Return a string representation of this BomItem instance"""
return "{n} x {child} to make {parent}".format(
parent=self.part.full_name,
child=self.sub_part.full_name,
n=decimal2string(self.quantity))
return f"{decimal2string(self.quantity)} x {self.sub_part.full_name} to make {self.part.full_name}"
@staticmethod
def get_api_url():
@ -4043,7 +4029,7 @@ class BomItem(DataImportMixin, MetadataMixin, models.Model):
pmin = decimal2money(pmin)
pmax = decimal2money(pmax)
return "{pmin} to {pmax}".format(pmin=pmin, pmax=pmax)
return f"{pmin} to {pmax}"
@receiver(post_save, sender=BomItem, dispatch_uid='update_bom_build_lines')

View File

@ -235,10 +235,7 @@ def python_version(*args, **kwargs):
def inventree_version(shortstring=False, *args, **kwargs):
"""Return InvenTree version string."""
if shortstring:
return _("{title} v{version}".format(
title=version.inventreeInstanceTitle(),
version=version.inventreeVersion()
))
return _(f"{version.inventreeInstanceTitle()} v{version.inventreeVersion()}")
return version.inventreeVersion()

View File

@ -239,7 +239,7 @@ class PartImport(FileManagementFormView):
# check if there's a category assigned, if not skip this part or else bad things happen
if not optional_matches['Category']:
import_error.append(_("Can't import part {name} because there is no category assigned").format(name=new_part.name))
import_error.append(_(f"Can't import part {new_part.name} because there is no category assigned"))
continue
try:
@ -260,7 +260,7 @@ class PartImport(FileManagementFormView):
# Set alerts
if import_done:
alert = f"<strong>{_('Part-Import')}</strong><br>{_('Imported {n} parts').format(n=import_done)}"
alert = f"<strong>{_('Part-Import')}</strong><br>{_(f'Imported {import_done} parts')}"
messages.success(self.request, alert)
if import_error:
error_text = '\n'.join([f'<li><strong>{import_error.count(a)}</strong>: {a}</li>' for a in set(import_error)])

View File

@ -28,7 +28,7 @@ from plugin.registry import registry
try:
from django_weasyprint import WeasyTemplateResponseMixin
except OSError as err: # pragma: no cover
print("OSError: {e}".format(e=err))
print(f"OSError: {err}")
print("You may require some further system packages to be installed.")
sys.exit(1)
@ -116,7 +116,7 @@ class ReportBase(models.Model):
def __str__(self):
"""Format a string representation of a report instance"""
return "{n} - {d}".format(n=self.name, d=self.description)
return f"{self.name} - {self.description}"
@classmethod
def getSubdir(cls):

View File

@ -847,10 +847,7 @@ class StockList(APIDownloadMixin, ListCreateDestroyAPIView):
filedata = dataset.export(export_format)
filename = 'InvenTree_StockItems_{date}.{fmt}'.format(
date=datetime.now().strftime("%d-%b-%Y"),
fmt=export_format
)
filename = f'InvenTree_StockItems_{datetime.now().strftime("%d-%b-%Y")}.{export_format}'
return DownloadFile(filedata, filename)

View File

@ -662,9 +662,7 @@ class StockItem(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, commo
try:
if self.supplier_part is not None:
if self.supplier_part.part != self.part:
raise ValidationError({'supplier_part': _("Part type ('{pf}') must be {pe}").format(
pf=str(self.supplier_part.part),
pe=str(self.part))
raise ValidationError({'supplier_part': _(f"Part type ('{self.supplier_part.part}') must be {self.part}")
})
if self.part is not None:
@ -1451,7 +1449,7 @@ class StockItem(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, commo
raise ValidationError({"quantity": _("Quantity must be greater than zero")})
if quantity > self.quantity:
raise ValidationError({"quantity": _("Quantity must not exceed available stock quantity ({n})").format(n=self.quantity)})
raise ValidationError({"quantity": _(f"Quantity must not exceed available stock quantity ({self.quantity})")})
if type(serials) not in [list, tuple]:
raise ValidationError({"serial_numbers": _("Serial numbers must be a list of integers")})
@ -1950,21 +1948,15 @@ class StockItem(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, commo
def __str__(self):
"""Human friendly name."""
if self.part.trackable and self.serial:
s = '{part} #{sn}'.format(
part=self.part.full_name,
sn=self.serial)
s = f'{self.part.full_name} #{self.serial}'
else:
s = '{n} x {part}'.format(
n=InvenTree.helpers.decimal2string(self.quantity),
part=self.part.full_name)
s = f'{InvenTree.helpers.decimal2string(self.quantity)} x {self.part.full_name}'
if self.location:
s += ' @ {loc}'.format(loc=self.location.name)
s += f' @ {self.location.name}'
if self.purchase_order:
s += " ({po})".format(
po=self.purchase_order,
)
s += f" ({self.purchase_order})"
return s
@ -2227,7 +2219,7 @@ class StockItemTracking(models.Model):
def get_absolute_url(self):
"""Return url for instance."""
return '/stock/track/{pk}'.format(pk=self.id)
return f'/stock/track/{self.id}'
def label(self):
"""Return label."""

View File

@ -1,4 +1,3 @@
import { t } from '@lingui/macro';
import { Select } from '@mantine/core';
import { UseFormReturnType } from '@mantine/form';
import { useId } from '@mantine/hooks';

View File

@ -1,5 +1,5 @@
import { t } from '@lingui/macro';
import { Anchor, Image } from '@mantine/core';
import { Anchor } from '@mantine/core';
import { Group } from '@mantine/core';
import { Text } from '@mantine/core';
import { useMemo } from 'react';

View File

@ -1,5 +1,5 @@
import { Group, Text } from '@mantine/core';
import { IconFileTypeJpg, IconPhoto } from '@tabler/icons-react';
import { IconPhoto } from '@tabler/icons-react';
import {
IconFile,
IconFileTypeCsv,

View File

@ -1,4 +1,4 @@
import { Anchor, SimpleGrid, Text, UnstyledButton } from '@mantine/core';
import { SimpleGrid, Text, UnstyledButton } from '@mantine/core';
import React from 'react';
import { Link } from 'react-router-dom';

View File

@ -11,7 +11,6 @@ import {
import { Group, Stack, Text } from '@mantine/core';
import { IconBellCheck, IconBellPlus } from '@tabler/icons-react';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../../App';

View File

@ -6,7 +6,7 @@ import { useMemo } from 'react';
import { api } from '../../App';
import { openModalApiForm } from '../../functions/forms';
import { ApiPaths, apiUrl } from '../../states/ApiState';
import { apiUrl } from '../../states/ApiState';
import { SettingsStateProps } from '../../states/SettingsState';
import { Setting } from '../../states/states';

View File

@ -1,4 +1,4 @@
import { LoadingOverlay, Stack, Text } from '@mantine/core';
import { Stack, Text } from '@mantine/core';
import { useEffect } from 'react';
import {

View File

@ -1,10 +1,7 @@
import { Trans, t } from '@lingui/macro';
import { ActionIcon, Divider, Group, Menu, Select } from '@mantine/core';
import { t } from '@lingui/macro';
import { ActionIcon, Menu } from '@mantine/core';
import { Tooltip } from '@mantine/core';
import { Button, Modal, Stack } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { IconDownload } from '@tabler/icons-react';
import { useState } from 'react';
export function DownloadAction({
downloadCallback

View File

@ -1,5 +1,5 @@
import { t } from '@lingui/macro';
import { Modal, Space } from '@mantine/core';
import { Modal } from '@mantine/core';
import { Select } from '@mantine/core';
import { Stack } from '@mantine/core';
import { Button, Group, Text } from '@mantine/core';

View File

@ -1,5 +1,3 @@
import { t } from '@lingui/macro';
import { HostList } from '../states/states';
export const defaultHostList: HostList = window.INVENTREE_SETTINGS.server_list;

View File

@ -1,5 +1,4 @@
import { Trans, t } from '@lingui/macro';
import { Image, Text } from '@mantine/core';
import { Trans } from '@lingui/macro';
import { MenuLinkItem } from '../components/items/MenuLinks';
import { IS_DEV_OR_DEMO } from '../main';

View File

@ -1,9 +1,6 @@
import { t } from '@lingui/macro';
import {
ApiFormFieldSet,
ApiFormFieldType
} from '../../components/forms/fields/ApiFormField';
import { ApiFormFieldSet } from '../../components/forms/fields/ApiFormField';
import { ApiPaths } from '../../states/ApiState';
import { openCreateApiForm, openEditApiForm } from '../forms';

View File

@ -3,8 +3,7 @@ import { t } from '@lingui/macro';
import {
ApiFormChangeCallback,
ApiFormData,
ApiFormFieldSet,
ApiFormFieldType
ApiFormFieldSet
} from '../../components/forms/fields/ApiFormField';
import { ApiPaths } from '../../states/ApiState';
import { openCreateApiForm, openEditApiForm } from '../forms';

View File

@ -5,7 +5,6 @@ import { Accordion } from '@mantine/core';
import { ReactNode, useState } from 'react';
import { ApiFormProps } from '../../components/forms/ApiForm';
import { ApiFormChangeCallback } from '../../components/forms/fields/ApiFormField';
import { PlaceholderPill } from '../../components/items/Placeholder';
import { StylishText } from '../../components/items/StylishText';
import { ModelType } from '../../components/render/ModelType';

View File

@ -7,7 +7,7 @@ import { PageDetail } from '../../components/nav/PageDetail';
import { PanelGroup, PanelType } from '../../components/nav/PanelGroup';
import { PluginListTable } from '../../components/tables/plugin/PluginListTable';
import { useInstance } from '../../hooks/UseInstance';
import { ApiPaths, apiUrl } from '../../states/ApiState';
import { ApiPaths } from '../../states/ApiState';
/**
* Plugins settings page

View File

@ -5,11 +5,9 @@ import {
IconListDetails,
IconSitemap
} from '@tabler/icons-react';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { api } from '../../App';
import { PlaceholderPanel } from '../../components/items/Placeholder';
import { PageDetail } from '../../components/nav/PageDetail';
import { PanelGroup, PanelType } from '../../components/nav/PanelGroup';

View File

@ -6,7 +6,7 @@ import { ModelType } from '../components/render/ModelType';
import { StatusCodeListInterface } from '../components/renderers/StatusRenderer';
import { statusCodeList } from '../defaults/backendMappings';
import { emptyServerAPI } from '../defaults/defaults';
import { ServerAPIProps, UserProps } from './states';
import { ServerAPIProps } from './states';
type StatusLookup = Record<ModelType, StatusCodeListInterface>;