Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions coldfront/core/allocation/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,7 @@ def allocation_status(self, obj):
return obj.allocation.status

def pi(self, obj):
return "{} {} ({})".format(
obj.allocation.project.pi.first_name,
obj.allocation.project.pi.last_name,
obj.allocation.project.pi.username,
)
return f"{obj.allocation.project.pi.first_name} {obj.allocation.project.pi.last_name} ({obj.allocation.project.pi.username})"

def project(self, obj):
return textwrap.shorten(obj.allocation.project.title, width=50)
Expand Down Expand Up @@ -330,7 +326,7 @@ def allocation_status(self, obj):
return obj.allocation.status

def user_info(self, obj):
return "{} {} ({})".format(obj.user.first_name, obj.user.last_name, obj.user.username)
return f"{obj.user.first_name} {obj.user.last_name} ({obj.user.username})"

def resource(self, obj):
return obj.allocation.resources.first()
Expand Down
9 changes: 6 additions & 3 deletions coldfront/core/allocation/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ def __init__(self, request_user, project_pk, *args, **kwargs):
user_query_set = user_query_set.exclude(user=project_obj.pi)
if user_query_set:
self.fields["users"].choices = (
(user.user.username, "%s %s (%s)" % (user.user.first_name, user.user.last_name, user.user.username))
(
user.user.username,
f"{user.user.first_name} {user.user.last_name} ({user.user.username})",
)
for user in user_query_set
)
self.fields["users"].help_text = "<br/>Select users in your project to add to this allocation."
Expand Down Expand Up @@ -229,7 +232,7 @@ def clean(self):
class AllocationChangeForm(forms.Form):
EXTENSION_CHOICES = [(0, "No Extension")]
for choice in ALLOCATION_CHANGE_REQUEST_EXTENSION_DAYS:
EXTENSION_CHOICES.append((choice, "{} days".format(choice)))
EXTENSION_CHOICES.append((choice, f"{choice} days"))

end_date_extension = forms.TypedChoiceField(
label="Request End Date Extension",
Expand Down Expand Up @@ -265,7 +268,7 @@ class Meta:
fields = "__all__"

def __init__(self, *args, **kwargs):
super(AllocationAttributeCreateForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.fields["allocation_attribute_type"].queryset = self.fields["allocation_attribute_type"].queryset.order_by(
Lower("name")
)
37 changes: 13 additions & 24 deletions coldfront/core/allocation/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,7 @@ def get_information(self):
"Allocation attribute '%s' == 0 but has a usage", attribute.allocation_attribute_type.name
)

string = "{}: {}/{} ({} %) <br>".format(
attribute.allocation_attribute_type.name,
attribute.allocationattributeusage.value,
attribute.value,
percent,
)
string = f"{attribute.allocation_attribute_type.name}: {attribute.allocationattributeusage.value}/{attribute.value} ({percent} %) <br>"
html_string += string

return mark_safe(html_string)
Expand Down Expand Up @@ -340,7 +335,7 @@ def has_perm(self, user, perm):
return perm in perms

def __str__(self):
return "%s (%s)" % (self.get_parent_resource.name, self.project.pi)
return f"{self.get_parent_resource.name} ({self.project.pi})"

def get_eula(self):
if self.get_resources_as_list:
Expand Down Expand Up @@ -428,7 +423,7 @@ class AllocationAttributeType(TimeStampedModel):
history = HistoricalRecords()

def __str__(self):
return "%s" % (self.name)
return self.name

class Meta:
ordering = [
Expand Down Expand Up @@ -469,40 +464,34 @@ def clean(self):
.exclude(id=self.pk)
.exists()
):
raise ValidationError(
"'{}' attribute already exists for this allocation.".format(self.allocation_attribute_type)
)
raise ValidationError(f"'{self.allocation_attribute_type}' attribute already exists for this allocation.")

expected_value_type = self.allocation_attribute_type.attribute_type.name.strip()

if expected_value_type == "Int" and not isinstance(literal_eval(self.value), int):
raise ValidationError(
'Invalid Value "%s" for "%s". Value must be an integer.'
% (self.value, self.allocation_attribute_type.name)
f'Invalid Value "{self.value}" for "{self.allocation_attribute_type.name}". Value must be an integer.'
)
elif expected_value_type == "Float" and not (
isinstance(literal_eval(self.value), float) or isinstance(literal_eval(self.value), int)
):
raise ValidationError(
'Invalid Value "%s" for "%s". Value must be a float.'
% (self.value, self.allocation_attribute_type.name)
f'Invalid Value "{self.value}" for "{self.allocation_attribute_type.name}". Value must be a float.'
)
elif expected_value_type == "Yes/No" and self.value not in ["Yes", "No"]:
raise ValidationError(
'Invalid Value "%s" for "%s". Allowed inputs are "Yes" or "No".'
% (self.value, self.allocation_attribute_type.name)
f'Invalid Value "{self.value}" for "{self.allocation_attribute_type.name}". Allowed inputs are "Yes" or "No".'
)
elif expected_value_type == "Date":
try:
datetime.datetime.strptime(self.value.strip(), "%Y-%m-%d")
except ValueError:
raise ValidationError(
'Invalid Value "%s" for "%s". Date must be in format YYYY-MM-DD'
% (self.value, self.allocation_attribute_type.name)
f'Invalid Value "{self.value}" for "{self.allocation_attribute_type.name}". Date must be in format YYYY-MM-DD'
)

def __str__(self):
return "%s" % (self.allocation_attribute_type.name)
return self.allocation_attribute_type.name

def typed_value(self):
"""
Expand Down Expand Up @@ -572,7 +561,7 @@ class AllocationAttributeUsage(TimeStampedModel):
history = HistoricalRecords()

def __str__(self):
return "{}: {}".format(self.allocation_attribute.allocation_attribute_type.name, self.value)
return f"{self.allocation_attribute.allocation_attribute_type.name}: {self.value}"


class AllocationUserStatusChoice(TimeStampedModel):
Expand Down Expand Up @@ -631,7 +620,7 @@ def is_active(self):
return self.status.name == "Active" and self.allocation.status.name in active_allocation_statuses

def __str__(self):
return "%s" % (self.user)
return str(self.user)

class Meta:
verbose_name_plural = "Allocation User Status"
Expand Down Expand Up @@ -711,7 +700,7 @@ def get_parent_resource(self):
return self.allocation.resources.filter(is_allocatable=True).first()

def __str__(self):
return "%s (%s)" % (self.get_parent_resource.name, self.allocation.project.pi)
return f"{self.get_parent_resource.name} ({self.allocation.project.pi})"


class AllocationAttributeChangeRequest(TimeStampedModel):
Expand All @@ -729,4 +718,4 @@ class AllocationAttributeChangeRequest(TimeStampedModel):
history = HistoricalRecords()

def __str__(self):
return "%s" % (self.allocation_attribute.allocation_attribute_type.name)
return str(self.allocation_attribute.allocation_attribute_type.name)
2 changes: 1 addition & 1 deletion coldfront/core/allocation/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def update_statuses():
sub_obj.status = expired_status_choice
sub_obj.save()

logger.info("Allocations set to expired: {}".format(allocations_to_expire.count()))
logger.info(f"Allocations set to expired: {allocations_to_expire.count()}")


def send_eula_reminders():
Expand Down
2 changes: 1 addition & 1 deletion coldfront/core/allocation/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def setUpTestData(cls):

def test_allocation_str(self):
"""test that allocation str method returns correct string"""
allocation_str = "%s (%s)" % (self.allocation.get_parent_resource.name, self.allocation.project.pi)
allocation_str = f"{self.allocation.get_parent_resource.name} ({self.allocation.project.pi})"
self.assertEqual(str(self.allocation), allocation_str)


Expand Down
2 changes: 1 addition & 1 deletion coldfront/core/allocation/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class AllocationListViewTest(AllocationViewBaseTest):
@classmethod
def setUpTestData(cls):
"""Set up users and project for testing"""
super(AllocationListViewTest, cls).setUpTestData()
super().setUpTestData()
cls.additional_allocations = [AllocationFactory() for i in list(range(100))]
for allocation in cls.additional_allocations:
allocation.resources.add(ResourceFactory(name="holylfs09/tier1"))
Expand Down
2 changes: 1 addition & 1 deletion coldfront/core/allocation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def set_allocation_user_status_to_error(allocation_user_pk):


def generate_guauge_data_from_usage(name, value, usage):
label = "%s: %.2f of %.2f" % (name, usage, value)
label = f"{name}: {usage:.2f} of {value:.2f}"

try:
percent = (usage / value) * 100
Expand Down
24 changes: 5 additions & 19 deletions coldfront/core/allocation/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,12 +317,7 @@ def post(self, request, *args, **kwargs):
if action == "auto-approve":
messages.success(
request,
"Allocation to {} has been ACTIVATED for {} {} ({})".format(
allocation_obj.get_parent_resource,
allocation_obj.project.pi.first_name,
allocation_obj.project.pi.last_name,
allocation_obj.project.pi.username,
),
f"Allocation to {allocation_obj.get_parent_resource} has been ACTIVATED for {allocation_obj.project.pi.first_name} {allocation_obj.project.pi.last_name} ({allocation_obj.project.pi.username})",
)
return HttpResponseRedirect(reverse("allocation-request-list"))

Expand Down Expand Up @@ -567,7 +562,8 @@ def get_context_data(self, **kwargs):
order_by = self.request.GET.get("order_by")
if order_by:
direction = self.request.GET.get("direction")
filter_parameters_with_order_by = filter_parameters + "order_by=%s&direction=%s&" % (order_by, direction)
filter_parameters_string = "" if not filter_parameters else filter_parameters
filter_parameters_with_order_by = filter_parameters_string + f"order_by={order_by}&direction={direction}&"
else:
filter_parameters_with_order_by = filter_parameters

Expand Down Expand Up @@ -1814,12 +1810,7 @@ def post(self, request, *args, **kwargs):

messages.success(
request,
"Allocation change request to {} has been DENIED for {} {} ({})".format(
allocation_change_obj.allocation.resources.first(),
allocation_change_obj.allocation.project.pi.first_name,
allocation_change_obj.allocation.project.pi.last_name,
allocation_change_obj.allocation.project.pi.username,
),
f"Allocation change request to {allocation_change_obj.allocation.resources.first()} has been DENIED for {allocation_change_obj.allocation.project.pi.first_name} {allocation_change_obj.allocation.project.pi.last_name} ({allocation_change_obj.allocation.project.pi.username})",
)

send_allocation_customer_email(
Expand Down Expand Up @@ -1894,12 +1885,7 @@ def post(self, request, *args, **kwargs):

messages.success(
request,
"Allocation change request to {} has been APPROVED for {} {} ({})".format(
allocation_change_obj.allocation.get_parent_resource,
allocation_change_obj.allocation.project.pi.first_name,
allocation_change_obj.allocation.project.pi.last_name,
allocation_change_obj.allocation.project.pi.username,
),
f"Allocation change request to {allocation_change_obj.allocation.get_parent_resource} has been APPROVED for {allocation_change_obj.allocation.project.pi.first_name} {allocation_change_obj.allocation.project.pi.last_name} ({allocation_change_obj.allocation.project.pi.username})",
)

allocation_change_approved.send(
Expand Down
42 changes: 15 additions & 27 deletions coldfront/core/attribute_expansion.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def get_attriblist_str(attribute_name, resources=[], allocations=[]):
attriblist attributes are found, we return None.
"""

attriblist_name = "{aname}{suffix}".format(aname=attribute_name, suffix=ATTRIBUTE_EXPANSION_ATTRIBLIST_SUFFIX)
attriblist_name = f"{attribute_name}{ATTRIBUTE_EXPANSION_ATTRIBLIST_SUFFIX}"
attriblist = None

# Check resources first
Expand Down Expand Up @@ -115,9 +115,7 @@ def get_attribute_parameter_value(argument, attribute_parameter_dict, error_text
else:
# Bad string literal
logger.warning(
"Bad string literal '{}' found while processing {}; missing final single quote".format(
argument, error_text
)
f"Bad string literal '{argument}' found while processing {error_text}; missing final single quote"
)
return None

Expand Down Expand Up @@ -167,11 +165,7 @@ def get_attribute_parameter_value(argument, attribute_parameter_dict, error_text
value = float(argument)
return value
except ValueError:
logger.warning(
"Unable to evaluate argument '{arg}' while processing {etxt}, returning None".format(
arg=argument, etxt=error_text
)
)
logger.warning(f"Unable to evaluate argument '{argument}' while processing {error_text}, returning None")
return None

# Should not reach here
Expand Down Expand Up @@ -214,12 +208,12 @@ def process_attribute_parameter_operation(opcode, oldvalue, argument, error_text
"""
# Argument should never be None
if argument is None:
logger.warning("Operator {}= acting on None argument in {}, returning None".format(opcode, error_text))
logger.warning(f"Operator {opcode}= acting on None argument in {error_text}, returning None")
return None
# Assignment and default operations allow oldvalue to be None
if oldvalue is None:
if opcode != ":" and opcode != "|":
logger.warning("Operator {}= acting on oldvalue=None in {}, returning None".format(opcode, error_text))
logger.warning(f"Operator {opcode}= acting on oldvalue=None in {error_text}, returning None")
return None

try:
Expand All @@ -242,9 +236,7 @@ def process_attribute_parameter_operation(opcode, oldvalue, argument, error_text
return newval
else:
logger.warning(
"Operator {}= acting on parameter of type {} in {}, returning None".format(
opcode, type(oldvalue), error_text
)
f"Operator {opcode}= acting on parameter of type {type(oldvalue)} in {error_text}, returning None"
)
return None
if opcode == "-":
Expand All @@ -260,17 +252,13 @@ def process_attribute_parameter_operation(opcode, oldvalue, argument, error_text
if argument == "floor":
newval = math.floor(oldvalue)
else:
logger.error(
"Unrecognized function named {} in {}= for {}, returning None".format(argument, opcode, error_text)
)
logger.error(f"Unrecognized function named {argument} in {opcode}= for {error_text}, returning None")
return None
# If reached here, we do not recognize opcode
logger.error("Unrecognized operation {}= in {}, returning None".format(opcode, error_text))
logger.error(f"Unrecognized operation {opcode}= in {error_text}, returning None")
except Exception:
logger.warning(
"Error performing operator {op}= on oldvalue='{old}' and argument={arg} in {errtext}".format(
op=opcode, old=oldvalue, arg=argument, errtext=error_text
)
f"Error performing operator {opcode}= on oldvalue='{oldvalue}' and argument={argument} in {error_text}"
)
return None

Expand Down Expand Up @@ -320,9 +308,9 @@ def process_attribute_parameter_string(
# No '=' found, so invalid format of parmstr
# Log error and return unmodified attribute_parameter_dict
logger.error(
"Invalid parameter string '{pstr}', no '=', while "
f"Invalid parameter string '{parameter_string}', no '=', while "
"creating attribute parameter dictionary for expanding "
"attribute {aname}".format(aname=attribute_name, pstr=parameter_string)
f"attribute {attribute_name}"
)
return attribute_parameter_dict
pname = tmp[0]
Expand All @@ -338,8 +326,8 @@ def process_attribute_parameter_string(
value = argument
else:
# Extra text to display in diagnostics if error occurs
error_text = "processing attribute_parameter_string={pstr} for expansion of attribute {aname}".format(
pstr=parameter_string, aname=attribute_name
error_text = (
f"processing attribute_parameter_string={parameter_string} for expansion of attribute {attribute_name}"
)
value = get_attribute_parameter_value(
argument=argument,
Expand Down Expand Up @@ -463,7 +451,7 @@ def expand_attribute(raw_value, attribute_name, attriblist_string, resources=[],
# referencing a parameter not defined in apdict to divide by
# zero errors in processing apdict. We just log it and then
# return raw_value
logger.error("Error expanding {aname}: {error}".format(aname=attribute_name, error=xcept))
logger.error(f"Error expanding {attribute_name}: {xcept}")
return raw_value


Expand All @@ -485,7 +473,7 @@ def convert_type(value, type_name, error_text="unknown"):
future "Attribute Expanded ..." types.
"""
if type_name is None:
logger.error("No AttributeType found for {}".format(error_text))
logger.error(f"No AttributeType found for {error_text}")
return value

if type_name.endswith("Text"):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def handle(self, *args, **options):
self.stdout.write("Adding field of science ...")
file_path = os.path.join(app_commands_dir, "data", "field_of_science_data.csv")
FieldOfScience.objects.all().delete()
with open(file_path, "r") as fp:
with open(file_path) as fp:
for line in fp:
pk, parent_id, is_selectable, description, fos_nsf_id, fos_nsf_abbrev, directorate_fos_id = (
line.strip().split("\t")
Expand Down
2 changes: 1 addition & 1 deletion coldfront/core/grant/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class GrantAdmin(SimpleHistoryAdmin):
]

def Project_PI(self, obj):
return "{} {} ({})".format(obj.project.pi.first_name, obj.project.pi.last_name, obj.project.pi.username)
return f"{obj.project.pi.first_name} {obj.project.pi.last_name} ({obj.project.pi.username})"

def Funding_Agency(self, obj):
if obj.funding_agency.name == "Other":
Expand Down
Loading
Loading