Big pile of minor code cleanups

This commit is contained in:
2022-01-12 20:54:32 +00:00
parent 3abb73872b
commit e002ab7bed
13 changed files with 78 additions and 77 deletions

View File

@@ -84,7 +84,7 @@ class BootstrapSelectElement(Region):
return [self.BootstrapSelectOption(self, i) for i in options] return [self.BootstrapSelectOption(self, i) for i in options]
def set_option(self, name, selected): def set_option(self, name, selected):
options = list((x for x in self.options if x.name == name)) options = [x for x in self.options if x.name == name]
assert len(options) == 1 assert len(options) == 1
options[0].set_selected(selected) options[0].set_selected(selected)

View File

@@ -24,7 +24,7 @@ class InvoiceIndex(generic.ListView):
template_name = 'invoice_list.html' template_name = 'invoice_list.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(InvoiceIndex, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
total = 0 total = 0
for i in context['object_list']: for i in context['object_list']:
total += i.balance total += i.balance
@@ -41,8 +41,9 @@ class InvoiceDetail(generic.DetailView):
template_name = 'invoice_detail.html' template_name = 'invoice_detail.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(InvoiceDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['page_title'] = "Invoice {} ({}) ".format(self.object.display_id, self.object.invoice_date.strftime("%d/%m/%Y")) invoice_date = self.object.invoice_date.strftime("%d/%m/%Y")
context['page_title'] = f"Invoice {self.object.display_id} ({invoice_date}) "
if self.object.void: if self.object.void:
context['page_title'] += "<span class='badge badge-warning float-right'>VOID</span>" context['page_title'] += "<span class='badge badge-warning float-right'>VOID</span>"
elif self.object.is_closed: elif self.object.is_closed:
@@ -117,7 +118,7 @@ class InvoiceArchive(generic.ListView):
paginate_by = 25 paginate_by = 25
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(InvoiceArchive, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['page_title'] = "Invoice Archive" context['page_title'] = "Invoice Archive"
context['description'] = "This page displays all invoices: outstanding, paid, and void" context['description'] = "This page displays all invoices: outstanding, paid, and void"
return context return context
@@ -196,7 +197,7 @@ class PaymentCreate(generic.CreateView):
template_name = 'payment_form.html' template_name = 'payment_form.html'
def get_initial(self): def get_initial(self):
initial = super(generic.CreateView, self).get_initial() initial = super().get_initial()
invoicepk = self.request.GET.get('invoice', self.request.POST.get('invoice', None)) invoicepk = self.request.GET.get('invoice', self.request.POST.get('invoice', None))
if invoicepk is None: if invoicepk is None:
raise Http404() raise Http404()

View File

@@ -97,10 +97,10 @@ class EventForm(forms.ModelForm):
raise forms.ValidationError( raise forms.ValidationError(
'You haven\'t provided any client contact details. Please add a person or organisation.', 'You haven\'t provided any client contact details. Please add a person or organisation.',
code='contact') code='contact')
return super(EventForm, self).clean() return super().clean()
def save(self, commit=True): def save(self, commit=True):
m = super(EventForm, self).save(commit=False) m = super().save(commit=False)
if (commit): if (commit):
m.save() m.save()
@@ -139,7 +139,7 @@ class BaseClientEventAuthorisationForm(forms.ModelForm):
class InternalClientEventAuthorisationForm(BaseClientEventAuthorisationForm): class InternalClientEventAuthorisationForm(BaseClientEventAuthorisationForm):
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(InternalClientEventAuthorisationForm, self).__init__(**kwargs) super().__init__(**kwargs)
self.fields['uni_id'].required = True self.fields['uni_id'].required = True
self.fields['account_code'].required = True self.fields['account_code'].required = True
@@ -154,7 +154,7 @@ class EventAuthorisationRequestForm(forms.Form):
class EventRiskAssessmentForm(forms.ModelForm): class EventRiskAssessmentForm(forms.ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(EventRiskAssessmentForm, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
for name, field in self.fields.items(): for name, field in self.fields.items():
if str(name) == 'supervisor_consulted': if str(name) == 'supervisor_consulted':
field.widget = forms.CheckboxInput() field.widget = forms.CheckboxInput()
@@ -185,7 +185,7 @@ class EventRiskAssessmentForm(forms.ModelForm):
class EventChecklistForm(forms.ModelForm): class EventChecklistForm(forms.ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(EventChecklistForm, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.fields['date'].widget.format = '%Y-%m-%d' self.fields['date'].widget.format = '%Y-%m-%d'
for name, field in self.fields.items(): for name, field in self.fields.items():
if field.__class__ == forms.NullBooleanField: if field.__class__ == forms.NullBooleanField:

View File

@@ -69,7 +69,7 @@ class Profile(AbstractUser):
return self.name return self.name
class RevisionMixin(object): class RevisionMixin:
@property @property
def is_first_version(self): def is_first_version(self):
versions = Version.objects.get_for_object(self) versions = Version.objects.get_for_object(self)

View File

@@ -38,7 +38,7 @@ class RigboardIndex(generic.TemplateView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# get super context # get super context
context = super(RigboardIndex, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
# call out method to get current events # call out method to get current events
context['events'] = models.Event.objects.current_events().select_related('riskassessment', 'invoice').prefetch_related('checklists') context['events'] = models.Event.objects.current_events().select_related('riskassessment', 'invoice').prefetch_related('checklists')
@@ -50,7 +50,7 @@ class WebCalendar(generic.TemplateView):
template_name = 'calendar.html' template_name = 'calendar.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(WebCalendar, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['view'] = kwargs.get('view', '') context['view'] = kwargs.get('view', '')
context['date'] = kwargs.get('date', '') context['date'] = kwargs.get('date', '')
return context return context
@@ -61,8 +61,8 @@ class EventDetail(generic.DetailView):
model = models.Event model = models.Event
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(EventDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
title = "{} | {}".format(self.object.display_id, self.object.name) title = f"{self.object.display_id} | {self.object.name}"
if self.object.dry_hire: if self.object.dry_hire:
title += " <span class='badge badge-secondary'>Dry Hire</span>" title += " <span class='badge badge-secondary'>Dry Hire</span>"
context['page_title'] = title context['page_title'] = title
@@ -84,7 +84,7 @@ class EventCreate(generic.CreateView):
template_name = 'event_form.html' template_name = 'event_form.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(EventCreate, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['page_title'] = "New Event" context['page_title'] = "New Event"
context['edit'] = True context['edit'] = True
context['currentVAT'] = models.VatRate.objects.current_rate() context['currentVAT'] = models.VatRate.objects.current_rate()
@@ -110,8 +110,8 @@ class EventUpdate(generic.UpdateView):
template_name = 'event_form.html' template_name = 'event_form.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(EventUpdate, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['page_title'] = "Event {}".format(self.object.display_id) context['page_title'] = f"Event {self.object.display_id}"
context['edit'] = True context['edit'] = True
form = context['form'] form = context['form']
@@ -134,7 +134,7 @@ class EventUpdate(generic.UpdateView):
if hasattr(self.object, 'authorised'): if hasattr(self.object, 'authorised'):
messages.warning(self.request, messages.warning(self.request,
'This event has already been authorised by the client, any changes to the price will require reauthorisation.') 'This event has already been authorised by the client, any changes to the price will require reauthorisation.')
return super(EventUpdate, self).render_to_response(context, **response_kwargs) return super().render_to_response(context, **response_kwargs)
def get_success_url(self): def get_success_url(self):
return reverse_lazy('event_detail', kwargs={'pk': self.object.pk}) return reverse_lazy('event_detail', kwargs={'pk': self.object.pk})
@@ -142,7 +142,7 @@ class EventUpdate(generic.UpdateView):
class EventDuplicate(EventUpdate): class EventDuplicate(EventUpdate):
def get_object(self, queryset=None): def get_object(self, queryset=None):
old = super(EventDuplicate, self).get_object(queryset) # Get the object (the event you're duplicating) old = super().get_object(queryset) # Get the object (the event you're duplicating)
new = copy.copy(old) # Make a copy of the object in memory new = copy.copy(old) # Make a copy of the object in memory
new.based_on = old # Make the new event based on the old event new.based_on = old # Make the new event based on the old event
new.purchase_order = None # Remove old PO new.purchase_order = None # Remove old PO
@@ -167,8 +167,8 @@ class EventDuplicate(EventUpdate):
return new return new
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(EventDuplicate, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['page_title'] = "Duplicate of Event {}".format(self.object.display_id) context['page_title'] = f"Duplicate of Event {self.object.display_id}"
context["duplicate"] = True context["duplicate"] = True
return context return context
@@ -210,8 +210,7 @@ class EventArchive(generic.ListView):
paginate_by = 25 paginate_by = 25
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# get super context context = super().get_context_data(**kwargs)
context = super(EventArchive, self).get_context_data(**kwargs)
context['start'] = self.request.GET.get('start', None) context['start'] = self.request.GET.get('start', None)
context['end'] = self.request.GET.get('end', datetime.date.today().strftime('%Y-%m-%d')) context['end'] = self.request.GET.get('end', datetime.date.today().strftime('%Y-%m-%d'))
@@ -266,7 +265,7 @@ class EventArchive(generic.ListView):
# Preselect related for efficiency # Preselect related for efficiency
qs.select_related('person', 'organisation', 'venue', 'mic') qs.select_related('person', 'organisation', 'venue', 'mic')
if len(qs) == 0: if not qs.exists():
messages.add_message(self.request, messages.WARNING, "No events have been found matching those criteria.") messages.add_message(self.request, messages.WARNING, "No events have been found matching those criteria.")
return qs return qs
@@ -283,7 +282,7 @@ class EventAuthorise(generic.UpdateView):
self.template_name = self.success_template self.template_name = self.success_template
messages.add_message(self.request, messages.SUCCESS, messages.add_message(self.request, messages.SUCCESS,
'Success! Your event has been authorised. ' + 'Success! Your event has been authorised. ' +
'You will also receive email confirmation to %s.' % self.object.email) f'You will also receive email confirmation to {self.object.email}.')
return self.render_to_response(self.get_context_data()) return self.render_to_response(self.get_context_data())
@property @property
@@ -297,10 +296,10 @@ class EventAuthorise(generic.UpdateView):
return forms.InternalClientEventAuthorisationForm return forms.InternalClientEventAuthorisationForm
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(EventAuthorise, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['event'] = self.event context['event'] = self.event
context['tos_url'] = settings.TERMS_OF_HIRE_URL context['tos_url'] = settings.TERMS_OF_HIRE_URL
context['page_title'] = "{}: {}".format(self.event.display_id, self.event.name) context['page_title'] = f"{self.event.display_id}: {self.event.name}"
if self.event.dry_hire: if self.event.dry_hire:
context['page_title'] += ' <span class="badge badge-secondary align-top">Dry Hire</span>' context['page_title'] += ' <span class="badge badge-secondary align-top">Dry Hire</span>'
context['preview'] = self.preview context['preview'] = self.preview
@@ -319,7 +318,7 @@ class EventAuthorise(generic.UpdateView):
return super(EventAuthorise, self).get(request, *args, **kwargs) return super(EventAuthorise, self).get(request, *args, **kwargs)
def get_form(self, **kwargs): def get_form(self, **kwargs):
form = super(EventAuthorise, self).get_form(**kwargs) form = super().get_form(**kwargs)
form.instance.event = self.event form.instance.event = self.event
form.instance.email = self.request.email form.instance.email = self.request.email
form.instance.sent_by = self.request.sent_by form.instance.sent_by = self.request.sent_by
@@ -335,7 +334,7 @@ class EventAuthorise(generic.UpdateView):
except (signing.BadSignature, AssertionError, KeyError, models.Profile.DoesNotExist): except (signing.BadSignature, AssertionError, KeyError, models.Profile.DoesNotExist):
raise SuspiciousOperation( raise SuspiciousOperation(
"This URL is invalid. Please ask your TEC contact for a new URL") "This URL is invalid. Please ask your TEC contact for a new URL")
return super(EventAuthorise, self).dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
class EventAuthorisationRequest(generic.FormView, generic.detail.SingleObjectMixin): class EventAuthorisationRequest(generic.FormView, generic.detail.SingleObjectMixin):
@@ -345,7 +344,7 @@ class EventAuthorisationRequest(generic.FormView, generic.detail.SingleObjectMix
@method_decorator(decorators.nottinghamtec_address_required) @method_decorator(decorators.nottinghamtec_address_required)
def dispatch(self, *args, **kwargs): def dispatch(self, *args, **kwargs):
return super(EventAuthorisationRequest, self).dispatch(*args, **kwargs) return super().dispatch(*args, **kwargs)
@property @property
def object(self): def object(self):
@@ -406,13 +405,13 @@ class EventAuthoriseRequestEmailPreview(generic.DetailView):
def render_to_response(self, context, **response_kwargs): def render_to_response(self, context, **response_kwargs):
css = finders.find('css/email.css') css = finders.find('css/email.css')
response = super(EventAuthoriseRequestEmailPreview, self).render_to_response(context, **response_kwargs) response = super().render_to_response(context, **response_kwargs)
assert isinstance(response, HttpResponse) assert isinstance(response, HttpResponse)
response.content = premailer.Premailer(response.rendered_content, external_styles=css).transform() response.content = premailer.Premailer(response.rendered_content, external_styles=css).transform()
return response return response
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(EventAuthoriseRequestEmailPreview, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['hmac'] = signing.dumps({ context['hmac'] = signing.dumps({
'pk': self.object.pk, 'pk': self.object.pk,
'email': self.request.GET.get('email', 'hello@world.test'), 'email': self.request.GET.get('email', 'hello@world.test'),

View File

@@ -6,7 +6,7 @@ class PersonList(GenericListView):
model = models.Person model = models.Person
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(PersonList, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['page_title'] = "People" context['page_title'] = "People"
context['create'] = 'person_create' context['create'] = 'person_create'
context['edit'] = 'person_update' context['edit'] = 'person_update'
@@ -19,7 +19,7 @@ class PersonDetail(GenericDetailView):
model = models.Person model = models.Person
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(PersonDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['history_link'] = 'person_history' context['history_link'] = 'person_history'
context['detail_link'] = 'person_detail' context['detail_link'] = 'person_detail'
context['update_link'] = 'person_update' context['update_link'] = 'person_update'
@@ -49,7 +49,7 @@ class OrganisationList(GenericListView):
model = models.Organisation model = models.Organisation
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(OrganisationList, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['create'] = 'organisation_create' context['create'] = 'organisation_create'
context['edit'] = 'organisation_update' context['edit'] = 'organisation_update'
context['can_edit'] = self.request.user.has_perm('RIGS.change_organisation') context['can_edit'] = self.request.user.has_perm('RIGS.change_organisation')
@@ -62,7 +62,7 @@ class OrganisationDetail(GenericDetailView):
model = models.Organisation model = models.Organisation
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(OrganisationDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['history_link'] = 'organisation_history' context['history_link'] = 'organisation_history'
context['detail_link'] = 'organisation_detail' context['detail_link'] = 'organisation_detail'
context['update_link'] = 'organisation_update' context['update_link'] = 'organisation_update'
@@ -92,7 +92,7 @@ class VenueList(GenericListView):
model = models.Venue model = models.Venue
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(VenueList, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['create'] = 'venue_create' context['create'] = 'venue_create'
context['edit'] = 'venue_update' context['edit'] = 'venue_update'
context['can_edit'] = self.request.user.has_perm('RIGS.change_venue') context['can_edit'] = self.request.user.has_perm('RIGS.change_venue')
@@ -104,7 +104,7 @@ class VenueDetail(GenericDetailView):
model = models.Venue model = models.Venue
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(VenueDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['history_link'] = 'venue_history' context['history_link'] = 'venue_history'
context['detail_link'] = 'venue_detail' context['detail_link'] = 'venue_detail'
context['update_link'] = 'venue_update' context['update_link'] = 'venue_update'

View File

@@ -79,7 +79,7 @@ class CableType(models.Model):
def __str__(self): def __str__(self):
if self.plug and self.socket: if self.plug and self.socket:
return "%s%s" % (self.plug.description, self.socket.description) return f"{self.plug.description}{self.socket.description}"
else: else:
return "Unknown" return "Unknown"
@@ -148,7 +148,7 @@ class Asset(models.Model, RevisionMixin):
] ]
def __str__(self): def __str__(self):
return "{} | {}".format(self.asset_id, self.description) return f"{self.asset_id} | {self.description}"
def get_absolute_url(self): def get_absolute_url(self):
return reverse('asset_detail', kwargs={'pk': self.asset_id}) return reverse('asset_detail', kwargs={'pk': self.asset_id})

View File

@@ -180,7 +180,7 @@ class TestAssetForm(AutoLoginTest):
def test_asset_edit(self): def test_asset_edit(self):
self.page = pages.AssetEdit(self.driver, self.live_server_url, asset_id=self.parent.asset_id).open() self.page = pages.AssetEdit(self.driver, self.live_server_url, asset_id=self.parent.asset_id).open()
self.assertTrue(self.driver.find_element_by_id('id_asset_id').get_attribute('readonly') is not None) self.assertIsNotNone(self.driver.find_element_by_id('id_asset_id').get_attribute('readonly'))
new_description = "Big Shelf" new_description = "Big Shelf"
self.page.description = new_description self.page.description = new_description
@@ -335,7 +335,7 @@ class TestAssetAudit(AutoLoginTest):
self.assertNotIn(self.asset.asset_id, self.page.assets) self.assertNotIn(self.asset.asset_id, self.page.assets)
def test_audit_list(self): def test_audit_list(self):
self.assertEqual(len(models.Asset.objects.filter(last_audited_at=None)), len(self.page.assets)) self.assertEqual(models.Asset.objects.filter(last_audited_at=None).count(), len(self.page.assets))
asset_row = self.page.assets[0] asset_row = self.page.assets[0]
self.driver.find_element(By.XPATH, "//a[contains(@class,'btn') and contains(., 'Audit')]").click() self.driver.find_element(By.XPATH, "//a[contains(@class,'btn') and contains(., 'Audit')]").click()
self.wait.until(ec.visibility_of_element_located((By.ID, 'modal'))) self.wait.until(ec.visibility_of_element_located((By.ID, 'modal')))

View File

@@ -73,7 +73,7 @@ class AssetList(LoginRequiredMixin, generic.ListView):
return queryset.select_related('category', 'status') return queryset.select_related('category', 'status')
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(AssetList, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["form"] = self.form context["form"] = self.form
if hasattr(self.form, 'cleaned_data'): if hasattr(self.form, 'cleaned_data'):
context["category_filters"] = self.form.cleaned_data.get('category') context["category_filters"] = self.form.cleaned_data.get('category')
@@ -114,7 +114,7 @@ class AssetDetail(LoginRequiredMixin, AssetIDUrlMixin, generic.DetailView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["page_title"] = "Asset {}".format(self.object.display_id) context["page_title"] = f"Asset {self.object.display_id}"
return context return context
@@ -127,7 +127,7 @@ class AssetEdit(LoginRequiredMixin, AssetIDUrlMixin, generic.UpdateView):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["edit"] = True context["edit"] = True
context["connectors"] = models.Connector.objects.all() context["connectors"] = models.Connector.objects.all()
context["page_title"] = "Edit Asset: {}".format(self.object.display_id) context["page_title"] = f"Edit Asset: {self.object.display_id}"
return context return context
def get_success_url(self): def get_success_url(self):
@@ -147,7 +147,7 @@ class AssetCreate(LoginRequiredMixin, generic.CreateView):
form_class = forms.AssetForm form_class = forms.AssetForm
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(AssetCreate, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["create"] = True context["create"] = True
context["connectors"] = models.Connector.objects.all() context["connectors"] = models.Connector.objects.all()
context["page_title"] = "Create Asset" context["page_title"] = "Create Asset"
@@ -174,8 +174,9 @@ class AssetDuplicate(DuplicateMixin, AssetIDUrlMixin, AssetCreate):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["create"] = None context["create"] = None
context["duplicate"] = True context["duplicate"] = True
context['previous_asset_id'] = self.get_object().asset_id old_id = self.get_object().asset_id
context["page_title"] = "Duplication of Asset: {}".format(context['previous_asset_id']) context['previous_asset_id'] = old_id
context["page_title"] = f"Duplication of Asset: {old_id}"
return context return context
@@ -198,7 +199,7 @@ class AssetAuditList(AssetList):
return self.model.objects.filter(Q(last_audited_at__isnull=True)).select_related('category', 'status') return self.model.objects.filter(Q(last_audited_at__isnull=True)).select_related('category', 'status')
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(AssetAuditList, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['page_title'] = "Asset Audit List" context['page_title'] = "Asset Audit List"
return context return context
@@ -209,7 +210,7 @@ class AssetAudit(AssetEdit):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["page_title"] = "Audit Asset: {}".format(self.object.display_id) context["page_title"] = f"Audit Asset: {self.object.display_id}"
return context return context
def get_success_url(self): def get_success_url(self):
@@ -226,7 +227,7 @@ class SupplierList(GenericListView):
ordering = ['name'] ordering = ['name']
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(SupplierList, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['create'] = 'supplier_create' context['create'] = 'supplier_create'
context['edit'] = 'supplier_update' context['edit'] = 'supplier_update'
context['can_edit'] = self.request.user.has_perm('assets.change_supplier') context['can_edit'] = self.request.user.has_perm('assets.change_supplier')
@@ -253,7 +254,7 @@ class SupplierDetail(GenericDetailView):
model = models.Supplier model = models.Supplier
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(SupplierDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['history_link'] = 'supplier_history' context['history_link'] = 'supplier_history'
context['update_link'] = 'supplier_update' context['update_link'] = 'supplier_update'
context['detail_link'] = 'supplier_detail' context['detail_link'] = 'supplier_detail'
@@ -272,7 +273,7 @@ class SupplierCreate(GenericCreateView, ModalURLMixin):
form_class = forms.SupplierForm form_class = forms.SupplierForm
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(SupplierCreate, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
if is_ajax(self.request): if is_ajax(self.request):
context['override'] = "base_ajax.html" context['override'] = "base_ajax.html"
else: else:
@@ -318,8 +319,8 @@ class CableTypeDetail(generic.DetailView):
template_name = 'cable_type_detail.html' template_name = 'cable_type_detail.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(CableTypeDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["page_title"] = "Cable Type {}".format(str(self.object)) context["page_title"] = f"Cable Type {self.object}"
return context return context
@@ -329,7 +330,7 @@ class CableTypeCreate(generic.CreateView):
form_class = forms.CableTypeForm form_class = forms.CableTypeForm
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(CableTypeCreate, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["create"] = True context["create"] = True
context["page_title"] = "Create Cable Type" context["page_title"] = "Create Cable Type"
@@ -345,9 +346,9 @@ class CableTypeUpdate(generic.UpdateView):
form_class = forms.CableTypeForm form_class = forms.CableTypeForm
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(CableTypeUpdate, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["edit"] = True context["edit"] = True
context["page_title"] = "Edit Cable Type" context["page_title"] = f"Edit Cable Type {self.object}"
return context return context
@@ -362,10 +363,10 @@ def generate_label(pk):
font = ImageFont.truetype("static/fonts/OpenSans-Regular.tff", 20) font = ImageFont.truetype("static/fonts/OpenSans-Regular.tff", 20)
obj = get_object_or_404(models.Asset, asset_id=pk) obj = get_object_or_404(models.Asset, asset_id=pk)
asset_id = "Asset: {}".format(obj.asset_id) asset_id = f"Asset: {obj.asset_id}"
if obj.is_cable: if obj.is_cable:
length = "Length: {}m".format(obj.length) length = f"Length: {obj.length}m"
csa = "CSA: {}mm²".format(obj.csa) csa = f"CSA: {obj.csa}mm²"
image = Image.new("RGB", size, white) image = Image.new("RGB", size, white)
logo = Image.open("static/imgs/square_logo.png") logo = Image.open("static/imgs/square_logo.png")

View File

@@ -11,7 +11,7 @@ class QualificationForm(forms.ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
pk = kwargs.pop('pk', None) pk = kwargs.pop('pk', None)
super(QualificationForm, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.fields['trainee'].initial = Profile.objects.get(pk=pk) self.fields['trainee'].initial = Profile.objects.get(pk=pk)
self.fields['date'].widget.format = '%Y-%m-%d' self.fields['date'].widget.format = '%Y-%m-%d'
@@ -39,5 +39,5 @@ class RequirementForm(forms.ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
pk = kwargs.pop('pk', None) pk = kwargs.pop('pk', None)
super(RequirementForm, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.fields['level'].initial = models.TrainingLevel.objects.get(pk=pk) self.fields['level'].initial = models.TrainingLevel.objects.get(pk=pk)

View File

@@ -16,7 +16,7 @@ class ItemList(generic.ListView):
model = models.TrainingItem model = models.TrainingItem
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(ItemList, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["page_title"] = "Training Items" context["page_title"] = "Training Items"
context["categories"] = models.TrainingCategory.objects.all() context["categories"] = models.TrainingCategory.objects.all()
return context return context
@@ -30,7 +30,7 @@ class TraineeDetail(views.ProfileDetail):
return self.model.objects.prefetch_related('qualifications_obtained') return self.model.objects.prefetch_related('qualifications_obtained')
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(TraineeDetail, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
if self.request.user.pk == self.object.pk: if self.request.user.pk == self.object.pk:
context["page_title"] = "Your Training Record" context["page_title"] = "Your Training Record"
else: else:
@@ -127,7 +127,7 @@ class AddQualification(generic.CreateView, ModalURLMixin):
return super().form_valid(form, *args, **kwargs) return super().form_valid(form, *args, **kwargs)
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(AddQualification, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["depths"] = models.TrainingItemQualification.CHOICES context["depths"] = models.TrainingItemQualification.CHOICES
if is_ajax(self.request): if is_ajax(self.request):
context['override'] = "base_ajax.html" context['override'] = "base_ajax.html"
@@ -151,13 +151,13 @@ class EditQualification(generic.UpdateView):
form_class = forms.QualificationForm form_class = forms.QualificationForm
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(EditQualification, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["depths"] = models.TrainingItemQualification.CHOICES context["depths"] = models.TrainingItemQualification.CHOICES
context['page_title'] = "Edit Qualification {} for {}".format(self.object, models.Trainee.objects.get(pk=self.kwargs['pk'])) context['page_title'] = "Edit Qualification {} for {}".format(self.object, models.Trainee.objects.get(pk=self.kwargs['pk']))
return context return context
def get_form_kwargs(self): def get_form_kwargs(self):
kwargs = super(EditQualification, self).get_form_kwargs() kwargs = super().get_form_kwargs()
kwargs['pk'] = self.kwargs['pk'] kwargs['pk'] = self.kwargs['pk']
return kwargs return kwargs
@@ -174,12 +174,12 @@ class AddLevelRequirement(generic.CreateView, ModalURLMixin):
form_class = forms.RequirementForm form_class = forms.RequirementForm
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(AddLevelRequirement, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context["page_title"] = "Add Requirements to Training Level {}".format(models.TrainingLevel.objects.get(pk=self.kwargs['pk'])) context["page_title"] = "Add Requirements to Training Level {}".format(models.TrainingLevel.objects.get(pk=self.kwargs['pk']))
return context return context
def get_form_kwargs(self): def get_form_kwargs(self):
kwargs = super(AddLevelRequirement, self).get_form_kwargs() kwargs = super().get_form_kwargs()
kwargs['pk'] = self.kwargs['pk'] kwargs['pk'] = self.kwargs['pk']
return kwargs return kwargs

View File

@@ -146,7 +146,7 @@ class RIGSVersionTestCase(TestCase):
self.assertFalse(current_version.changes.fields_changed) self.assertFalse(current_version.changes.fields_changed)
self.assertTrue(current_version.changes.anything_changed) self.assertTrue(current_version.changes.anything_changed)
self.assertTrue(diffs[0].old is None) self.assertIsNone(diffs[0].old)
self.assertEqual(diffs[0].new.name, "TI I1") self.assertEqual(diffs[0].new.name, "TI I1")
# Edit the item # Edit the item
@@ -188,4 +188,4 @@ class RIGSVersionTestCase(TestCase):
self.assertTrue(current_version.changes.anything_changed) self.assertTrue(current_version.changes.anything_changed)
self.assertEqual(diffs[0].old.name, "New Name") self.assertEqual(diffs[0].old.name, "New Name")
self.assertTrue(diffs[0].new is None) self.assertIsNone(diffs[0].new)

View File

@@ -13,14 +13,14 @@ from training.models import Trainee
logger = logging.getLogger('tec.pyrigs') logger = logging.getLogger('tec.pyrigs')
class FieldComparison(object): class FieldComparison:
def __init__(self, field=None, old=None, new=None): def __init__(self, field=None, old=None, new=None):
self.field = field self.field = field
self._old = old self._old = old
self._new = new self._new = new
def display_value(self, value): def display_value(self, value):
if (isinstance(self.field, IntegerField) or isinstance(self.field, CharField)) and self.field.choices is not None and len(self.field.choices) > 0: if (isinstance(self.field, (IntegerField, CharField)) and self.field.choices is not None and len(self.field.choices) > 0:
choice = [x[1] for x in self.field.choices if x[0] == value] choice = [x[1] for x in self.field.choices if x[0] == value]
if len(choice) > 0: if len(choice) > 0:
return choice[0] return choice[0]
@@ -71,7 +71,7 @@ class FieldComparison(object):
return outputDiffs return outputDiffs
class ModelComparison(object): class ModelComparison:
def __init__(self, old=None, new=None, version=None, follow=False, excluded_keys=['date_joined']): def __init__(self, old=None, new=None, version=None, follow=False, excluded_keys=['date_joined']):
# recieves two objects of the same model, and compares them. Returns an array of FieldCompare objects # recieves two objects of the same model, and compares them. Returns an array of FieldCompare objects
try: try: