diff options
| author | Magnus Hagander | 2018-12-14 13:25:38 +0000 |
|---|---|---|
| committer | Magnus Hagander | 2018-12-14 13:25:38 +0000 |
| commit | 12f7175e1fedccd890ab6d3475b21f2f016fbb03 (patch) | |
| tree | 9b8fdf9a8f0da9b688116786d845f39ae6dc5be0 /postgresqleu | |
| parent | 957224e2f86435b7f84e30b45c21976fd4dab297 (diff) | |
Fix spacing around operators
Diffstat (limited to 'postgresqleu')
68 files changed, 341 insertions, 341 deletions
diff --git a/postgresqleu/accountinfo/views.py b/postgresqleu/accountinfo/views.py index d2d7750d..681bdeae 100644 --- a/postgresqleu/accountinfo/views.py +++ b/postgresqleu/accountinfo/views.py @@ -32,7 +32,7 @@ def search(request): users = user_search(term) # All users need a negative id so we can differentiate them for n in range(0, len(users)): - users[n]['i'] = -1-n + users[n]['i'] = -1 - n return HttpResponse(json.dumps([{'ui': u['i'], 'u': u['u'], 'n': u['f'] + ' ' + u['l'], diff --git a/postgresqleu/accounting/forms.py b/postgresqleu/accounting/forms.py index efa1c114..248f7815 100644 --- a/postgresqleu/accounting/forms.py +++ b/postgresqleu/accounting/forms.py @@ -29,7 +29,7 @@ class JournalItemForm(forms.ModelForm): if self.instance.amount: if self.instance.amount > 0: self.fields['debit'].initial = self.instance.amount - elif self.instance.amount <0: + elif self.instance.amount < 0: self.fields['credit'].initial = -self.instance.amount self.fields['account'].widget.attrs['class'] = 'dropdownbox' self.fields['object'].widget.attrs['class'] = 'dropdownbox' @@ -84,7 +84,7 @@ class JournalItemForm(forms.ModelForm): return 0 debit = self.cleaned_data.has_key('debit') and self.cleaned_data['debit'] or 0 credit = self.cleaned_data.has_key('credit') and self.cleaned_data['credit'] or 0 - return debit-credit + return debit - credit class JournalItemFormset(BaseInlineFormSet): def clean(self): diff --git a/postgresqleu/accounting/models.py b/postgresqleu/accounting/models.py index ab21863d..8cee3bbb 100644 --- a/postgresqleu/accounting/models.py +++ b/postgresqleu/accounting/models.py @@ -5,7 +5,7 @@ def nonzero_validator(value): if value == 0: raise ValidationError("Must be non-zero value!") -ACCOUNT_OBJECT_CHOICES= ( +ACCOUNT_OBJECT_CHOICES = ( (0, "Optional"), (1, "Required"), (2, "Forbidden"), diff --git a/postgresqleu/accounting/util.py b/postgresqleu/accounting/util.py index 60d2f508..61a2d100 100644 --- a/postgresqleu/accounting/util.py +++ b/postgresqleu/accounting/util.py @@ -56,7 +56,7 @@ def create_accounting_entry(date, # We assume the rest is correct and start building the db entries, # since we'll just roll it back if referenced data is missing. - entry = JournalEntry(year=year, seq=seq+1, date=date, closed=False) + entry = JournalEntry(year=year, seq=seq + 1, date=date, closed=False) entry.save() for accountnum, description, amount, objectname in items: diff --git a/postgresqleu/accounting/views.py b/postgresqleu/accounting/views.py index df8bce99..01b1c5e3 100644 --- a/postgresqleu/accounting/views.py +++ b/postgresqleu/accounting/views.py @@ -40,7 +40,7 @@ def _perform_search(request, year): return ('', list(JournalEntry.objects.filter(year=year).order_by('closed', '-date', '-id'))) class EntryPaginator(Paginator): - ENTRIES_PER_PAGE=50 + ENTRIES_PER_PAGE = 50 def __init__(self, entries): return super(EntryPaginator, self).__init__(entries, self.ENTRIES_PER_PAGE) @@ -51,10 +51,10 @@ class EntryPaginator(Paginator): if currentpage < 6: return list(self.page_range)[:10] - elif currentpage > self.num_pages-5: + elif currentpage > self.num_pages - 5: return list(self.page_range)[-10:] else: - return list(self.page_range)[currentpage-5:currentpage-5+10] + return list(self.page_range)[currentpage - 5:currentpage - 5 + 10] else: return self.page_range @@ -102,7 +102,7 @@ def new(request, year): highseq = JournalEntry.objects.filter(year=year).aggregate(Max('seq'))['seq__max'] if highseq is None: highseq = 0 - entry = JournalEntry(year=year, seq=highseq+1, date=d, closed=False) + entry = JournalEntry(year=year, seq=highseq + 1, date=d, closed=False) entry.save() # Disable any search query to make sure we can actually see @@ -126,7 +126,7 @@ def entry(request, entryid): paginator = EntryPaginator(entries) currpage = request.GET.has_key('p') and int(request.GET['p']) or 1 - extra = max(2, 6-entry.journalitem_set.count()) + extra = max(2, 6 - entry.journalitem_set.count()) inlineformset = inlineformset_factory(JournalEntry, JournalItem, JournalItemForm, JournalItemFormset, can_delete=True, extra=extra) inlineurlformset = inlineformset_factory(JournalEntry, JournalUrl, JournalUrlForm, can_delete=True, extra=2, exclude=[]) @@ -157,8 +157,8 @@ def entry(request, entryid): urlformset = inlineurlformset(instance=entry) items = list(entry.journalitem_set.all()) - totals = (sum([i.amount for i in items if i.amount>0]), - -sum([i.amount for i in items if i.amount<0])) + totals = (sum([i.amount for i in items if i.amount > 0]), + -sum([i.amount for i in items if i.amount < 0])) urls = list(entry.journalurl_set.all()) return render(request, 'accounting/main.html', { 'entries': paginator.page(currpage), @@ -284,7 +284,7 @@ def closeyear(request, year): year = Year.objects.get(pk=year) hasopen = JournalEntry.objects.filter(year=year, closed=False).exists() try: - nextyear = Year.objects.get(year=year.year+1) + nextyear = Year.objects.get(year=year.year + 1) hasnext = IncomingBalance.objects.filter(year=nextyear).exists() except Year.DoesNotExist: hasnext = False @@ -327,7 +327,7 @@ SELECT ac.name AS acname, ag.name AS agname, anum, a.name, else: # Ok, let's do this :) # Create a new year if we have to - (nextyear, created) = Year.objects.get_or_create(year=year.year+1, defaults={'isopen':True}) + (nextyear, created) = Year.objects.get_or_create(year=year.year + 1, defaults={'isopen':True}) # Start by transferring this years result IncomingBalance(year=nextyear, @@ -493,13 +493,13 @@ def report(request, year, reporttype): title = 'Results report' totalname = 'Final result' valheaders = ['Amount'] - elif reporttype=='balance': + elif reporttype == 'balance': # Balance report. # We always assume we have an incoming balance and that the previous # year has been closed. If it's not closed, we just show a warning # about that. try: - prevyear = Year.objects.get(year=year.year-1) + prevyear = Year.objects.get(year=year.year - 1) if prevyear and prevyear.isopen: messages.warning(request, 'Previous year (%s) is still open. Incoming balance will be incorrect!' % prevyear.year) except Year.DoesNotExist: diff --git a/postgresqleu/adyen/admin.py b/postgresqleu/adyen/admin.py index d5a01eb8..2b159173 100644 --- a/postgresqleu/adyen/admin.py +++ b/postgresqleu/adyen/admin.py @@ -72,11 +72,11 @@ class AdyenLogAdmin(admin.ModelAdmin): def success(self, obj): return not obj.error - success.boolean=True + success.boolean = True def sentstr(self, obj): return obj.sent and 'Yes' or 'No' - sentstr.short_description='Log sent' + sentstr.short_description = 'Log sent' admin.site.register(RawNotification, RawNotificationAdmin) admin.site.register(Notification, NotificationAdmin) diff --git a/postgresqleu/adyen/management/commands/process_adyen_reports.py b/postgresqleu/adyen/management/commands/process_adyen_reports.py index 2fa638c9..445320f9 100644 --- a/postgresqleu/adyen/management/commands/process_adyen_reports.py +++ b/postgresqleu/adyen/management/commands/process_adyen_reports.py @@ -115,7 +115,7 @@ class Command(BaseCommand): accrows = [ (settings.ACCOUNTING_ADYEN_AUTHORIZED_ACCOUNT, accstr, -trans.amount, None), (settings.ACCOUNTING_ADYEN_PAYABLE_ACCOUNT, accstr, trans.settledamount, None), - (settings.ACCOUNTING_ADYEN_FEE_ACCOUNT, accstr, trans.amount-trans.settledamount, trans.accounting_object), + (settings.ACCOUNTING_ADYEN_FEE_ACCOUNT, accstr, trans.amount - trans.settledamount, trans.accounting_object), ] create_accounting_entry(date.today(), accrows, False) diff --git a/postgresqleu/adyen/management/commands/send_adyen_logreport.py b/postgresqleu/adyen/management/commands/send_adyen_logreport.py index a2069312..6ecdbaa7 100755 --- a/postgresqleu/adyen/management/commands/send_adyen_logreport.py +++ b/postgresqleu/adyen/management/commands/send_adyen_logreport.py @@ -40,7 +40,7 @@ class Command(BaseCommand): sio.getvalue()) def report_unconfirmed_notifications(self): - lines = list(Notification.objects.filter(confirmed=False, receivedat__lt=datetime.now()-timedelta(days=1)).order_by('eventDate')) + lines = list(Notification.objects.filter(confirmed=False, receivedat__lt=datetime.now() - timedelta(days=1)).order_by('eventDate')) if len(lines): sio = StringIO() sio.write("The following notifications have not been confirmed in the Adyen integration.\nThese need to be manually processed and then flagged as confirmed!\n\nThis list only contains unconfirmed events older than 24 hours.\n\n\n") @@ -55,8 +55,8 @@ class Command(BaseCommand): def report_unsettled_transactions(self): # Number of days until we start reporting unsettled transactions - UNSETTLED_THRESHOLD=15 - lines = list(TransactionStatus.objects.filter(settledat__isnull=True, authorizedat__lt=datetime.now()-timedelta(days=UNSETTLED_THRESHOLD)).order_by('authorizedat')) + UNSETTLED_THRESHOLD = 15 + lines = list(TransactionStatus.objects.filter(settledat__isnull=True, authorizedat__lt=datetime.now() - timedelta(days=UNSETTLED_THRESHOLD)).order_by('authorizedat')) if len(lines): sio = StringIO() sio.write("The following payments have been authorized, but not captured for more than %s days.\nThese probably need to be verified manually.\n\n\n" % UNSETTLED_THRESHOLD) diff --git a/postgresqleu/adyen/models.py b/postgresqleu/adyen/models.py index 1465d474..f250f26b 100644 --- a/postgresqleu/adyen/models.py +++ b/postgresqleu/adyen/models.py @@ -59,7 +59,7 @@ class TransactionStatus(models.Model): return self.pspReference class Meta: - verbose_name_plural='Transaction statuses' + verbose_name_plural = 'Transaction statuses' class Refund(models.Model): receivedat = models.DateTimeField(null=False, blank=False, auto_now_add=True) diff --git a/postgresqleu/adyen/util.py b/postgresqleu/adyen/util.py index 1acbfda9..fd54293b 100644 --- a/postgresqleu/adyen/util.py +++ b/postgresqleu/adyen/util.py @@ -252,7 +252,7 @@ def process_new_report(notification): # Just store the fact that this report is available. We'll have an # asynchronous cronjob that downloads and processes the reports. Report(notification=notification, url=notification.reason, processedat=None).save() - notification.confirmed=True + notification.confirmed = True notification.save() @@ -354,7 +354,7 @@ def process_raw_adyen_notification(raw, POST): notification.paymentMethod = POST['paymentMethod'] notification.reason = POST['reason'] try: - notification.amount = Decimal(POST['value'])/100 + notification.amount = Decimal(POST['value']) / 100 except: # Invalid amount, set to -1 AdyenLog(pspReference=notification.pspReference, message='Received invalid amount %s' % POST['value'], error=True).save() diff --git a/postgresqleu/auth.py b/postgresqleu/auth.py index d4a51abc..d861204a 100644 --- a/postgresqleu/auth.py +++ b/postgresqleu/auth.py @@ -57,7 +57,7 @@ def login(request): r = Random.new() iv = r.read(16) encryptor = AES.new(SHA.new(settings.SECRET_KEY).digest()[:16], AES.MODE_CBC, iv) - cipher = encryptor.encrypt(s + ' ' * (16-(len(s) % 16))) # pad to 16 bytes + cipher = encryptor.encrypt(s + ' ' * (16 - (len(s) % 16))) # pad to 16 bytes return HttpResponseRedirect("%s?d=%s$%s" % ( settings.PGAUTH_REDIRECT, @@ -115,7 +115,7 @@ def auth_receive(request): changed = True if user.email != data['e'][0]: user.email = data['e'][0] - changed= True + changed = True if changed: user.save() except User.DoesNotExist: diff --git a/postgresqleu/braintreepayment/admin.py b/postgresqleu/braintreepayment/admin.py index 8fe60ca1..67e71289 100644 --- a/postgresqleu/braintreepayment/admin.py +++ b/postgresqleu/braintreepayment/admin.py @@ -11,11 +11,11 @@ class BraintreeLogAdmin(admin.ModelAdmin): def success(self, obj): return not obj.error - success.boolean=True + success.boolean = True def sentstr(self, obj): return obj.sent and 'Yes' or 'No' - sentstr.short_description='Log sent' + sentstr.short_description = 'Log sent' admin.site.register(BraintreeTransaction, BraintreeTransactionAdmin) admin.site.register(BraintreeLog, BraintreeLogAdmin) diff --git a/postgresqleu/braintreepayment/management/commands/update_braintree_transactions.py b/postgresqleu/braintreepayment/management/commands/update_braintree_transactions.py index 9f4b0c69..9470f313 100755 --- a/postgresqleu/braintreepayment/management/commands/update_braintree_transactions.py +++ b/postgresqleu/braintreepayment/management/commands/update_braintree_transactions.py @@ -98,8 +98,8 @@ class Command(BaseCommand): (settings.ACCOUNTING_BRAINTREE_PAYABLE_ACCOUNT, accstr, -t.amount, None), (settings.ACCOUNTING_BRAINTREE_PAYOUT_ACCOUNT, accstr, t.disbursedamount, None), ] - if t.amount-t.disbursedamount > 0: - accrows.append((settings.ACCOUNTING_BRAINTREE_FEE_ACCOUNT, accstr, t.amount-t.disbursedamount, t.accounting_object)) + if t.amount - t.disbursedamount > 0: + accrows.append((settings.ACCOUNTING_BRAINTREE_FEE_ACCOUNT, accstr, t.amount - t.disbursedamount, t.accounting_object)) create_accounting_entry(date.today(), accrows, False) elif datetime.today() - t.settledat > timedelta(days=10): diff --git a/postgresqleu/confreg/admin.py b/postgresqleu/confreg/admin.py index 46e80905..1bc09297 100644 --- a/postgresqleu/confreg/admin.py +++ b/postgresqleu/confreg/admin.py @@ -140,7 +140,7 @@ class ConferenceRegistrationAdmin(admin.ModelAdmin): list_filter = ['conference', RegtypeListFilter, AdditionalOptionListFilter, ] search_fields = ['email', 'firstname', 'lastname', ] ordering = ['-payconfirmedat', '-created', 'lastname', 'firstname', ] - actions= ['approve_conferenceregistration', 'email_recipients'] + actions = ['approve_conferenceregistration', 'email_recipients'] filter_horizontal = ('additionaloptions',) exclude = ('invoice','bulkpayment',) readonly_fields = ('invoice_link','bulkpayment_link', 'lastmodified', ) @@ -155,12 +155,12 @@ class ConferenceRegistrationAdmin(admin.ModelAdmin): def payconfirmedat_short(self, inst): return inst.payconfirmedat - payconfirmedat_short.short_description="Pay conf" + payconfirmedat_short.short_description = "Pay conf" def created_short(self, inst): return "<nobr>%s</nobr>" % inst.created.strftime("%Y-%m-%d %H:%M") - created_short.allow_tags=True - created_short.short_description="Created" + created_short.allow_tags = True + created_short.short_description = "Created" def invoice_link(self, inst): if inst.invoice: @@ -247,7 +247,7 @@ class ConferenceSessionAdmin(admin.ModelAdmin): list_filter = ['conference', TrackListFilter, 'status', ] search_fields = ['title', ] filter_horizontal = ('speaker',) - actions= ['email_recipients', ] + actions = ['email_recipients', ] def get_queryset(self, request): qs = super(ConferenceSessionAdmin, self).get_queryset(request) diff --git a/postgresqleu/confreg/backendforms.py b/postgresqleu/confreg/backendforms.py index 24ea7d71..854256fa 100644 --- a/postgresqleu/confreg/backendforms.py +++ b/postgresqleu/confreg/backendforms.py @@ -31,8 +31,8 @@ from postgresqleu.confreg.models import valid_status_transitions, get_status_str from backendlookups import GeneralAccountLookup, RegisteredUsersLookup, SpeakerLookup class _NewFormDataField(django.forms.Field): - required=True - widget=django.forms.HiddenInput + required = True + widget = django.forms.HiddenInput class BackendForm(ConcurrentProtectedModelForm): selectize_multiple_fields = None @@ -78,7 +78,7 @@ class BackendForm(ConcurrentProtectedModelForm): # but meh, this isn't used that often so... if self.fieldsets: all_fields = set([f for f in self.fields if not f == '_validator']) - all_fieldsetted_fields = set(reduce(lambda x,y: x+y, [v['fields'] for v in self.fieldsets])) + all_fieldsetted_fields = set(reduce(lambda x,y: x + y, [v['fields'] for v in self.fieldsets])) missing = all_fields.difference(all_fieldsetted_fields) if missing: raise Exception("ERROR: fields %s are not in a fieldset" % ", ".join(missing)) @@ -93,7 +93,7 @@ class BackendForm(ConcurrentProtectedModelForm): if isinstance(v, django.forms.fields.DateTimeField) and not k in self.exclude_date_validators: v.validators.extend([ MinValueValidator(datetime.datetime.combine(self.conference.startdate, datetime.time(0,0,0))), - MaxValueValidator(datetime.datetime.combine(self.conference.enddate+datetime.timedelta(days=1), datetime.time(0,0,0))), + MaxValueValidator(datetime.datetime.combine(self.conference.enddate + datetime.timedelta(days=1), datetime.time(0,0,0))), ]) elif isinstance(v, django.forms.fields.DateField) and not k in self.exclude_date_validators: v.validators.extend([ @@ -301,7 +301,7 @@ class BackendRegistrationTypeForm(BackendForm): 'Sortkey': ['nosearch', ], } defaultsort = [[4, 'asc']] - auto_cascade_delete_to=['registrationtype_days', 'registrationtype_requires_option'] + auto_cascade_delete_to = ['registrationtype_days', 'registrationtype_requires_option'] class Meta: model = RegistrationType @@ -323,7 +323,7 @@ class BackendRegistrationTypeForm(BackendForm): def clean_cost(self): if self.instance and self.instance.cost != self.cleaned_data['cost']: - if self.instance.conferenceregistration_set.filter(Q(payconfirmedat__isnull=False)|Q(invoice__isnull=False)|Q(bulkpayment__isnull=False)).exists(): + if self.instance.conferenceregistration_set.filter(Q(payconfirmedat__isnull=False) | Q(invoice__isnull=False) | Q(bulkpayment__isnull=False)).exists(): raise ValidationError("This registration type has been used, so the cost can no longer be changed") return self.cleaned_data['cost'] @@ -432,7 +432,7 @@ class BackendTransformConferenceDateTimeForm(django.forms.Form): self.source = source self.target = target super(BackendTransformConferenceDateTimeForm, self).__init__(*args, **kwargs) - self.fields['timeshift'].initial = self.source.startdate-self.target.startdate + self.fields['timeshift'].initial = self.source.startdate - self.target.startdate def confirm_value(self): return str(self.cleaned_data['timeshift']) @@ -665,7 +665,7 @@ class BackendFeedbackQuestionForm(BackendForm): class BackendNewDiscountCodeForm(django.forms.Form): - helplink='vouchers#discountcodes' + helplink = 'vouchers#discountcodes' codetype = django.forms.ChoiceField(choices=((1, 'Fixed amount discount'), (2, 'Percentage discount'))) def get_newform_data(self): @@ -690,7 +690,7 @@ class DiscountCodeUserManager(object): return None class BackendDiscountCodeForm(BackendForm): - helplink='vouchers#discountcodes' + helplink = 'vouchers#discountcodes' list_fields = ['code', 'validuntil', 'maxuses'] linked_objects = OrderedDict({ '../../regdashboard/list': DiscountCodeUserManager(), diff --git a/postgresqleu/confreg/backendlookups.py b/postgresqleu/confreg/backendlookups.py index 253c8390..5675aaac 100644 --- a/postgresqleu/confreg/backendlookups.py +++ b/postgresqleu/confreg/backendlookups.py @@ -19,7 +19,7 @@ class LookupBase(object): # or at some point in the future. if not (request.user.is_superuser or Conference.objects.filter(Q(administrators=request.user) | Q(series__administrators=request.user), - startdate__gt=datetime.datetime.now()-datetime.timedelta(days=90)).exists()): + startdate__gt=datetime.datetime.now() - datetime.timedelta(days=90)).exists()): raise PermissionDenied("Access denied.") @classmethod diff --git a/postgresqleu/confreg/backendviews.py b/postgresqleu/confreg/backendviews.py index 4f4b7395..c168b68d 100644 --- a/postgresqleu/confreg/backendviews.py +++ b/postgresqleu/confreg/backendviews.py @@ -126,19 +126,19 @@ def backend_process_form(request, urlname, formclass, id, cancel_url='../', save instance = get_object_or_404(formclass.Meta.model, pk=id, conference=conference) if request.method == 'POST' and not nopostprocess: - extra_error=None + extra_error = None if allow_delete and request.POST['submit'] == 'Delete': if instance.pk: # Are there any associated objects here, by any chance? - collector=NestedObjects(using='default') + collector = NestedObjects(using = 'default') collector.collect([instance,]) to_delete = collector.nested() to_delete.remove(instance) if to_delete: to_delete = [d for d in flatten_list(to_delete[0]) if not d._meta.model_name in formclass.auto_cascade_delete_to] if to_delete: - pieces=[unicode(to_delete[n]) for n in range(0, min(5, len(to_delete))) if not isinstance(to_delete[n], list)] - extra_error=u"This {0} cannot be deleted. It would have resulted in the following other objects also being deleted: {1}".format(formclass.Meta.model._meta.verbose_name,u', '.join(pieces)) + pieces = [unicode(to_delete[n]) for n in range(0, min(5, len(to_delete))) if not isinstance(to_delete[n], list)] + extra_error = u"This {0} cannot be deleted. It would have resulted in the following other objects also being deleted: {1}".format(formclass.Meta.model._meta.verbose_name,u', '.join(pieces)) else: messages.info(request, "{0} {1} deleted.".format(formclass.Meta.model._meta.verbose_name.capitalize(), instance)) instance.delete() @@ -324,7 +324,7 @@ def backend_list_editor(request, urlname, formclass, resturl, allow_new=True, al 'helplink': formclass.helplink, }) - if allow_new and resturl=='new': + if allow_new and resturl == 'new': # This one is more interesting... return backend_process_form(request, urlname, diff --git a/postgresqleu/confreg/feedback.py b/postgresqleu/confreg/feedback.py index 74830369..032d2398 100644 --- a/postgresqleu/confreg/feedback.py +++ b/postgresqleu/confreg/feedback.py @@ -15,8 +15,8 @@ def build_graphdata(question, key, options): def build_feedback_response(question): r = {'question': question.question, 'id': question.id, } - confid=question.conference.id - questionid=question.id + confid = question.conference.id + questionid = question.id if question.isfreetext: # This can actually be either freetext *or* graph! if question.textchoices: diff --git a/postgresqleu/confreg/forms.py b/postgresqleu/confreg/forms.py index 75a7d66d..5d419178 100644 --- a/postgresqleu/confreg/forms.py +++ b/postgresqleu/confreg/forms.py @@ -92,7 +92,7 @@ class ConferenceRegistrationForm(forms.ModelForm): def clean_vouchercode(self): newval = self.cleaned_data.get('vouchercode') - if newval=='': return newval + if newval == '': return newval try: v = PrepaidVoucher.objects.get(vouchervalue=newval, conference=self.instance.conference) @@ -552,8 +552,8 @@ class PrepaidCreateForm(forms.Form): def __init__(self, conference, *args, **kwargs): self.conference = conference super(PrepaidCreateForm, self).__init__(*args, **kwargs) - self.fields['regtype'].queryset=RegistrationType.objects.filter(conference=conference) - self.fields['buyer'].label_from_instance=lambda x: u'{0} {1} <{2}> ({3})'.format(x.first_name, x.last_name, x.email, x.username) + self.fields['regtype'].queryset = RegistrationType.objects.filter(conference = conference) + self.fields['buyer'].label_from_instance = lambda x: u'{0} {1} <{2}> ({3})'.format(x.first_name, x.last_name, x.email, x.username) if not (self.data.has_key('regtype') and self.data.has_key('count') and self.data.get('regtype') and @@ -657,14 +657,14 @@ class WaitlistOfferForm(forms.Form): return l def clean(self): - if len(self.reg_list)==0: + if len(self.reg_list) == 0: raise ValidationError("At least one registration must be selected to make an offer") return self.cleaned_data class WaitlistSendmailForm(forms.Form): - TARGET_ALL=0 - TARGET_OFFERS=1 - TARGET_NOOFFERS=2 + TARGET_ALL = 0 + TARGET_OFFERS = 1 + TARGET_NOOFFERS = 2 TARGET_CHOICES = ( (TARGET_ALL, 'All attendees on waitlist'), @@ -672,10 +672,10 @@ class WaitlistSendmailForm(forms.Form): (TARGET_NOOFFERS, 'Only attendees without active offers'), ) - POSITION_NONE=0 - POSITION_FULL=1 - POSITION_ONLY=2 - POSITION_SIZE=3 + POSITION_NONE = 0 + POSITION_FULL = 1 + POSITION_ONLY = 2 + POSITION_SIZE = 3 POSITION_CHOICES = ( (POSITION_NONE, 'No position information'), (POSITION_FULL, 'Both position and size of waitlist'), diff --git a/postgresqleu/confreg/invoicehandler.py b/postgresqleu/confreg/invoicehandler.py index e14f5b89..8e37a844 100644 --- a/postgresqleu/confreg/invoicehandler.py +++ b/postgresqleu/confreg/invoicehandler.py @@ -223,7 +223,7 @@ class BulkInvoiceProcessor(object): class AddonInvoiceProcessor(object): - can_refund=False + can_refund = False # Process invoices for additional options added to an existing # registration. # diff --git a/postgresqleu/confreg/jinjabadge.py b/postgresqleu/confreg/jinjabadge.py index 8b3d692b..8ae60cc8 100755 --- a/postgresqleu/confreg/jinjabadge.py +++ b/postgresqleu/confreg/jinjabadge.py @@ -30,7 +30,7 @@ def get_color(col): if isinstance(col, unicode) or isinstance(col, str): return colors.getAllNamedColors().get(col) elif isinstance(col, list): - return colors.Color(*map(lambda x: x/255.0, col)) + return colors.Color(*map(lambda x: x / 255.0, col)) else: raise Exception("Unknown color defintion type") @@ -138,7 +138,7 @@ class JinjaBadge(Flowable): style.alignment = alignments[o.get('align', 'left')] p = Paragraph(txt, style) (actualwidth, actualheight) = p.wrap(getmm(o, 'width'), getmm(o, 'height')) - p.drawOn(self.canv, getmm(o, 'x'), self.calc_y(o)+getmm(o, 'height')-actualheight-yoffset) + p.drawOn(self.canv, getmm(o, 'x'), self.calc_y(o) + getmm(o, 'height') - actualheight - yoffset) def escapejson_filter(v): @@ -221,7 +221,7 @@ class JinjaRenderer(object): self.story.append(PageBreak()) def render(self, output): - doc = SimpleDocTemplate(output, pagesize=A4, leftMargin=10*mm, topMargin=5*mm, rightMargin=10*mm, bottomMargin=5*mm) + doc = SimpleDocTemplate(output, pagesize=A4, leftMargin=10 * mm, topMargin=5 * mm, rightMargin=10 * mm, bottomMargin=5 * mm) doc.build(self.story) diff --git a/postgresqleu/confreg/jinjafunc.py b/postgresqleu/confreg/jinjafunc.py index a59d2713..32616230 100644 --- a/postgresqleu/confreg/jinjafunc.py +++ b/postgresqleu/confreg/jinjafunc.py @@ -24,7 +24,7 @@ from postgresqleu.confreg.templatetags.leadingnbsp import leadingnbsp # We use a separate root directory for jinja2 templates, so find that # directory by searching relative to ourselves. -JINJA_TEMPLATE_ROOT=os.path.abspath(os.path.join(os.path.dirname(__file__), '../../template.jinja')) +JINJA_TEMPLATE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../template.jinja')) # Locate the git revision for a repository in the given path, including @@ -65,7 +65,7 @@ def find_git_revision(path): # by including or inheriting templates from other parts of the system. class ConfTemplateLoader(jinja2.FileSystemLoader): # Templates that are whitelisted for inclusion. - WHITELISTED_TEMPLATES=('invoices/userinvoice_spec.html',) + WHITELISTED_TEMPLATES = ('invoices/userinvoice_spec.html',) def __init__(self, conference, roottemplate): self.conference = conference @@ -153,7 +153,7 @@ class ConfSandbox(jinja2.sandbox.SandboxedEnvironment): if hasattr(obj, '_unsafe_attributes'): if attr in getattr(obj, '_unsafe_attributes'): return False - elif modname=='postgresqleu.invoices.util' and obj.__class__.__name__=='InvoicePresentationWrapper': + elif modname == 'postgresqleu.invoices.util' and obj.__class__.__name__ == 'InvoicePresentationWrapper': # This is ugly, but we special-case the invoice information if attr in obj._unsafe_attributes: return False diff --git a/postgresqleu/confreg/management/commands/confreg_frequent_reminders.py b/postgresqleu/confreg/management/commands/confreg_frequent_reminders.py index e04d5873..02e28567 100644 --- a/postgresqleu/confreg/management/commands/confreg_frequent_reminders.py +++ b/postgresqleu/confreg/management/commands/confreg_frequent_reminders.py @@ -35,8 +35,8 @@ class Command(BaseCommand): # Right now that's only twitter reminders, butin the future there cna be # more plugins. for conference in Conference.objects.filter(twitterreminders_active=True, - startdate__lte=datetime.today()+timedelta(days=1), - enddate__gte=datetime.today()-timedelta(days=1)) \ + startdate__lte=datetime.today() + timedelta(days=1), + enddate__gte=datetime.today() - timedelta(days=1)) \ .exclude(twitter_token='') \ .exclude(twitter_secret=''): tw = Twitter(conference) @@ -45,8 +45,8 @@ class Command(BaseCommand): # step here, but that will likely fall apart later with more integrations anyway) for s in ConferenceSession.objects.select_related('room') \ .filter(conference=conference, - starttime__gt=datetime.now()-timedelta(hours=conference.timediff), - starttime__lt=datetime.now()-timedelta(hours=conference.timediff)+timedelta(minutes=15), + starttime__gt=datetime.now() - timedelta(hours=conference.timediff), + starttime__lt=datetime.now() - timedelta(hours=conference.timediff) + timedelta(minutes=15), status=1, reminder_sent=False): for reg in ConferenceRegistration.objects.filter( @@ -66,5 +66,5 @@ class Command(BaseCommand): # ignore that one. Other errors should be shown. print("Failed to send twitter DM to {0}: {1}".format(reg.twittername, err)) - s.reminder_sent=True + s.reminder_sent = True s.save() diff --git a/postgresqleu/confreg/management/commands/confreg_send_reminders.py b/postgresqleu/confreg/management/commands/confreg_send_reminders.py index 45f6c173..55e05e5e 100644 --- a/postgresqleu/confreg/management/commands/confreg_send_reminders.py +++ b/postgresqleu/confreg/management/commands/confreg_send_reminders.py @@ -70,7 +70,7 @@ class Command(BaseCommand): speakers = Speaker.objects.filter(conferencesession__conference=conference, conferencesession__status=3, conferencesession__lastnotifiedstatus=3, - conferencesession__lastnotifiedtime__lt=datetime.now()-timedelta(days=7)).distinct() + conferencesession__lastnotifiedtime__lt=datetime.now() - timedelta(days=7)).distinct() if speakers: whatstr.write("Found {0} unconfirmed talks:\n".format(len(speakers))) @@ -100,7 +100,7 @@ class Command(BaseCommand): def remind_unregistered_speakers(self, whatstr, conference): # Get speakers that are approved but not registered speakers = list(Speaker.objects.raw("SELECT s.* FROM confreg_speaker s WHERE EXISTS (SELECT 1 FROM confreg_conferencesession sess INNER JOIN confreg_conferencesession_speaker css ON css.conferencesession_id=sess.id WHERE sess.conference_id=%s AND css.speaker_id=s.id AND sess.status=1 AND sess.lastnotifiedtime<%s) AND NOT EXISTS (SELECT 1 FROM confreg_conferenceregistration r WHERE r.conference_id=%s AND r.attendee_id=s.user_id AND r.payconfirmedat IS NOT NULL)", - [conference.id, datetime.now()-timedelta(days=7), conference.id])) + [conference.id, datetime.now() - timedelta(days=7), conference.id])) if speakers: whatstr.write("Found {0} unregistered speakers:\n".format(len(speakers))) for speaker in speakers: @@ -145,8 +145,8 @@ class Command(BaseCommand): invoice__isnull=True, bulkpayment__isnull=True, registrationwaitlistentry__isnull=True, - created__lt=datetime.now()-timedelta(days=5), - lastmodified__lt=datetime.now()-timedelta(days=5)) + created__lt=datetime.now() - timedelta(days=5), + lastmodified__lt=datetime.now() - timedelta(days=5)) if regs: whatstr.write("Found {0} unconfirmed registrations that are stalled:\n".format(len(regs))) @@ -182,8 +182,8 @@ class Command(BaseCommand): invoice__isnull=True, bulkpayment__isnull=True, registrationwaitlistentry__isnull=True, - created__lt=datetime.now()-timedelta(days=5), - lastmodified__lt=datetime.now()-timedelta(days=5)) + created__lt=datetime.now() - timedelta(days=5), + lastmodified__lt=datetime.now() - timedelta(days=5)) if regs: multiregs = set([r.registrator for r in regs]) @@ -220,7 +220,7 @@ class Command(BaseCommand): for sess in conference.conferencesession_set.filter(abstract='', status=0, - lastmodified__lt=datetime.now()-timedelta(days=3)): + lastmodified__lt=datetime.now() - timedelta(days=3)): for spk in sess.speaker.all(): send_template_mail(conference.contactaddr, spk.email, @@ -243,7 +243,7 @@ class Command(BaseCommand): speakers = Speaker.objects.filter(conferencesession__conference=conference, conferencesession__status=0, - lastmodified__lt=datetime.now()-timedelta(days=3), + lastmodified__lt=datetime.now() - timedelta(days=3), abstract='', ).distinct() diff --git a/postgresqleu/confreg/mobileviews.py b/postgresqleu/confreg/mobileviews.py index 3e426acd..fc358e12 100644 --- a/postgresqleu/confreg/mobileviews.py +++ b/postgresqleu/confreg/mobileviews.py @@ -20,9 +20,9 @@ import json # When running in debug mode, turn off the appcache because it can be # a real PITA to debug. if settings.DEBUG: - MANIFESTVERSION=None + MANIFESTVERSION = None else: - MANIFESTVERSION=105 + MANIFESTVERSION = 105 def index(request, confname): conference = get_object_or_404(Conference, urlname=confname) diff --git a/postgresqleu/confreg/models.py b/postgresqleu/confreg/models.py index 4459fc4a..303a941d 100644 --- a/postgresqleu/confreg/models.py +++ b/postgresqleu/confreg/models.py @@ -51,9 +51,9 @@ STATUS_CHOICES_LONG = ( (4, "Reserve-listed in case of cancels/changes"), # Reserve list ) def get_status_string(val): - return (t for v,t in STATUS_CHOICES if v==val).next() + return (t for v,t in STATUS_CHOICES if v == val).next() def get_status_string_long(val): - return (t for v,t in STATUS_CHOICES_LONG if v==val).next() + return (t for v,t in STATUS_CHOICES_LONG if v == val).next() valid_status_transitions = { 0: {3: 'Talk approved', 2: 'Talk is rejected', 4: 'Talk added to reserve list'}, @@ -70,7 +70,7 @@ def color_validator(value): raise ValidationError('Color values must be # + 7 characters') for n in range(0,3): try: - int(value[n*2+1:n*2+2+1], 16) + int(value[n * 2 + 1:n * 2 + 2 + 1], 16) except ValueError: raise ValidationError('Invalid value in color specification') @@ -177,7 +177,7 @@ class Conference(models.Model): @property def conferencedatestr(self): - if self.enddate and not self.startdate==self.enddate: + if self.enddate and not self.startdate == self.enddate: return "%s - %s" % ( self.startdate.strftime("%Y-%m-%d"), self.enddate.strftime("%Y-%m-%d") @@ -244,7 +244,7 @@ class RegistrationClass(models.Model): return self.regclass def colortuple(self): - return tuple([int(self.badgecolor[n*2+1:n*2+2+1], 16) for n in range(0,3)]) + return tuple([int(self.badgecolor[n * 2 + 1:n * 2 + 2 + 1], 16) for n in range(0,3)]) @property def bgcolortuplestr(self): @@ -255,7 +255,7 @@ class RegistrationClass(models.Model): def foregroundcolortuple(self): if len(self.badgeforegroundcolor): - return tuple([int(self.badgeforegroundcolor[n*2+1:n*2+2+1], 16) for n in range(0,3)]) + return tuple([int(self.badgeforegroundcolor[n * 2 + 1:n * 2 + 2 + 1], 16) for n in range(0,3)]) else: return None @@ -303,7 +303,7 @@ class RegistrationType(models.Model): specialtype = models.CharField(max_length=5, blank=True, null=True, choices=special_reg_types, verbose_name="Special type") require_phone = models.BooleanField(null=False, blank=False, default=False, help_text="Require phone number to be entered") days = models.ManyToManyField(RegistrationDay, blank=True) - alertmessage =models.TextField(null=False, blank=True, verbose_name="Alert message", help_text="Message shown in popup to user when completing the registration") + alertmessage = models.TextField(null=False, blank=True, verbose_name="Alert message", help_text="Message shown in popup to user when completing the registration") upsell_target = models.BooleanField(null=False, blank=False, default=False, help_text='Is target registration type for upselling in order to add additional options') invoice_autocancel_hours = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1),], verbose_name="Autocancel invoices", help_text="Automatically cancel invoices after this many hours") requires_option = models.ManyToManyField('ConferenceAdditionalOption', blank=True, help_text='Requires at least one of the selected additional options to be picked') @@ -322,7 +322,7 @@ class RegistrationType(models.Model): @property def total_cost(self): if self.conference.vat_registrations: - return "%.2f incl VAT" % (self.cost * (1+self.conference.vat_registrations.vatpercent/Decimal(100.0))) + return "%.2f incl VAT" % (self.cost * (1 + self.conference.vat_registrations.vatpercent / Decimal(100.0))) else: return self.cost @@ -369,7 +369,7 @@ class ConferenceAdditionalOption(models.Model): # it nice for the end user. if self.cost > 0: if self.conference.vat_registrations: - coststr = " (%s %.2f)" % (settings.CURRENCY_ABBREV, self.cost * (1+self.conference.vat_registrations.vatpercent/Decimal(100.0))) + coststr = " (%s %.2f)" % (settings.CURRENCY_ABBREV, self.cost * (1 + self.conference.vat_registrations.vatpercent / Decimal(100.0))) else: coststr = " (%s %s)" % (settings.CURRENCY_ABBREV, self.cost) else: @@ -623,12 +623,12 @@ class Speaker(models.Model): return None def has_abstract(self): - return len(self.abstract)>0 + return len(self.abstract) > 0 has_abstract.boolean = True def has_photo(self): return (self.photofile != None and self.photofile != "") - has_photo.boolean= True + has_photo.boolean = True def __unicode__(self): return self.name @@ -701,7 +701,7 @@ class ConferenceSession(models.Model): @property def skill_level_string(self): - return (t for v,t in SKILL_CHOICES if v==self.skill_level).next() + return (t for v,t in SKILL_CHOICES if v == self.skill_level).next() @property def status_string(self): diff --git a/postgresqleu/confreg/pdfschedule.py b/postgresqleu/confreg/pdfschedule.py index 32fb3679..4d0f9a0d 100644 --- a/postgresqleu/confreg/pdfschedule.py +++ b/postgresqleu/confreg/pdfschedule.py @@ -85,12 +85,12 @@ def build_linear_pdf_schedule(conference, room, tracks, day, colored, pagesize, def _finalize_page(): canvas.setFont("DejaVu Serif", 20) - canvas.drawCentredString(width/2, height-2*cm, "%s - %s" % (room.roomname, lastdate.strftime(titledatefmt))) + canvas.drawCentredString(width / 2, height - 2*cm, "%s - %s" % (room.roomname, lastdate.strftime(titledatefmt))) - t = Table(tbldata, colWidths=[3*cm, width - 3*cm - 2*table_horiz_margin]) + t = Table(tbldata, colWidths=[3*cm, width - 3*cm - 2 * table_horiz_margin]) t.setStyle(TableStyle(tblstyle)) w,h = t.wrapOn(canvas, width, height) - t.drawOn(canvas, table_horiz_margin, height-4*cm-h) + t.drawOn(canvas, table_horiz_margin, height - 4*cm - h) canvas.showPage() for s in sessions: @@ -108,7 +108,7 @@ def build_linear_pdf_schedule(conference, room, tracks, day, colored, pagesize, else: tbldata.extend([(tstr, (Paragraph(s.title, st_title), Paragraph("<i>%s</i>" % s.speaker_list, st_speakers)))]) if colored and s.track and s.track.color: - tblstyle.append(('BACKGROUND', (1,len(tbldata)-1), (1,len(tbldata)-1), s.track.color),) + tblstyle.append(('BACKGROUND', (1,len(tbldata) - 1), (1,len(tbldata) - 1), s.track.color),) _finalize_page() canvas.save() @@ -151,18 +151,18 @@ def build_complete_pdf_schedule(conference, tracks, day, colored, pagesize, orie v['rooms'] = set([s.room for s in v['sessions'] if s.room]) timestampstyle = ParagraphStyle('timestampstyle') - timestampstyle.fontName="DejaVu Serif" + timestampstyle.fontName = "DejaVu Serif" timestampstyle.fontSize = 8 # Now build one page for each day for d in sorted(groupedbyday.keys()): dd = groupedbyday[d] - usableheight = height - 2*2*cm - 1*cm - usablewidth = width - 2*2*cm + usableheight = height - 2 * 2*cm - 1*cm + usablewidth = width - 2 * 2*cm - pagesessions=[] - currentpagesessions=[] + pagesessions = [] + currentpagesessions = [] if pagesperday > 1: # >1 page per day, so we try to find the breakpoints. We do this by locating # cross-schedule sessions at appropriate times, and including those both on @@ -221,7 +221,7 @@ def build_complete_pdf_schedule(conference, tracks, day, colored, pagesize, orie roompos = {} for r in sorted(dd['rooms'], key=lambda x: (x.sortkey, x.roomname)): - canvas.rect(2*cm + len(roompos) * roomwidth, height-4*cm, roomwidth, 1*cm, stroke=1) + canvas.rect(2*cm + len(roompos) * roomwidth, height - 4*cm, roomwidth, 1*cm, stroke=1) canvas.drawCentredString(2*cm + len(roompos) * roomwidth + roomwidth / 2, height - 4*cm + (1*cm-roomtitlefontsize)/2, r.roomname) @@ -281,7 +281,7 @@ def build_complete_pdf_schedule(conference, tracks, day, colored, pagesize, orie while title: for fs in (12,10,9,8): sessionstyle = ParagraphStyle('sessionstyle') - sessionstyle.fontName="DejaVu Serif" + sessionstyle.fontName = "DejaVu Serif" sessionstyle.fontSize = fs speakersize = fs > 8 and 8 or fs - 1 if includespeaker: diff --git a/postgresqleu/confreg/reporting.py b/postgresqleu/confreg/reporting.py index 4f800172..e28b58c8 100644 --- a/postgresqleu/confreg/reporting.py +++ b/postgresqleu/confreg/reporting.py @@ -31,7 +31,7 @@ def timereport(request): report = None try: - report = reporttypes[reporttype-1][1](reporttypes[reporttype-1][0],conferences) + report = reporttypes[reporttype - 1][1](reporttypes[reporttype - 1][0], conferences) report.run() return render(request, 'confreg/timereport.html', { 'form': form, @@ -78,7 +78,7 @@ class MultiConferenceReport(object): (maxday,minday) = self.maxmin() if not maxday: raise ReportException("There are no %s at this conference." % self.title.lower()) - allvals = [range(maxday, minday-1, -1), ] + allvals = [range(maxday, minday - 1, -1), ] self.headers = ['Days'] maxseen = 0 for c in self.conferences: @@ -87,8 +87,8 @@ class MultiConferenceReport(object): self.headers.append(Header(c.conferencename)) maxseen = max(max(myvals), maxseen) - if maxday-minday: - maxpred = float(maxseen)*maxday/(maxday-minday) + if maxday - minday: + maxpred = float(maxseen) * maxday / (maxday - minday) else: maxpred = 10 self.graphdata = zip(*allvals) @@ -114,7 +114,7 @@ class SingleConferenceReport(object): (maxday,minday,startdate) = self.curs.fetchone() if not maxday: raise ReportException("There are no %s at this conference." % self.title.lower()) - allvals = [range(maxday,minday-1,-1), ] + allvals = [range(maxday,minday - 1, -1), ] self.headers = ['Days'] for header, rows in self.fetch_all_data(minday, maxday, startdate): allvals.append([r[0] for r in rows]) diff --git a/postgresqleu/confreg/reports.py b/postgresqleu/confreg/reports.py index b72b6acc..e894c0a9 100644 --- a/postgresqleu/confreg/reports.py +++ b/postgresqleu/confreg/reports.py @@ -110,7 +110,7 @@ class ReportFilter(object): # Filter by speaker state is more complex than the default filter can handle, # so it needs a special implementation. class ReportSpeakerFilter(object): - id='speakerstate' + id = 'speakerstate' def __init__(self, conference): self.conference = conference @@ -191,7 +191,7 @@ class ReportWriterPdf(ReportWriterBase): resp = HttpResponse(content_type='application/pdf') registerFont(TTFont('DejaVu Serif', "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf")) - pagesize = self.orientation=='portrait' and A4 or landscape(A4) + pagesize = self.orientation == 'portrait' and A4 or landscape(A4) doc = SimpleDocTemplate(resp, pagesize=pagesize) story = [] @@ -238,21 +238,21 @@ def build_attendee_report(conference, POST): # Run the query! result = ConferenceRegistration.objects.select_related('shirtsize', 'regtype', 'country', 'conference').filter(q).distinct().order_by(*orderby) - if format=='html': + if format == 'html': writer = ReportWriterHtml(title, borders) - elif format=='pdf': + elif format == 'pdf': writer = ReportWriterPdf(title, borders) writer.set_orientation(orientation) - elif format=='csv': + elif format == 'csv': writer = ReportWriterCsv(title, borders) - elif format=='json': + elif format == 'json': # Don't want to use normal renderer here, since we need to pass # the filtered full objects into the builder (because it needs to # be the same data as the badges get) resp = HttpResponse(content_type='application/json') json.dump([r.safe_export() for r in result], resp, indent=2) return resp - elif format=='badge': + elif format == 'badge': # Can't use a normal renderer here, since we need to actually # pass the full objects into the badge builder. try: diff --git a/postgresqleu/confreg/util.py b/postgresqleu/confreg/util.py index 8555a345..555e02cf 100644 --- a/postgresqleu/confreg/util.py +++ b/postgresqleu/confreg/util.py @@ -76,9 +76,9 @@ def invoicerows_for_registration(reg, update_used_vouchers): else: # Percentage discount. Can be either off the total or just the reg if d.regonly: - discount = reg.regtype.cost*d.discountpercentage/100 + discount = reg.regtype.cost * d.discountpercentage / 100 else: - discount = current_total*d.discountpercentage/100 + discount = current_total * d.discountpercentage / 100 if discount > 0: r.append([' Discount code %s' % d.code, 1, -discount, reg.conference.vat_registrations]) except DiscountCode.DoesNotExist: @@ -207,7 +207,7 @@ def expire_additional_options(reg): # being expired (expects to run within a transaction). # Returns the list of options expired for this particular user. - hours = int(round((datetime.now() - reg.lastmodified).total_seconds()/3600)) + hours = int(round((datetime.now() - reg.lastmodified).total_seconds() / 3600)) expireset = list(reg.additionaloptions.filter(invoice_autocancel_hours__isnull=False, invoice_autocancel_hours__lt=hours)) diff --git a/postgresqleu/confreg/views.py b/postgresqleu/confreg/views.py index 4faff692..5870d1a2 100644 --- a/postgresqleu/confreg/views.py +++ b/postgresqleu/confreg/views.py @@ -354,14 +354,14 @@ def multireg(request, confname, regid=None): pk=regid, conference=conference, registrator=request.user) - redir_root='../' + redir_root = '../' else: reg = ConferenceRegistration(conference=conference, registrator=request.user, created=datetime.now(), regtoken=generate_random_token(), ) - redir_root='./' + redir_root = './' if request.method == 'POST': @@ -537,7 +537,7 @@ def multireg_newinvoice(request, confname): for r in invoicerows: # Calculate the with-vat information for this row if r[3]: - r.append(r[2]*(100+r[3].vatpercent)/Decimal(100)) + r.append(r[2] * (100 + r[3].vatpercent) / Decimal(100)) else: r.append(r[2]) totalcost = sum([r[2] for r in invoicerows]) @@ -733,7 +733,7 @@ def reg_add_options(request, confname): for r in invoicerows: # Calculate the with-vat information for this row if r[3]: - r.append(r[2]*(100+r[3].vatpercent)/Decimal(100)) + r.append(r[2] * (100 + r[3].vatpercent) / Decimal(100)) else: r.append(r[2]) @@ -833,7 +833,7 @@ def feedback(request, confname): # in code here. The number of sessions is always going to be low, so it won't # be too big a performance issue. for s in sessions: - fb = [f for f in feedback if f.session==s] + fb = [f for f in feedback if f.session == s] if len(fb): s.has_given_feedback = True @@ -867,7 +867,7 @@ def feedback_session(request, confname, sessionid): except ConferenceSessionFeedback.DoesNotExist: feedback = ConferenceSessionFeedback() - if request.method=='POST': + if request.method == 'POST': form = ConferenceSessionFeedbackForm(data=request.POST, instance=feedback) if form.is_valid(): feedback = form.save(commit=False) @@ -901,7 +901,7 @@ def feedback_conference(request, confname): # Get all current responses responses = ConferenceFeedbackAnswer.objects.filter(conference=conference, attendee=request.user) - if request.method=='POST': + if request.method == 'POST': form = ConferenceFeedbackForm(data=request.POST, questions=questions, responses=responses) if form.is_valid(): # We've got the data, now write it to the database. @@ -940,17 +940,17 @@ class SessionSet(object): # For old-style rendering, update positions if not s['cross_schedule']: s.update({ - 'leftpos': self.roomwidth()*self.rooms[s['room_id']], - 'toppos': self.timediff_to_y_pixels(s['starttime'], s['firsttime'])+self.headersize, - 'widthpos': self.roomwidth()-2, + 'leftpos': self.roomwidth() * self.rooms[s['room_id']], + 'toppos': self.timediff_to_y_pixels(s['starttime'], s['firsttime']) + self.headersize, + 'widthpos': self.roomwidth() - 2, 'heightpos': self.timediff_to_y_pixels(s['endtime'], s['starttime']), }) else: s.update({ 'leftpos': 0, - 'toppos': self.timediff_to_y_pixels(s['starttime'], s['firsttime'])+self.headersize, + 'toppos': self.timediff_to_y_pixels(s['starttime'], s['firsttime']) + self.headersize, 'widthpos': self.roomwidth() * len(self.rooms) - 2, - 'heightpos': self.timediff_to_y_pixels(s['endtime'], s['starttime'])-2, + 'heightpos': self.timediff_to_y_pixels(s['endtime'], s['starttime']) - 2, }) if 'id' in s: del s['id'] @@ -960,30 +960,30 @@ class SessionSet(object): return self.sessions def schedule_height(self): - return self.timediff_to_y_pixels(self.sessions[0]['lasttime'], self.sessions[0]['firsttime'])+2+self.headersize + return self.timediff_to_y_pixels(self.sessions[0]['lasttime'], self.sessions[0]['firsttime']) + 2 + self.headersize def schedule_width(self): if len(self.rooms): - return self.roomwidth()*len(self.rooms) + return self.roomwidth() * len(self.rooms) else: return 0 def roomwidth(self): if len(self.rooms): - return int(self.totalwidth/len(self.rooms)) + return int(self.totalwidth / len(self.rooms)) else: return 0 def timediff_to_y_pixels(self, t, compareto): - return ((t - compareto).seconds/60)*self.pixelsperminute + return ((t - compareto).seconds / 60) * self.pixelsperminute def allrooms(self): return [{ 'id': id, 'name': self.available_rooms[id]['roomname'], - 'leftpos': self.roomwidth()*self.rooms[id], - 'widthpos': self.roomwidth()-2, - 'heightpos': self.headersize-2, + 'leftpos': self.roomwidth() * self.rooms[id], + 'widthpos': self.roomwidth() - 2, + 'heightpos': self.headersize - 2, 'sessions': list(self.room_sessions(id)), } for id, idx in sorted(self.rooms.items(), key=lambda x: x[1])] @@ -993,7 +993,7 @@ class SessionSet(object): if s['cross_schedule'] or s['room_id'] == roomid: if roomprevsess and roomprevsess['endtime'] < s['starttime']: yield {'empty': True, - 'length': (s['starttime']-roomprevsess['endtime']).total_seconds()/60, + 'length': (s['starttime'] - roomprevsess['endtime']).total_seconds() / 60, } roomprevsess = s yield s @@ -1145,7 +1145,7 @@ def speakerprofile(request, confurlname=None): except Exception: pass - if request.method=='POST': + if request.method == 'POST': # Attempt to save # If this is a new speaker, create an instance for it if not speaker: @@ -1227,7 +1227,7 @@ def callforpapers_edit(request, confname, sessionid): # on the same page. If feedback is still open, we show nothing feedback_fields = ('topic_importance', 'content_quality', 'speaker_knowledge', 'speaker_quality') if is_tester or not conference.feedbackopen: - feedbackdata = [{'key': k, 'title': k.replace('_',' ').title(), 'num': [0]*5} for k in feedback_fields] + feedbackdata = [{'key': k, 'title': k.replace('_',' ').title(), 'num': [0] * 5} for k in feedback_fields] feedbacktext = [] fb = list(ConferenceSessionFeedback.objects.filter(conference=conference, session=session)) feedbackcount = len(fb) @@ -1235,7 +1235,7 @@ def callforpapers_edit(request, confname, sessionid): # Summarize the values for d in feedbackdata: if getattr(f, d['key']) > 0: - d['num'][getattr(f, d['key'])-1] += 1 + d['num'][getattr(f, d['key']) - 1] += 1 # Add the text if necessary if f.speaker_feedback: feedbacktext.append({ @@ -1534,7 +1534,7 @@ def confirmreg(request, confname): # so just redirect back to the page for retry. return HttpResponseRedirect("../") - totalcost = sum([r[2]*(1+(r[3] and r[3].vatpercent or 0)/Decimal(100.0)) for r in invoicerows]) + totalcost = sum([r[2] * (1 + (r[3] and r[3].vatpercent or 0) / Decimal(100.0)) for r in invoicerows]) if len(invoicerows) <= 0: return HttpResponseRedirect("../") @@ -1601,7 +1601,7 @@ def confirmreg(request, confname): for r in invoicerows: # Calculate the with-vat information for this row if r[3]: - r.append(r[2]*(100+r[3].vatpercent)/Decimal(100)) + r.append(r[2] * (100 + r[3].vatpercent) / Decimal(100)) else: r.append(r[2]) @@ -1791,7 +1791,7 @@ def optout(request, token=None): email = request.user.email if request.method == 'POST': - global_optout = request.POST.get('global', '0')=='1' + global_optout = request.POST.get('global', '0') == '1' sids = exec_to_list("SELECT id FROM confreg_conferenceseries") optout_ids = [i for i, in sids if request.POST.get('series_{0}'.format(i), '0') == '1'] @@ -2007,7 +2007,7 @@ def bulkpay(request, confname): allregs.append(regs[0]) else: state.append({'email': e, 'found': 0, 'text': 'Email not found or registration already completed.'}) - errors=1 + errors = 1 # Validate each entry for r in allregs: @@ -2015,26 +2015,26 @@ def bulkpay(request, confname): if r.payconfirmedat: state.append({'email': e, 'found': 1, 'pay': 0, 'text': 'Email not found or registration already completed.'}) - errors=1 + errors = 1 elif r.invoice: state.append({'email': e, 'found': 1, 'pay': 0, 'text': 'This registration already has an invoice generated for individual payment.'}) - errors=1 + errors = 1 elif r.bulkpayment: state.append({'email': e, 'found': 1, 'pay': 0, 'text': 'This registration is already part of a different bulk registration.'}) - errors=1 + errors = 1 elif not (r.regtype and r.regtype.active): state.append({'email': e, 'found': 1, 'pay': 0, 'text': 'Registration type for this registration is not active!'}) - errors=1 + errors = 1 else: # If this is the confirmation step, we flag vouchers as used. # Else we just get the data and generate a confirmation page try: regrows = invoicerows_for_registration(r, confirmstep) - s = sum([r[1]*r[2] for r in regrows]) + s = sum([r[1] * r[2] for r in regrows]) if s == 0: # No payment needed state.append({'email': e, 'found': 1, 'pay': 0, 'text': 'Registration does not need payment'}) - errors=1 + errors = 1 else: # All content is valid, so just append it state.append({'email': regs[0].email, 'found': 1, 'pay': 1, 'total': s, 'rows':[u'%s (%s%s)' % (r[0], settings.CURRENCY_SYMBOL.decode('utf8'), r[2]) for r in regrows]}) @@ -2216,14 +2216,14 @@ def talkvote_status(request, confname): if not isadmin: return HttpResponse('Only admins can change the status') - if request.method!='POST': + if request.method != 'POST': return HttpResponse('Can only use POST') session = get_object_or_404(ConferenceSession, conference=conference, id=request.POST['sessionid']) session.status = int(request.POST['newstatus']) session.save() return HttpResponse("{0};{1}".format(get_status_string(session.status), - session.status!=session.lastnotifiedstatus and 1 or 0, + session.status != session.lastnotifiedstatus and 1 or 0, ), content_type='text/plain') @login_required @@ -2232,7 +2232,7 @@ def talkvote_vote(request, confname): conference = get_object_or_404(Conference, urlname=confname) if not conference.talkvoters.filter(pk=request.user.id): raise PermissionDenied('You are not a talk voter for this conference!') - if request.method!='POST': + if request.method != 'POST': return HttpResponse('Can only use POST') session = get_object_or_404(ConferenceSession, conference=conference, id=request.POST['sessionid']) @@ -2256,7 +2256,7 @@ def talkvote_comment(request, confname): conference = get_object_or_404(Conference, urlname=confname) if not conference.talkvoters.filter(pk=request.user.id): raise PermissionDenied('You are not a talk voter for this conference!') - if request.method!='POST': + if request.method != 'POST': return HttpResponse('Can only use POST') session = get_object_or_404(ConferenceSession, conference=conference, id=request.POST['sessionid']) @@ -2278,7 +2278,7 @@ def createschedule(request, confname): raise PermissionDenied('You are not an administrator or talk voter for this conference!') - if request.method=="POST": + if request.method == "POST": if request.POST.has_key('get'): # Get the current list of tentatively scheduled talks s = {} @@ -2309,7 +2309,7 @@ def createschedule(request, confname): sess.tentativeroom = Room.objects.get(pk=roomid) sess.tentativescheduleslot = ConferenceSessionScheduleSlot.objects.get(pk=slotid) sess.save() - found=True + found = True break if not found: if sess.tentativescheduleslot: @@ -2358,7 +2358,7 @@ def createschedule(request, confname): 'sessions': sessions, 'tracks': tracks, 'sesswidth': min(600 / len(allrooms), 150), - 'availableheight': len(sessions)*75, + 'availableheight': len(sessions) * 75, 'helplink': 'schedule', }) @@ -2474,9 +2474,9 @@ def simple_report(request, confname): @login_required def admin_dashboard(request): if request.user.is_superuser: - conferences = Conference.objects.filter(startdate__gt=datetime.now()-timedelta(days=3*365)).order_by('-startdate') + conferences = Conference.objects.filter(startdate__gt=datetime.now() - timedelta(days=3 * 365)).order_by('-startdate') else: - conferences = Conference.objects.filter(Q(administrators=request.user) | Q(series__administrators=request.user), startdate__gt=datetime.now()-timedelta(days=3*365)).distinct().order_by('-startdate') + conferences = Conference.objects.filter(Q(administrators=request.user) | Q(series__administrators=request.user), startdate__gt=datetime.now() - timedelta(days=3 * 365)).distinct().order_by('-startdate') # Split conferences in three buckets: # Current: anything that starts or finishes within two weeks @@ -2589,8 +2589,8 @@ WHERE dc.conference_id={1} AND (r.conference_id={1} OR r.conference_id IS NULL) sums = ['Total'] for cn in range(1, t['fixedcols']): sums.append('') - for cn in range(t['fixedcols']-1, len(t['columns'])-1): - sums.append(sum((r[cn+1] for r in t['rows'] if r[cn+1] != None))) + for cn in range(t['fixedcols'] - 1, len(t['columns']) - 1): + sums.append(sum((r[cn + 1] for r in t['rows'] if r[cn + 1] != None))) t['rows'] = [(r, t.get('linker', lambda x: None)(r)) for r in t['rows']] t['rows'].append((sums, None)) return render(request, 'confreg/admin_registration_dashboard.html', { @@ -2605,7 +2605,7 @@ def admin_registration_list(request, urlname): skey = request.GET.get('sort', '-date') if skey[0] == '-': revsort = True - skey=skey[1:] + skey = skey[1:] else: revsort = False @@ -3147,7 +3147,7 @@ def crossmail(request): elif t == 'sp': # Speaker if v == '*': - sf="" + sf = "" elif v == '?': sf = " AND status IN (1,3)" else: diff --git a/postgresqleu/confsponsor/backendforms.py b/postgresqleu/confsponsor/backendforms.py index 04f4bc30..eef2ca64 100644 --- a/postgresqleu/confsponsor/backendforms.py +++ b/postgresqleu/confsponsor/backendforms.py @@ -17,7 +17,7 @@ from benefitclasses import all_benefits import json class BackendSponsorForm(BackendForm): - helplink='sponsors#sponsor' + helplink = 'sponsors#sponsor' class Meta: model = Sponsor fields = ['name', 'displayname', 'url', 'twittername', @@ -37,7 +37,7 @@ class BackendSponsorForm(BackendForm): class BackendSponsorshipLevelBenefitForm(BackendForm): - helplink='sponsors#benefit' + helplink = 'sponsors#benefit' json_fields = ['class_parameters', ] markdown_fields = ['benefitdescription', 'claimprompt', ] dynamic_preview_fields = ['tweet_template'] @@ -124,7 +124,7 @@ class BackendSponsorshipLevelBenefitManager(object): return lambda: SponsorshipBenefit(level=masterobj, class_parameters={}) class BackendSponsorshipLevelForm(BackendForm): - helplink='sponsors#level' + helplink = 'sponsors#level' list_fields = ['levelname', 'levelcost', 'available', ] linked_objects = OrderedDict({ 'benefit': BackendSponsorshipLevelBenefitManager(), @@ -166,7 +166,7 @@ class BackendSponsorshipLevelForm(BackendForm): b.save() class BackendSponsorshipContractForm(BackendForm): - helplink='sponsors#contract' + helplink = 'sponsors#contract' list_fields = ['contractname', ] file_fields = ['contractpdf', ] class Meta: diff --git a/postgresqleu/confsponsor/benefitclasses/attendeelist.py b/postgresqleu/confsponsor/benefitclasses/attendeelist.py index 989be498..8da2fd38 100644 --- a/postgresqleu/confsponsor/benefitclasses/attendeelist.py +++ b/postgresqleu/confsponsor/benefitclasses/attendeelist.py @@ -40,7 +40,7 @@ class AttendeeList(BaseBenefit): if claimedbenefit.confirmed: if self.level.conference.enddate < datetime.today().date(): data = StringIO.StringIO() - c=csv.writer(data, delimiter=';') + c = csv.writer(data, delimiter=';') for r in ConferenceRegistration.objects.filter(conference=self.level.conference, payconfirmedat__isnull=False, shareemail=True).order_by('lastname', 'firstname'): diff --git a/postgresqleu/confsponsor/benefitclasses/imageupload.py b/postgresqleu/confsponsor/benefitclasses/imageupload.py index 2553f3a3..f35b4ef2 100644 --- a/postgresqleu/confsponsor/benefitclasses/imageupload.py +++ b/postgresqleu/confsponsor/benefitclasses/imageupload.py @@ -77,8 +77,8 @@ class ImageUpload(BaseBenefit): def save_form(self, form, claim, request): if form.cleaned_data['decline']: - claim.declined=True - claim.confirmed=True + claim.declined = True + claim.confirmed = True return True storage = InlineEncodedStorage('benefit_image') storage.save(str(claim.id), form.cleaned_data['image']) diff --git a/postgresqleu/confsponsor/forms.py b/postgresqleu/confsponsor/forms.py index 14f7ba2a..bdfe2aa2 100644 --- a/postgresqleu/confsponsor/forms.py +++ b/postgresqleu/confsponsor/forms.py @@ -149,9 +149,9 @@ class PurchaseDiscountForm(forms.Form): self.conference = conference super(PurchaseDiscountForm, self).__init__(*args, **kwargs) self.fields['requiredoptions'].queryset = ConferenceAdditionalOption.objects.filter(conference=conference) - self.fields['expires'].initial=conference.startdate-timedelta(days=2) - self.fields['expires'].validators.append(BeforeValidator(conference.startdate-timedelta(days=1))) - self.fields['expires'].validators.append(AfterValidator(date.today()-timedelta(days=1))) + self.fields['expires'].initial = conference.startdate - timedelta(days=2) + self.fields['expires'].validators.append(BeforeValidator(conference.startdate - timedelta(days=1))) + self.fields['expires'].validators.append(AfterValidator(date.today() - timedelta(days=1))) if not showconfirm: del self.fields['confirm'] diff --git a/postgresqleu/confsponsor/management/commands/sponsor_generate_discount_invoices.py b/postgresqleu/confsponsor/management/commands/sponsor_generate_discount_invoices.py index 46dd1db7..eec3827b 100644 --- a/postgresqleu/confsponsor/management/commands/sponsor_generate_discount_invoices.py +++ b/postgresqleu/confsponsor/management/commands/sponsor_generate_discount_invoices.py @@ -33,7 +33,7 @@ class Command(BaseCommand): if code.count == 0: # In case there is not a single user, we just notify the user of this and set it to # invoiced in the system so we don't try again. - code.is_invoiced=True + code.is_invoiced = True code.save() send_simple_mail(code.conference.sponsoraddr, code.conference.sponsoraddr, @@ -64,7 +64,7 @@ class Command(BaseCommand): # Percentage discount, so we need to calculate it. Ordered discount codes will # only support a registration-only style discount code, so only count it # against that. - discountvalue = r.regtype.cost * code.discountpercentage/100 + discountvalue = r.regtype.cost * code.discountpercentage / 100 invoicerows.append(['Attendee "{0}"'.format(r.fullname), 1, discountvalue, r.conference.vat_registrations]) # All invoices are always due immediately manager = InvoiceManager() @@ -75,7 +75,7 @@ class Command(BaseCommand): '%s\n%s' % (code.sponsor.name, code.sponsor.invoiceaddr), u'{0} discount code {1}'.format(code.conference, code.code), datetime.now(), - date.today()+timedelta(days=1), + date.today() + timedelta(days=1), invoicerows, bankinfo=True, accounting_account = settings.ACCOUNTING_CONFREG_ACCOUNT, diff --git a/postgresqleu/confsponsor/views.py b/postgresqleu/confsponsor/views.py index 3efb4a80..347e12f1 100644 --- a/postgresqleu/confsponsor/views.py +++ b/postgresqleu/confsponsor/views.py @@ -32,8 +32,8 @@ from vatutil import validate_eu_vat_number @login_required def sponsor_dashboard(request): # We define "past sponsors" as those older than a month - because we have to pick something. - currentsponsors = Sponsor.objects.filter(managers=request.user, conference__enddate__gte=datetime.today()-timedelta(days=31)).order_by('conference__startdate') - pastsponsors = Sponsor.objects.filter(managers=request.user, conference__enddate__lt=datetime.today()-timedelta(days=31)).order_by('conference__startdate') + currentsponsors = Sponsor.objects.filter(managers=request.user, conference__enddate__gte=datetime.today() - timedelta(days=31)).order_by('conference__startdate') + pastsponsors = Sponsor.objects.filter(managers=request.user, conference__enddate__lt=datetime.today() - timedelta(days=31)).order_by('conference__startdate') conferences = Conference.objects.filter(callforsponsorsopen=True, startdate__gt=datetime.today()).order_by('startdate') return render(request, 'confsponsor/dashboard.html', { diff --git a/postgresqleu/confwiki/views.py b/postgresqleu/confwiki/views.py index 0bd4177d..7eeec305 100644 --- a/postgresqleu/confwiki/views.py +++ b/postgresqleu/confwiki/views.py @@ -94,7 +94,7 @@ def wikipage_history(request, confurl, wikiurl): if not page.history: raise PermissionDenied() - fromid=toid=None + fromid = toid = None if request.method == 'POST': # View a diff diff --git a/postgresqleu/elections/forms.py b/postgresqleu/elections/forms.py index a6370cf3..84282b28 100644 --- a/postgresqleu/elections/forms.py +++ b/postgresqleu/elections/forms.py @@ -23,7 +23,7 @@ class VoteForm(forms.Form): for vote in self.votes: votemap[vote.candidate_id] = vote.score - dropdown = [(x,self._votestring(x)) for x in range(1,len(self.candidates)+1)] + dropdown = [(x,self._votestring(x)) for x in range(1,len(self.candidates) + 1)] dropdown.insert(0, (-1, '** Please rate this candidate')) # Dynamically add a dropdown field for each candidate @@ -62,7 +62,7 @@ class VoteForm(forms.Form): raise Exception("Data for candidate not standing for election found!") # Finally, verify that all options have been found, and none have been duplicated - options = range(1, len(self.candidates)+1) + options = range(1, len(self.candidates) + 1) for k,v in self.cleaned_data.items(): if int(v) in options: # First use is ok. Take it out of the list, so next attempt generates error diff --git a/postgresqleu/elections/views.py b/postgresqleu/elections/views.py index c9405dc9..9b034594 100644 --- a/postgresqleu/elections/views.py +++ b/postgresqleu/elections/views.py @@ -9,9 +9,9 @@ from datetime import date, timedelta def home(request): elections = Election.objects.filter(isopen=True).order_by('startdate') - open_elections = [e for e in elections if e.startdate<=date.today() and e.enddate>=date.today()] - past_elections = [e for e in elections if e.startdate<date.today() and e.enddate<date.today()] - upcoming_elections = [e for e in elections if e.startdate>date.today()] + open_elections = [e for e in elections if e.startdate <= date.today() and e.enddate >= date.today()] + past_elections = [e for e in elections if e.startdate < date.today() and e.enddate < date.today()] + upcoming_elections = [e for e in elections if e.startdate > date.today()] return render(request, 'elections/home.html', { 'open': open_elections, @@ -47,7 +47,7 @@ def election(request, electionid): return render(request, 'elections/results.html', { 'election': election, 'topscore': res[0][1], - 'scores': [{'name': r[0], 'score': r[1], 'width': 300*r[1]/res[0][1]} for r in res], + 'scores': [{'name': r[0], 'score': r[1], 'width': 300 * r[1] / res[0][1]} for r in res], }) if len(election.candidate_set.all()) <= 0: diff --git a/postgresqleu/invoices/forms.py b/postgresqleu/invoices/forms.py index 04e75a19..92715b1d 100644 --- a/postgresqleu/invoices/forms.py +++ b/postgresqleu/invoices/forms.py @@ -111,11 +111,11 @@ class RefundForm(forms.Form): del self.fields['confirm'] def clean_amount(self): - errstr = "Amount must be a decimal between 1 and {0}".format(self.invoice.total_amount-self.invoice.total_vat) + errstr = "Amount must be a decimal between 1 and {0}".format(self.invoice.total_amount - self.invoice.total_vat) try: amount = Decimal(self.cleaned_data['amount']) - if amount < 1 or amount > self.invoice.total_amount-self.invoice.total_vat: + if amount < 1 or amount > self.invoice.total_amount - self.invoice.total_vat: raise ValidationError(errstr) if amount.as_tuple().exponent > 0 or amount.as_tuple().exponent < -2: raise ValidationError("Maximum two decimal digits supported") diff --git a/postgresqleu/invoices/management/commands/process_refunds.py b/postgresqleu/invoices/management/commands/process_refunds.py index 3d9d23d9..5e9ab1d3 100644 --- a/postgresqleu/invoices/management/commands/process_refunds.py +++ b/postgresqleu/invoices/management/commands/process_refunds.py @@ -45,7 +45,7 @@ class Command(BaseCommand): # Send alerts for any refunds that have been issued but that have not completed within # 3 days (completely arbitrary, but normally it happens within seconds/minutes/hours). stalledrefunds = InvoiceRefund.objects.filter(issued__isnull=False, completed__isnull=True, - issued__lt=datetime.now()-timedelta(days=3)) + issued__lt=datetime.now() - timedelta(days=3)) if stalledrefunds: send_simple_mail(settings.INVOICE_SENDER_EMAIL, settings.INVOICE_SENDER_EMAIL, diff --git a/postgresqleu/invoices/management/commands/send_invoice_reminders.py b/postgresqleu/invoices/management/commands/send_invoice_reminders.py index b2db37eb..f87ddc27 100755 --- a/postgresqleu/invoices/management/commands/send_invoice_reminders.py +++ b/postgresqleu/invoices/management/commands/send_invoice_reminders.py @@ -22,6 +22,6 @@ class Command(BaseCommand): for invoice in invoices: wrapper = InvoiceWrapper(invoice) wrapper.email_reminder() - invoice.remindersent=datetime.now() + invoice.remindersent = datetime.now() invoice.save() self.stdout.write("Sent invoice reminder for #{0} - {1}".format(invoice.id, invoice.title)) diff --git a/postgresqleu/invoices/util.py b/postgresqleu/invoices/util.py index 518ec4e0..9f8de7ed 100644 --- a/postgresqleu/invoices/util.py +++ b/postgresqleu/invoices/util.py @@ -253,7 +253,7 @@ def _trunc_string(s, l): if len(s) <= l: return s - return s[:97]+"..." + return s[:97] + "..." class InvoiceManager(object): def __init__(self): @@ -362,7 +362,7 @@ class InvoiceManager(object): accountingtxt = 'Invoice #%s: %s' % (invoice.id, invoice.title) accrows = [ - (incomeaccount, accountingtxt, invoice.total_amount-transcost, None), + (incomeaccount, accountingtxt, invoice.total_amount - transcost, None), ] if transcost > 0: # If there was a transaction cost known at this point (which @@ -389,7 +389,7 @@ class InvoiceManager(object): if invoice.accounting_account: accrows.append( - (invoice.accounting_account, accountingtxt, -(invoice.total_amount-invoice.total_vat), invoice.accounting_object), + (invoice.accounting_account, accountingtxt, -(invoice.total_amount - invoice.total_vat), invoice.accounting_object), ) leaveopen = False else: @@ -477,7 +477,7 @@ class InvoiceManager(object): invoice.save() InvoiceHistory(invoice=invoice, - txt='Registered refund of {0}{1}'.format(settings.CURRENCY_SYMBOL, amount+vatamount)).save() + txt='Registered refund of {0}{1}'.format(settings.CURRENCY_SYMBOL, amount + vatamount)).save() wrapper = InvoiceWrapper(invoice) if invoice.can_autorefund: @@ -488,7 +488,7 @@ class InvoiceManager(object): # provider. InvoiceLog(timestamp=datetime.now(), - message="Initiated refund of {0}{1} of invoice {2}: {3}".format(settings.CURRENCY_SYMBOL, amount+vatamount, invoice.id, reason), + message="Initiated refund of {0}{1} of invoice {2}: {3}".format(settings.CURRENCY_SYMBOL, amount + vatamount, invoice.id, reason), ).save() else: # No automatic refund, so this is flagging something that has @@ -504,7 +504,7 @@ class InvoiceManager(object): if invoice.accounting_account: accountingtxt = 'Refund of invoice #{0}: {1}'.format(invoice.id, invoice.title) accrows = [ - (invoice.accounting_account, accountingtxt, invoice.total_amount-vatamount, invoice.accounting_object), + (invoice.accounting_account, accountingtxt, invoice.total_amount - vatamount, invoice.accounting_object), ] if vatamount: accrows.append( @@ -515,11 +515,11 @@ class InvoiceManager(object): create_accounting_entry(date.today(), accrows, True, urls) InvoiceHistory(invoice=invoice, - txt='Flagged refund of {0}{1}'.format(settings.CURRENCY_SYMBOL, amount+vatamount)).save() + txt='Flagged refund of {0}{1}'.format(settings.CURRENCY_SYMBOL, amount + vatamount)).save() wrapper.email_refund_sent() InvoiceLog(timestamp=datetime.now(), - message=u"Flagged invoice {0} as refunded by {1}{2}: {3}".format(invoice.id, settings.CURRENCY_SYMBOL.decode('utf8'), amount+vatamount, reason), + message=u"Flagged invoice {0} as refunded by {1}{2}: {3}".format(invoice.id, settings.CURRENCY_SYMBOL.decode('utf8'), amount + vatamount, reason), ).save() return r @@ -546,7 +546,7 @@ class InvoiceManager(object): accountingtxt = 'Refund ({0}) of invoice #{1}'.format(refundid, invoice.id) accrows = [ - (incomeaccount, accountingtxt, -(refundamount-refundfee), None), + (incomeaccount, accountingtxt, -(refundamount - refundfee), None), ] if refund.vatamount: accrows.append( @@ -558,7 +558,7 @@ class InvoiceManager(object): ) if invoice.accounting_account: accrows.append( - (invoice.accounting_account, accountingtxt, refundamount-refund.vatamount, invoice.accounting_object), + (invoice.accounting_account, accountingtxt, refundamount - refund.vatamount, invoice.accounting_object), ) leaveopen = False else: diff --git a/postgresqleu/invoices/views.py b/postgresqleu/invoices/views.py index 42d1e36e..71a6d967 100644 --- a/postgresqleu/invoices/views.py +++ b/postgresqleu/invoices/views.py @@ -170,7 +170,7 @@ def oneinvoice(request, invoicenum): else: form = InvoiceForm(initial={ 'invoicedate': datetime.now(), - 'duedate': datetime.now()+timedelta(days=31)} + 'duedate': datetime.now() + timedelta(days=31)} ) formset = InvoiceRowInlineFormset(instance=invoice) diff --git a/postgresqleu/membership/invoicehandler.py b/postgresqleu/membership/invoicehandler.py index 2c2ec67d..864ca5f0 100644 --- a/postgresqleu/membership/invoicehandler.py +++ b/postgresqleu/membership/invoicehandler.py @@ -5,7 +5,7 @@ from models import Member, MemberLog from datetime import datetime, timedelta, date class InvoiceProcessor(object): - can_refund=False + can_refund = False # Process invoices once they're getting paid # # In the case of membership, that simply means extending the @@ -25,9 +25,9 @@ class InvoiceProcessor(object): # Extend the membership. If already paid to a date in the future, # extend from that date. Otherwise, from today. if member.paiduntil and member.paiduntil > date.today(): - member.paiduntil = member.paiduntil + timedelta(days=settings.MEMBERSHIP_LENGTH*365) + member.paiduntil = member.paiduntil + timedelta(days=settings.MEMBERSHIP_LENGTH * 365) else: - member.paiduntil = date.today()+timedelta(days=settings.MEMBERSHIP_LENGTH*365) + member.paiduntil = date.today() + timedelta(days=settings.MEMBERSHIP_LENGTH * 365) member.expiry_warning_sent = None # If the member isn't already a member, set todays date as the diff --git a/postgresqleu/membership/models.py b/postgresqleu/membership/models.py index 64d41063..368a1538 100644 --- a/postgresqleu/membership/models.py +++ b/postgresqleu/membership/models.py @@ -62,7 +62,7 @@ class Meeting(models.Model): @property def joining_active(self): - if datetime.now() > self.dateandtime-timedelta(hours=4): + if datetime.now() > self.dateandtime - timedelta(hours=4): return True return False diff --git a/postgresqleu/membership/views.py b/postgresqleu/membership/views.py index 5904a414..2c73ccd9 100644 --- a/postgresqleu/membership/views.py +++ b/postgresqleu/membership/views.py @@ -145,7 +145,7 @@ def admin_email(request): def meetings(request): # Only available for actual members member = get_object_or_404(Member, user=request.user) - q = Q(dateandtime__gte=datetime.now()-timedelta(hours=4)) & (Q(allmembers=True) | Q(members=member)) + q = Q(dateandtime__gte=datetime.now() - timedelta(hours=4)) & (Q(allmembers=True) | Q(members=member)) meetings = Meeting.objects.filter(q).order_by('dateandtime') meetinginfo = [{ diff --git a/postgresqleu/newsevents/management/commands/twitter_post.py b/postgresqleu/newsevents/management/commands/twitter_post.py index cae86fe6..48ed760a 100644 --- a/postgresqleu/newsevents/management/commands/twitter_post.py +++ b/postgresqleu/newsevents/management/commands/twitter_post.py @@ -26,7 +26,7 @@ class Command(BaseCommand): raise CommandError("Failed to get advisory lock, existing twitter_post process stuck?") if settings.TWITTER_NEWS_TOKEN: - articles = list(News.objects.filter(tweeted=False, datetime__gt=datetime.now()-timedelta(days=7), datetime__lt=datetime.now()).order_by('datetime')) + articles = list(News.objects.filter(tweeted=False, datetime__gt=datetime.now() - timedelta(days=7), datetime__lt=datetime.now()).order_by('datetime')) else: articles = [] @@ -35,7 +35,7 @@ class Command(BaseCommand): for a in articles: # We hardcode 30 chars for the URL shortener. And then 10 to cover the intro and spacing. - statusstr = u"{0} {1}/news/{2}-{3}/".format(a.title[:140-40], + statusstr = u"{0} {1}/news/{2}-{3}/".format(a.title[:140 - 40], settings.SITEBASE, slugify(a.title), a.id) @@ -61,10 +61,10 @@ class Command(BaseCommand): ]): tw = Twitter(c) - al = list(ConferenceNews.objects.filter(conference=c, tweeted=False, datetime__gt=datetime.now()-timedelta(days=7), datetime__lt=datetime.now(), conference__twittersync_active=True).order_by('datetime')[:1]) + al = list(ConferenceNews.objects.filter(conference=c, tweeted=False, datetime__gt=datetime.now() - timedelta(days=7), datetime__lt=datetime.now(), conference__twittersync_active=True).order_by('datetime')[:1]) if al: a = al[0] - statusstr = u"{0} {1}##{2}".format(a.title[:250-40], + statusstr = u"{0} {1}##{2}".format(a.title[:250 - 40], c.confurl, a.id) ok, msg = tw.post_tweet(statusstr) diff --git a/postgresqleu/paypal/management/commands/paypal_fetch.py b/postgresqleu/paypal/management/commands/paypal_fetch.py index b5be3b1f..88a247d6 100644 --- a/postgresqleu/paypal/management/commands/paypal_fetch.py +++ b/postgresqleu/paypal/management/commands/paypal_fetch.py @@ -120,7 +120,7 @@ class Command(BaseCommand): }) # Fetch all transactions from last sync, with a 3 day overlap - for r in api.get_transaction_list(cursor.fetchall()[0][0]-timedelta(days=3)): + for r in api.get_transaction_list(cursor.fetchall()[0][0] - timedelta(days=3)): if r['TYPE'] in ('Payment', 'Donation', 'Purchase'): t = PaypalTransaction(r) elif r['TYPE'] in ('Transfer'): diff --git a/postgresqleu/paypal/management/commands/paypal_match.py b/postgresqleu/paypal/management/commands/paypal_match.py index 88609ff1..6be4fde1 100755 --- a/postgresqleu/paypal/management/commands/paypal_match.py +++ b/postgresqleu/paypal/management/commands/paypal_match.py @@ -44,7 +44,7 @@ class Command(BaseCommand): # manually completed. accstr = "Paypal donation %s" % trans.paypaltransid accrows = [ - (settings.ACCOUNTING_PAYPAL_INCOME_ACCOUNT, accstr, trans.amount-trans.fee, None), + (settings.ACCOUNTING_PAYPAL_INCOME_ACCOUNT, accstr, trans.amount - trans.fee, None), (settings.ACCOUNTING_PAYPAL_FEE_ACCOUNT, accstr, trans.fee, None), (settings.ACCOUNTING_DONATIONS_ACCOUNT, accstr, -trans.amount, None), ] @@ -57,7 +57,7 @@ class Command(BaseCommand): accstr = "Unlabeled paypal payment from {0}".format(trans.sender) accrows = [ - (settings.ACCOUNTING_PAYPAL_INCOME_ACCOUNT, accstr, trans.amount-trans.fee, None), + (settings.ACCOUNTING_PAYPAL_INCOME_ACCOUNT, accstr, trans.amount - trans.fee, None), ] if trans.fee: accrows.append( diff --git a/postgresqleu/paypal/views.py b/postgresqleu/paypal/views.py index 9eb8acfe..f84225af 100644 --- a/postgresqleu/paypal/views.py +++ b/postgresqleu/paypal/views.py @@ -141,7 +141,7 @@ def paypal_return_handler(request): # manually completed. accstr = "Paypal donation %s" % ti.paypaltransid accrows = [ - (settings.ACCOUNTING_PAYPAL_INCOME_ACCOUNT, accstr, ti.amount-ti.fee, None), + (settings.ACCOUNTING_PAYPAL_INCOME_ACCOUNT, accstr, ti.amount - ti.fee, None), (settings.ACCOUNTING_PAYPAL_FEE_ACCOUNT, accstr, ti.fee, None), (settings.ACCOUNTING_DONATIONS_ACCOUNT, accstr, -ti.amount, None), ] diff --git a/postgresqleu/settings.py b/postgresqleu/settings.py index 43f439f4..2598f4cc 100644 --- a/postgresqleu/settings.py +++ b/postgresqleu/settings.py @@ -61,7 +61,7 @@ MIDDLEWARE_CLASSES = [ 'postgresqleu.util.middleware.RedirectMiddleware', ] -CSRF_FAILURE_VIEW='postgresqleu.views.csrf_failure' +CSRF_FAILURE_VIEW = 'postgresqleu.views.csrf_failure' ROOT_URLCONF = 'postgresqleu.urls' @@ -112,109 +112,109 @@ MEMBERSHIP_SENDER_EMAIL = DEFAULT_EMAIL # Currency parameter -CURRENCY_ABBREV='EUR' -CURRENCY_SYMBOL='€' -CURRENCY_ISO='EUR' +CURRENCY_ABBREV = 'EUR' +CURRENCY_SYMBOL = '€' +CURRENCY_ISO = 'EUR' # Process EU-specific VAT rules -EU_VAT=False +EU_VAT = False # Home country prefix for EU VAT -EU_VAT_HOME_COUNTRY="FR" +EU_VAT_HOME_COUNTRY = "FR" # On-line validate EU vat numbers -EU_VAT_VALIDATE=False +EU_VAT_VALIDATE = False ##### Membership module ##### # Years of membership per payment -MEMBERSHIP_LENGTH=2 +MEMBERSHIP_LENGTH = 2 # Cost for membership -MEMBERSHIP_COST=10 +MEMBERSHIP_COST = 10 # Function called to valide that country is acceptable for membership -MEMBERSHIP_COUNTRY_VALIDATOR=None +MEMBERSHIP_COUNTRY_VALIDATOR = None ##### Invoice module ##### -INVOICE_PDF_BUILDER='postgresqleu.util.misc.pgeuinvoice' +INVOICE_PDF_BUILDER = 'postgresqleu.util.misc.pgeuinvoice' # Paypal sandbox configuration -PAYPAL_BASEURL='https://www.paypal.com/cgi-bin/webscr' -PAYPAL_EMAIL=DEFAULT_EMAIL -PAYPAL_PDT_TOKEN='abc123' -PAYPAL_DEFAULT_SOURCEACCOUNT=1 -PAYPAL_API_USER='someuser' -PAYPAL_API_PASSWORD='secret' -PAYPAL_API_SIGNATURE='secret' -PAYPAL_SANDBOX=True -PAYPAL_REPORT_RECEIVER=DEFAULT_EMAIL -PAYPAL_DONATION_TEXT="Paypal Donation" +PAYPAL_BASEURL = 'https://www.paypal.com/cgi-bin/webscr' +PAYPAL_EMAIL = DEFAULT_EMAIL +PAYPAL_PDT_TOKEN = 'abc123' +PAYPAL_DEFAULT_SOURCEACCOUNT = 1 +PAYPAL_API_USER = 'someuser' +PAYPAL_API_PASSWORD = 'secret' +PAYPAL_API_SIGNATURE = 'secret' +PAYPAL_SANDBOX = True +PAYPAL_REPORT_RECEIVER = DEFAULT_EMAIL +PAYPAL_DONATION_TEXT = "Paypal Donation" # Adyen configuration -ADYEN_BASEURL='https://test.adyen.com/' -ADYEN_CABASEURL='https://test-ca.adyen.com/' -ADYEN_APIBASEURL='https://pal-test.adyen.com/' -ADYEN_MERCHANTACCOUNT='whatever' -ADYEN_SIGNKEY='foobar' -ADYEN_SKINCODE='abc123' -ADYEN_NOTIFICATION_RECEIVER=DEFAULT_EMAIL -ADYEN_NOTIFY_USER='adyennot' -ADYEN_NOTIFY_PASSWORD='topsecret' -ADYEN_REPORT_USER='someone' -ADYEN_REPORT_PASSWORD='topsecret' -ADYEN_WS_USER='someone' -ADYEN_WS_PASSWORD='topsecret' -ADYEN_MERCHANTREF_PREFIX='PGEU' -ADYEN_MERCHANTREF_REFUND_PREFIX='PGEUREFUND' +ADYEN_BASEURL = 'https://test.adyen.com/' +ADYEN_CABASEURL = 'https://test-ca.adyen.com/' +ADYEN_APIBASEURL = 'https://pal-test.adyen.com/' +ADYEN_MERCHANTACCOUNT = 'whatever' +ADYEN_SIGNKEY = 'foobar' +ADYEN_SKINCODE = 'abc123' +ADYEN_NOTIFICATION_RECEIVER = DEFAULT_EMAIL +ADYEN_NOTIFY_USER = 'adyennot' +ADYEN_NOTIFY_PASSWORD = 'topsecret' +ADYEN_REPORT_USER = 'someone' +ADYEN_REPORT_PASSWORD = 'topsecret' +ADYEN_WS_USER = 'someone' +ADYEN_WS_PASSWORD = 'topsecret' +ADYEN_MERCHANTREF_PREFIX = 'PGEU' +ADYEN_MERCHANTREF_REFUND_PREFIX = 'PGEUREFUND' # Account numbers used for auto-accounting -ENABLE_AUTO_ACCOUNTING=False -ACCOUNTING_PAYPAL_INCOME_ACCOUNT=1932 -ACCOUNTING_PAYPAL_FEE_ACCOUNT=6041 -ACCOUNTING_PAYPAL_TRANSFER_ACCOUNT=1930 -ACCOUNTING_ADYEN_AUTHORIZED_ACCOUNT=1621 -ACCOUNTING_ADYEN_PAYABLE_ACCOUNT=1622 -ACCOUNTING_ADYEN_FEE_ACCOUNT=6040 -ACCOUNTING_ADYEN_PAYOUT_ACCOUNT=1930 -ACCOUNTING_ADYEN_MERCHANT_ACCOUNT=1971 -ACCOUNTING_ADYEN_REFUNDS_ACCOUNT=2498 -ACCOUNTING_MANUAL_INCOME_ACCOUNT=1930 -ACCOUNTING_CONFREG_ACCOUNT=3003 -ACCOUNTING_CONFSPONSOR_ACCOUNT=3004 -ACCOUNTING_MEMBERSHIP_ACCOUNT=3001 -ACCOUNTING_DONATIONS_ACCOUNT=3601 -ACCOUNTING_INVOICE_VAT_ACCOUNT=2610 +ENABLE_AUTO_ACCOUNTING = False +ACCOUNTING_PAYPAL_INCOME_ACCOUNT = 1932 +ACCOUNTING_PAYPAL_FEE_ACCOUNT = 6041 +ACCOUNTING_PAYPAL_TRANSFER_ACCOUNT = 1930 +ACCOUNTING_ADYEN_AUTHORIZED_ACCOUNT = 1621 +ACCOUNTING_ADYEN_PAYABLE_ACCOUNT = 1622 +ACCOUNTING_ADYEN_FEE_ACCOUNT = 6040 +ACCOUNTING_ADYEN_PAYOUT_ACCOUNT = 1930 +ACCOUNTING_ADYEN_MERCHANT_ACCOUNT = 1971 +ACCOUNTING_ADYEN_REFUNDS_ACCOUNT = 2498 +ACCOUNTING_MANUAL_INCOME_ACCOUNT = 1930 +ACCOUNTING_CONFREG_ACCOUNT = 3003 +ACCOUNTING_CONFSPONSOR_ACCOUNT = 3004 +ACCOUNTING_MEMBERSHIP_ACCOUNT = 3001 +ACCOUNTING_DONATIONS_ACCOUNT = 3601 +ACCOUNTING_INVOICE_VAT_ACCOUNT = 2610 ##### Organisation configuration ##### -ORG_NAME="Not Configured Organisation" -ORG_SHORTNAME="NOTCONF" +ORG_NAME = "Not Configured Organisation" +ORG_SHORTNAME = "NOTCONF" # Base URLs for generating absolute URLs -SITEBASE="http://localhost:8000" +SITEBASE = "http://localhost:8000" # Set cookies to secure to explicitly force off in the local settings -SESSION_COOKIE_SECURE=True -CSRF_COOKIE_SECURE=True +SESSION_COOKIE_SECURE = True +CSRF_COOKIE_SECURE = True -DATETIME_FORMAT="Y-m-d H:i:s" +DATETIME_FORMAT = "Y-m-d H:i:s" ##### Enable/disable modules ##### -ENABLE_PG_COMMUNITY_AUTH=False -ENABLE_NEWS=True -ENABLE_MEMBERSHIP=False -ENABLE_ELECTIONS=False -ENABLE_BRAINTREE=False -ENABLE_TRUSTLY=False +ENABLE_PG_COMMUNITY_AUTH = False +ENABLE_NEWS = True +ENABLE_MEMBERSHIP = False +ENABLE_ELECTIONS = False +ENABLE_BRAINTREE = False +ENABLE_TRUSTLY = False # Set to a username and password in local_settings.py to enable global http auth -GLOBAL_LOGIN_USER='' -GLOBAL_LOGIN_PASSWORD='' +GLOBAL_LOGIN_USER = '' +GLOBAL_LOGIN_PASSWORD = '' # Treasurer email address -TREASURER_EMAIL=DEFAULT_EMAIL +TREASURER_EMAIL = DEFAULT_EMAIL # Twitter application keys -TWITTER_CLIENT="" -TWITTER_CLIENTSECRET="" +TWITTER_CLIENT = "" +TWITTER_CLIENTSECRET = "" # Twitter user keys for the account posting main news -TWITTER_NEWS_TOKEN="" -TWITTER_NEWS_TOKENSECRET="" +TWITTER_NEWS_TOKEN = "" +TWITTER_NEWS_TOKENSECRET = "" # If there is a local_settings.py, let it override our settings try: @@ -222,11 +222,11 @@ try: except ImportError, e: pass -PRELOAD_URLS=[] +PRELOAD_URLS = [] if 'SYSTEM_SKIN_DIRECTORY' in globals(): # A skin directory is configured! # First, add it to templates - HAS_SKIN=True + HAS_SKIN = True TEMPLATES[0]['DIRS'].insert(0, os.path.join(SYSTEM_SKIN_DIRECTORY, 'template/')) @@ -245,7 +245,7 @@ if 'SYSTEM_SKIN_DIRECTORY' in globals(): if 'SKIN_APPS' in globals(): INSTALLED_APPS.extend(SKIN_APPS) else: - HAS_SKIN=False + HAS_SKIN = False if not SECRET_KEY: @@ -258,8 +258,8 @@ ADMINS = ( MANAGERS = ADMINS ##### Invoice module ##### -INVOICE_TITLE_PREFIX=u'{0} Invoice'.format(ORG_NAME) -INVOICE_FILENAME_PREFIX=ORG_SHORTNAME.lower() +INVOICE_TITLE_PREFIX = u'{0} Invoice'.format(ORG_NAME) +INVOICE_FILENAME_PREFIX = ORG_SHORTNAME.lower() if GLOBAL_LOGIN_USER: @@ -269,7 +269,7 @@ if ENABLE_PG_COMMUNITY_AUTH: AUTHENTICATION_BACKENDS = ( 'postgresqleu.auth.AuthBackend', ) - LOGIN_URL="{0}/accounts/login/".format(SITEBASE) + LOGIN_URL = "{0}/accounts/login/".format(SITEBASE) 4 if ENABLE_ELECTIONS and not ENABLE_MEMBERSHIP: raise Exception("Elections module requires membership module!") @@ -284,17 +284,17 @@ if ENABLE_ELECTIONS: if ENABLE_BRAINTREE: INSTALLED_APPS.append('postgresqleu.braintreepayment') - BRAINTREE_SANDBOX=False + BRAINTREE_SANDBOX = False # Accounts to use for braintree transactions # Override in local_settings.py, and also configure # the public and secret keys there. - ACCOUNTING_BRAINTREE_AUTHORIZED_ACCOUNT=1621 - ACCOUNTING_BRAINTREE_PAYABLE_ACCOUNT=1623 - ACCOUNTING_BRAINTREE_PAYOUT_ACCOUNT=1930 - ACCOUNTING_BRAINTREE_FEE_ACCOUNT=6040 + ACCOUNTING_BRAINTREE_AUTHORIZED_ACCOUNT = 1621 + ACCOUNTING_BRAINTREE_PAYABLE_ACCOUNT = 1623 + ACCOUNTING_BRAINTREE_PAYOUT_ACCOUNT = 1930 + ACCOUNTING_BRAINTREE_FEE_ACCOUNT = 6040 if ENABLE_TRUSTLY: INSTALLED_APPS.append('postgresqleu.trustlypayment') # Accounts to use for trustly transactions - ACCOUNTING_TRUSTLY_ACCOUNT=1972 + ACCOUNTING_TRUSTLY_ACCOUNT = 1972 diff --git a/postgresqleu/trustlypayment/admin.py b/postgresqleu/trustlypayment/admin.py index 336c2645..1d00085d 100644 --- a/postgresqleu/trustlypayment/admin.py +++ b/postgresqleu/trustlypayment/admin.py @@ -5,7 +5,7 @@ from django.urls import reverse from models import TrustlyTransaction, TrustlyRawNotification, TrustlyNotification, TrustlyLog class TrustlyTransactionAdmin(admin.ModelAdmin): - list_display=('orderid', 'invoiceid', 'amount', 'createdat', 'pendingat', 'completedat',) + list_display = ('orderid', 'invoiceid', 'amount', 'createdat', 'pendingat', 'completedat',) class TrustlyRawNotificationAdmin(admin.ModelAdmin): list_display = ('dat', 'confirmed') @@ -26,7 +26,7 @@ class TrustlyNotificationAdmin(admin.ModelAdmin): def rawnotification_link(self, obj): url = reverse('admin:trustlypayment_trustlyrawnotification_change', args=(obj.rawnotification.id, )) return mark_safe('<a href="{0}">{1}</a>'.format(url, obj)) - rawnotification_link.short_description='Rawnotification' + rawnotification_link.short_description = 'Rawnotification' class TrustlyLogAdmin(admin.ModelAdmin): list_display = ('timestamp', 'success', 'sentstr', 'message', ) @@ -37,7 +37,7 @@ class TrustlyLogAdmin(admin.ModelAdmin): def sentstr(self, obj): return obj.sent and 'Yes' or 'No' - sentstr.short_description='Log sent' + sentstr.short_description = 'Log sent' admin.site.register(TrustlyTransaction, TrustlyTransactionAdmin) admin.site.register(TrustlyRawNotification, TrustlyRawNotificationAdmin) diff --git a/postgresqleu/trustlypayment/api.py b/postgresqleu/trustlypayment/api.py index 6ced41a2..77690ff9 100644 --- a/postgresqleu/trustlypayment/api.py +++ b/postgresqleu/trustlypayment/api.py @@ -92,7 +92,7 @@ class TrustlyWrapper(object): } params['Data']['Username'] = self.username params['Data']['Password'] = self.password - tosign = unicode((method+params['UUID']+self._serializestruct(params['Data'])).decode('utf8')) + tosign = unicode((method + params['UUID'] + self._serializestruct(params['Data'])).decode('utf8')) sha1hash = SHA.new(tosign.encode('utf-8')) signature = self.signer.sign(sha1hash) params['Signature'] = base64.b64encode(signature) @@ -122,7 +122,7 @@ class TrustlyWrapper(object): def parse_notification(self, notstr): struct = json.loads(notstr) - tosign = unicode(struct['method']+struct['params']['uuid']+self._serializestruct(struct['params']['data'])) + tosign = unicode(struct['method'] + struct['params']['uuid'] + self._serializestruct(struct['params']['data'])) sha1hash = SHA.new(tosign.encode('utf-8')) if self.verifier.verify(sha1hash, base64.b64decode(struct['params']['signature'])): @@ -142,7 +142,7 @@ class TrustlyWrapper(object): }, 'version': '1.1', } - tosign = unicode(method+uuid+self._serializestruct(struct['result']['data'])) + tosign = unicode(method + uuid + self._serializestruct(struct['result']['data'])) sha1hash = SHA.new(tosign.encode('utf-8')) signature = self.signer.sign(sha1hash) struct['result']['signature'] = base64.b64encode(signature) diff --git a/postgresqleu/trustlypayment/management/commands/send_trustly_logreport.py b/postgresqleu/trustlypayment/management/commands/send_trustly_logreport.py index 4af5ac6e..c184349a 100755 --- a/postgresqleu/trustlypayment/management/commands/send_trustly_logreport.py +++ b/postgresqleu/trustlypayment/management/commands/send_trustly_logreport.py @@ -40,7 +40,7 @@ class Command(BaseCommand): sio.getvalue()) def report_unconfirmed_notifications(self): - lines = list(TrustlyNotification.objects.filter(confirmed=False, receivedat__lt=datetime.now()-timedelta(days=1)).order_by('receivedat')) + lines = list(TrustlyNotification.objects.filter(confirmed=False, receivedat__lt=datetime.now() - timedelta(days=1)).order_by('receivedat')) if len(lines): sio = StringIO() sio.write("The following notifications have not been confirmed in the Trustly integration.\nThese need to be manually processed and then flagged as confirmed!\n\nThis list only contains unconfirmed events older than 24 hours.\n\n\n") @@ -56,9 +56,9 @@ class Command(BaseCommand): # Number of days until we start reporting unfinished transactions # Note: we only care about transactions that have actually started, where the user # got the first step of confirmation. The ones that were never started are uninteresting. - UNFINISHED_THRESHOLD=3 + UNFINISHED_THRESHOLD = 3 - lines = list(TrustlyTransaction.objects.filter(completedat__isnull=True, pendingat__isnull=False, pendingat__lt=datetime.now()-timedelta(days=UNFINISHED_THRESHOLD)).order_by('pendingat')) + lines = list(TrustlyTransaction.objects.filter(completedat__isnull=True, pendingat__isnull=False, pendingat__lt=datetime.now() - timedelta(days=UNFINISHED_THRESHOLD)).order_by('pendingat')) if len(lines): sio = StringIO() sio.write("The following payments have been authorized, but not finished for more than %s days.\nThese probably need to be verified manually.\n\n\n" % UNFINISHED_THRESHOLD) diff --git a/postgresqleu/trustlypayment/util.py b/postgresqleu/trustlypayment/util.py index 7a4b7a8f..84bd3344 100644 --- a/postgresqleu/trustlypayment/util.py +++ b/postgresqleu/trustlypayment/util.py @@ -55,7 +55,7 @@ class Trustly(TrustlyWrapper): messageid=data['messageid'], ) n.save() - raw.confirmed=True + raw.confirmed = True raw.save() # Raw is confirmed, but parsed one is still pending. So handle that one. @@ -97,7 +97,7 @@ class Trustly(TrustlyWrapper): if not trans.pendingat: trans.pendingat = datetime.now() trans.save() - notification.confirmed=True + notification.confirmed = True notification.save() TrustlyLog(message="Pending payment for Trustly id {0} (order {1}) received".format(trans.id, trans.orderid)).save() @@ -119,7 +119,7 @@ class Trustly(TrustlyWrapper): self.log_and_email(e) return False trans.save() - notification.confirmed=True + notification.confirmed = True notification.save() return True elif notification.method == 'cancel': diff --git a/postgresqleu/trustlypayment/views.py b/postgresqleu/trustlypayment/views.py index 4a71dfb9..5716c432 100644 --- a/postgresqleu/trustlypayment/views.py +++ b/postgresqleu/trustlypayment/views.py @@ -88,7 +88,7 @@ def success(request, invoiceid, secret): status.seencount += 1 status.save() return render(request, 'trustlypayment/pending.html', { - 'refresh': 3*status.seencount, + 'refresh': 3 * status.seencount, 'url': '/invoices/{0}/{1}/'.format(invoiceid, secret), 'createdat': trans.createdat, 'pendingat': trans.pendingat, diff --git a/postgresqleu/util/forms.py b/postgresqleu/util/forms.py index c369d958..c700b813 100644 --- a/postgresqleu/util/forms.py +++ b/postgresqleu/util/forms.py @@ -8,8 +8,8 @@ import base64 from itertools import groupby class _ValidatorField(forms.Field): - required=True - widget=forms.HiddenInput + required = True + widget = forms.HiddenInput class ConcurrentProtectedModelForm(forms.ModelForm): _validator = _ValidatorField() diff --git a/postgresqleu/util/middleware.py b/postgresqleu/util/middleware.py index 2146e0d6..62f10734 100644 --- a/postgresqleu/util/middleware.py +++ b/postgresqleu/util/middleware.py @@ -20,7 +20,7 @@ class FilterPersistMiddleware(object): referrer = request.META['HTTP_REFERER'].split('?')[0] referrer = referrer[referrer.find('/admin'):len(referrer)] - key = 'key'+path.replace('/','_') + key = 'key' + path.replace('/','_') if path == referrer: #We are in same page as before if query_string == '': #Filter is empty, delete it @@ -29,14 +29,14 @@ class FilterPersistMiddleware(object): return None request.session[key] = query_string elif '_directlink=1' in query_string: # Direct link to a filter, by ourselves, so remove it - redirect_to = path+'?'+query_string.replace('&_directlink=1','') + redirect_to = path + '?' + query_string.replace('&_directlink=1','') if session.has_key(key): del session[key] return http.HttpResponseRedirect(redirect_to) else: #We are are coming from another page, restore filter if available if session.get(key, False): - query_string=request.session.get(key) - redirect_to = path+'?'+query_string + query_string = request.session.get(key) + redirect_to = path + '?' + query_string request.session['redirected'] = True return http.HttpResponseRedirect(redirect_to) else: diff --git a/postgresqleu/util/misc/pgeuinvoice.py b/postgresqleu/util/misc/pgeuinvoice.py index e1bfad67..4f9ac2f7 100755 --- a/postgresqleu/util/misc/pgeuinvoice.py +++ b/postgresqleu/util/misc/pgeuinvoice.py @@ -123,7 +123,7 @@ class PDFInvoice(PDFBase): self.rows.append((title, cost, count, vatrate, vatrate and vatrate.vatpercent or 0)) - ROWS_PER_PAGE=14 + ROWS_PER_PAGE = 14 def save(self): # We can fit ROWS_PER_PAGE rows on one page. We might want to do something # cute to avoid a single row on it's own page in the future, but @@ -179,7 +179,7 @@ class PDFInvoice(PDFBase): totalexcl = sum([cost*count for title,cost,count,vatrate,vatpercent in self.rows]) totalvat = sum([(cost*count*(vatpercent/Decimal(100))).quantize(Decimal('0.01')) for title,cost,count,vatrate,vatpercent in self.rows]) totalincl = sum([(cost*count*(1+vatpercent/Decimal(100))).quantize(Decimal('0.01')) for title,cost,count,vatrate,vatpercent in self.rows]) - if self.totalvat>0 and totalvat != self.totalvat: + if self.totalvat > 0 and totalvat != self.totalvat: raise Exception("Specified total VAT {0} does not match calculated VAT {1}".format(self.totalvat, totalvat)) if self.reverse_vat: diff --git a/postgresqleu/util/payment/adyen.py b/postgresqleu/util/payment/adyen.py index 0e4d996e..71975035 100644 --- a/postgresqleu/util/payment/adyen.py +++ b/postgresqleu/util/payment/adyen.py @@ -40,7 +40,7 @@ def _gzip_string(str): return s.getvalue() class _AdyenBase(object): - ADYEN_COMMON={ + ADYEN_COMMON = { 'currencyCode': settings.CURRENCY_ABBREV, 'skinCode': settings.ADYEN_SKINCODE, 'merchantAccount': settings.ADYEN_MERCHANTACCOUNT, @@ -52,7 +52,7 @@ class _AdyenBase(object): orderdata = "<p>%s</p>" % invoicestr param.update({ 'merchantReference': '%s%s' % (settings.ADYEN_MERCHANTREF_PREFIX, invoiceid), - 'paymentAmount': '%s' % (int(invoiceamount*Decimal(100.0)),), + 'paymentAmount': '%s' % (int(invoiceamount * Decimal(100.0)),), 'orderData': base64.encodestring(_gzip_string(orderdata.encode('utf-8'))).strip().replace("\n",''), 'merchantReturnData': '%s%s' % (settings.ADYEN_MERCHANTREF_PREFIX, invoiceid), 'sessionValidity': (datetime.utcnow() + timedelta(minutes=30)).strftime('%Y-%m-%dT%H:%M:%SZ'), @@ -85,7 +85,7 @@ class _AdyenBase(object): return reason if trans.settledamount: - return trans.amount-trans.settledamount + return trans.amount - trans.settledamount else: return "not settled yet" @@ -105,7 +105,7 @@ class _AdyenBase(object): return True class AdyenCreditcard(_AdyenBase): - description=""" + description = """ Pay using your credit card, including Mastercard, VISA and American Express. """ @@ -121,7 +121,7 @@ Pay using your credit card, including Mastercard, VISA and American Express. return "Credit Card ({0})".format(trans.method) class AdyenBanktransfer(_AdyenBase): - description=""" + description = """ Pay using a direct IBAN bank transfer. Due to the unreliable and slow processing of these payments, this method is <b>not recommended</b> unless it is the only option possible. In particular, we strongly advice not using this method if diff --git a/postgresqleu/util/payment/banktransfer.py b/postgresqleu/util/payment/banktransfer.py index c1d102b3..5b9d62a7 100644 --- a/postgresqleu/util/payment/banktransfer.py +++ b/postgresqleu/util/payment/banktransfer.py @@ -1,7 +1,7 @@ from urllib import urlencode class Banktransfer(object): - description=""" + description = """ Using this payment method, you can pay via a regular bank transfer using IBAN. Note that this requires that you are able to make a payment in Euros, and requires you to cover all transfer charges. diff --git a/postgresqleu/util/payment/braintree.py b/postgresqleu/util/payment/braintree.py index e4d8fe01..61705280 100644 --- a/postgresqleu/util/payment/braintree.py +++ b/postgresqleu/util/payment/braintree.py @@ -4,7 +4,7 @@ from postgresqleu.invoices.models import Invoice from postgresqleu.braintreepayment.models import BraintreeTransaction class Braintree(object): - description=""" + description = """ Using this payment method, you can pay using your credit card, including Mastercard, VISA and American Express. """ @@ -32,7 +32,7 @@ Mastercard, VISA and American Express. if not trans: return reason if trans.disbursedamount: - return trans.amount-trans.disbursedamount + return trans.amount - trans.disbursedamount else: return "not disbursed yet" diff --git a/postgresqleu/util/payment/dummy.py b/postgresqleu/util/payment/dummy.py index 64f83104..15bfcd10 100644 --- a/postgresqleu/util/payment/dummy.py +++ b/postgresqleu/util/payment/dummy.py @@ -1,7 +1,7 @@ from postgresqleu.invoices.models import Invoice class DummyPayment(object): - description=""" + description = """ This is a payment method purely for debugging. If you see this in production, please let the administrator know immediately! """ diff --git a/postgresqleu/util/payment/paypal.py b/postgresqleu/util/payment/paypal.py index 178a5d6d..587576b7 100644 --- a/postgresqleu/util/payment/paypal.py +++ b/postgresqleu/util/payment/paypal.py @@ -7,7 +7,7 @@ from postgresqleu.paypal.models import TransactionInfo from postgresqleu.paypal.util import PaypalAPI class Paypal(object): - description=""" + description = """ Pay using Paypal. You can use this both to pay from your Paypal balance if you have a Paypal account, or you can use it to pay with any credit card supported by Paypal (Visa, Mastercard, American Express). @@ -17,7 +17,7 @@ with credit card. However, we do recommend using the payment method called lower fees. """ - PAYPAL_COMMON={ + PAYPAL_COMMON = { 'business':settings.PAYPAL_EMAIL, 'lc':'GB', 'currency_code': settings.CURRENCY_ABBREV, diff --git a/postgresqleu/util/payment/trustly.py b/postgresqleu/util/payment/trustly.py index e4647eae..3de79a13 100644 --- a/postgresqleu/util/payment/trustly.py +++ b/postgresqleu/util/payment/trustly.py @@ -9,7 +9,7 @@ from postgresqleu.trustlypayment.api import TrustlyException class TrustlyPayment(object): - description=""" + description = """ Pay directly using online banking. Currently supported with most banks in {0}. """.format(', '.join(settings.TRUSTLY_COUNTRIES)) diff --git a/postgresqleu/util/validators.py b/postgresqleu/util/validators.py index ede5f67d..942e17d0 100644 --- a/postgresqleu/util/validators.py +++ b/postgresqleu/util/validators.py @@ -53,14 +53,14 @@ def validate_json_structure(config, structure): def _validate_json_level(config, structure, path): missing = set(structure.keys()).difference(set(config.keys())) if missing: - raise ValidationError("Keys {0} are missing".format(", ".join(["->".join(path+[m]) for m in missing]))) + raise ValidationError("Keys {0} are missing".format(", ".join(["->".join(path + [m]) for m in missing]))) extra = set(config.keys()).difference(set(structure.keys())) if extra: - raise ValidationError("Keys {0} are not allowed".format(", ".join(["->".join(path+[m]) for m in extra]))) + raise ValidationError("Keys {0} are not allowed".format(", ".join(["->".join(path + [m]) for m in extra]))) # Keys are correct, validate datatypes for k,v in config.items(): - fullkey = "->".join(path+[k]) + fullkey = "->".join(path + [k]) # Dicts don't have __name__ if type(structure[k]) == dict: structtype = dict @@ -73,7 +73,7 @@ def validate_json_structure(config, structure): raise ValidationError("Value for {0} should be of type {1}, not {2}".format(fullkey, structname, valname)) if isinstance(v, dict): # Recursively check substructure - _validate_json_level(v, structure[k], path+[k]) + _validate_json_level(v, structure[k], path + [k]) _validate_json_level(config, structure, []) @@ -97,7 +97,7 @@ class PictureUrlValidator(object): img = Image.open(StringIO(r.content)) w,h = img.size if self.aspect: - newaspect = round(float(w)/float(h), 2) + newaspect = round(float(w) / float(h), 2) if newaspect != self.aspect: raise ValidationError("Image has aspect ratio %s, must have %s" % (newaspect, self.aspect)) |
