supporters: Apply Black formatter

This commit is contained in:
Ben Sturmfels 2024-10-23 18:16:47 +11:00
parent 68c5199bb5
commit c843e1c59f
Signed by: bsturmfels
GPG key ID: 023C05E2C9C068F0
3 changed files with 47 additions and 29 deletions

View file

@ -3,6 +3,7 @@ from django.utils.safestring import mark_safe
from django.urls import reverse
from .models import SustainerOrder
class SustainerFormRenderer(forms.renderers.DjangoTemplates):
# Customised layout with labels on own row
field_template_name = 'supporters/field.html'
@ -10,6 +11,7 @@ class SustainerFormRenderer(forms.renderers.DjangoTemplates):
class ButtonRadioSelect(forms.widgets.RadioSelect):
"""Radio button styled like a button. BYO CSS."""
# Extra <span> wrappers to support CSS
option_template_name = 'supporters/buttonradio_option.html'
use_fieldset = False
@ -52,11 +54,13 @@ class SustainerForm(forms.ModelForm):
'country',
]
widgets = {
'recurring': ButtonRadioSelect(attrs={
'x-model': 'recurring',
# Reset the amount field and option when changing monthly/annually.
'x-on:change': '$refs.amount.value = null; amount_option = null',
}),
'recurring': ButtonRadioSelect(
attrs={
'x-model': 'recurring',
# Reset the amount field and option when changing monthly/annually.
'x-on:change': '$refs.amount.value = null; amount_option = null',
}
),
}
def __init__(self, *args, **kwargs):
@ -72,7 +76,9 @@ class SustainerForm(forms.ModelForm):
self.fields['amount'].widget.attrs['onblur'] = 'this.reportValidity()'
self.fields['amount'].widget.attrs['x-bind:min'] = 'amount_minimum'
self.fields['email'].help_text = 'For your payment receipt'
self.fields['tshirt_size'].help_text = mark_safe("""Sizing chart: <a href="/videos/women-2017-to-2020-t-shirt-sizing.jpg" target="_blank" class="black-60">Women's</a>, <a href="/videos/men-2017-to-2020-t-shirt-sizing.jpg" target="_blank" class="black-60">Men's</a>""")
self.fields['tshirt_size'].help_text = mark_safe(
"""Sizing chart: <a href="/videos/women-2017-to-2020-t-shirt-sizing.jpg" target="_blank" class="black-60">Women's</a>, <a href="/videos/men-2017-to-2020-t-shirt-sizing.jpg" target="_blank" class="black-60">Men's</a>"""
)
self.fields['tshirt_size'].widget.attrs['x-model'] = 'tshirt_size'
def clean(self):
@ -84,15 +90,16 @@ class SustainerForm(forms.ModelForm):
if amount < minimum:
self.add_error(
'',
mark_safe(f'${minimum:d} is a minimum for Conservancy Sustainers. <a href="{donate_url}">Donate smaller amounts here</a>.')
mark_safe(
f'${minimum:d} is a minimum for Conservancy Sustainers. <a href="{donate_url}">Donate smaller amounts here</a>.'
),
)
tshirt_size = self.cleaned_data.get('tshirt_size')
if tshirt_size and not all([
if tshirt_size and not all(
[
self.cleaned_data.get('street'),
self.cleaned_data.get('city'),
self.cleaned_data.get('country')
]):
self.add_error(
'street',
'No address provided'
)
self.cleaned_data.get('country'),
]
):
self.add_error('street', 'No address provided')

View file

@ -5,7 +5,9 @@ class Supporter(models.Model):
"""Conservancy Supporter listing"""
display_name = models.CharField(max_length=200, blank=False)
display_until_date = models.DateTimeField("date until which this supporter name is displayed")
display_until_date = models.DateTimeField(
"date until which this supporter name is displayed"
)
ledger_entity_id = models.CharField(max_length=200, blank=False)
def test(self):
@ -65,13 +67,17 @@ class SustainerOrder(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
amount = models.PositiveIntegerField()
recurring = models.CharField(max_length=10, choices=RENEW_CHOICES, blank=True, default='')
recurring = models.CharField(
max_length=10, choices=RENEW_CHOICES, blank=True, default=''
)
payment_method = models.CharField(max_length=10, default='Stripe')
payment_id = models.CharField(max_length=255, blank=True)
paid_time = models.DateTimeField(null=True, blank=True)
acknowledge_publicly = models.BooleanField(default=True)
add_to_mailing_list = models.BooleanField(default=True)
tshirt_size = models.CharField('T-shirt size', max_length=50, choices=TSHIRT_CHOICES, blank=True, default='')
tshirt_size = models.CharField(
'T-shirt size', max_length=50, choices=TSHIRT_CHOICES, blank=True, default=''
)
street = models.CharField(max_length=255, blank=True)
city = models.CharField(max_length=255, blank=True)
state = models.CharField(max_length=255, blank=True)

View file

@ -13,6 +13,7 @@ from .models import Supporter, SustainerOrder
logger = logging.getLogger(__name__)
def sustainers(request):
with ParameterValidator(request.GET, 'upgrade_id') as validator:
try:
@ -36,17 +37,19 @@ def sponsors(request):
"""
supporters = Supporter.objects.all().filter(display_until_date__gte=datetime.now())
supporters_count = len(supporters)
anonymous_count = len(supporters.filter(display_name='Anonymous'))
anonymous_count = len(supporters.filter(display_name='Anonymous'))
supporters = supporters.exclude(display_name='Anonymous').order_by('ledger_entity_id')
c = {
'supporters' : supporters,
'supporters_count' : supporters_count,
'anonymous_count' : anonymous_count
'supporters': supporters,
'supporters_count': supporters_count,
'anonymous_count': anonymous_count,
}
return render(request, "supporters/sponsors.html", c)
def create_checkout_session(reference_id, email: str, amount: int, recurring: str, base_url: str):
def create_checkout_session(
reference_id, email: str, amount: int, recurring: str, base_url: str
):
# https://docs.stripe.com/payments/accept-a-payment
# https://docs.stripe.com/api/checkout/sessions
YOUR_DOMAIN = base_url
@ -85,7 +88,9 @@ def sustainers_stripe(request):
if form.is_valid():
order = form.save()
base_url = f'{request.scheme}://{request.get_host()}'
stripe_checkout_url = create_checkout_session(order.id, order.email, order.amount, order.recurring, base_url)
stripe_checkout_url = create_checkout_session(
order.id, order.email, order.amount, order.recurring, base_url
)
return redirect(stripe_checkout_url)
else:
form = forms.SustainerForm()
@ -121,7 +126,9 @@ def fulfill_checkout(session_id):
# Checkout Session
logger.info(f'Session ID {session_id} PAID!')
try:
order = SustainerOrder.objects.get(id=checkout_session['client_reference_id'], paid_time=None)
order = SustainerOrder.objects.get(
id=checkout_session['client_reference_id'], paid_time=None
)
order.paid_time = timezone.now()
if checkout_session['payment_intent']:
# Payments get a payment intent directly
@ -151,9 +158,7 @@ def webhook(request):
logger.warning('Missing STRIPE_ENDPOINT_SECRET')
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
except ValueError:
# Invalid payload
return HttpResponse(status=400)
@ -162,8 +167,8 @@ def webhook(request):
return HttpResponse(status=400)
if (
event['type'] == 'checkout.session.completed'
or event['type'] == 'checkout.session.async_payment_succeeded'
event['type'] == 'checkout.session.completed'
or event['type'] == 'checkout.session.async_payment_succeeded'
):
fulfill_checkout(event['data']['object']['id'])