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 django.urls import reverse
from .models import SustainerOrder from .models import SustainerOrder
class SustainerFormRenderer(forms.renderers.DjangoTemplates): class SustainerFormRenderer(forms.renderers.DjangoTemplates):
# Customised layout with labels on own row # Customised layout with labels on own row
field_template_name = 'supporters/field.html' field_template_name = 'supporters/field.html'
@ -10,6 +11,7 @@ class SustainerFormRenderer(forms.renderers.DjangoTemplates):
class ButtonRadioSelect(forms.widgets.RadioSelect): class ButtonRadioSelect(forms.widgets.RadioSelect):
"""Radio button styled like a button. BYO CSS.""" """Radio button styled like a button. BYO CSS."""
# Extra <span> wrappers to support CSS # Extra <span> wrappers to support CSS
option_template_name = 'supporters/buttonradio_option.html' option_template_name = 'supporters/buttonradio_option.html'
use_fieldset = False use_fieldset = False
@ -52,11 +54,13 @@ class SustainerForm(forms.ModelForm):
'country', 'country',
] ]
widgets = { widgets = {
'recurring': ButtonRadioSelect(attrs={ 'recurring': ButtonRadioSelect(
attrs={
'x-model': 'recurring', 'x-model': 'recurring',
# Reset the amount field and option when changing monthly/annually. # Reset the amount field and option when changing monthly/annually.
'x-on:change': '$refs.amount.value = null; amount_option = null', 'x-on:change': '$refs.amount.value = null; amount_option = null',
}), }
),
} }
def __init__(self, *args, **kwargs): 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['onblur'] = 'this.reportValidity()'
self.fields['amount'].widget.attrs['x-bind:min'] = 'amount_minimum' self.fields['amount'].widget.attrs['x-bind:min'] = 'amount_minimum'
self.fields['email'].help_text = 'For your payment receipt' 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' self.fields['tshirt_size'].widget.attrs['x-model'] = 'tshirt_size'
def clean(self): def clean(self):
@ -84,15 +90,16 @@ class SustainerForm(forms.ModelForm):
if amount < minimum: if amount < minimum:
self.add_error( 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') 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('street'),
self.cleaned_data.get('city'), self.cleaned_data.get('city'),
self.cleaned_data.get('country') self.cleaned_data.get('country'),
]): ]
self.add_error( ):
'street', self.add_error('street', 'No address provided')
'No address provided'
)

View file

@ -5,7 +5,9 @@ class Supporter(models.Model):
"""Conservancy Supporter listing""" """Conservancy Supporter listing"""
display_name = models.CharField(max_length=200, blank=False) 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) ledger_entity_id = models.CharField(max_length=200, blank=False)
def test(self): def test(self):
@ -65,13 +67,17 @@ class SustainerOrder(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
email = models.EmailField() email = models.EmailField()
amount = models.PositiveIntegerField() 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_method = models.CharField(max_length=10, default='Stripe')
payment_id = models.CharField(max_length=255, blank=True) payment_id = models.CharField(max_length=255, blank=True)
paid_time = models.DateTimeField(null=True, blank=True) paid_time = models.DateTimeField(null=True, blank=True)
acknowledge_publicly = models.BooleanField(default=True) acknowledge_publicly = models.BooleanField(default=True)
add_to_mailing_list = 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) street = models.CharField(max_length=255, blank=True)
city = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=255, blank=True)
state = 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__) logger = logging.getLogger(__name__)
def sustainers(request): def sustainers(request):
with ParameterValidator(request.GET, 'upgrade_id') as validator: with ParameterValidator(request.GET, 'upgrade_id') as validator:
try: try:
@ -41,12 +42,14 @@ def sponsors(request):
c = { c = {
'supporters': supporters, 'supporters': supporters,
'supporters_count': supporters_count, 'supporters_count': supporters_count,
'anonymous_count' : anonymous_count 'anonymous_count': anonymous_count,
} }
return render(request, "supporters/sponsors.html", c) 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/payments/accept-a-payment
# https://docs.stripe.com/api/checkout/sessions # https://docs.stripe.com/api/checkout/sessions
YOUR_DOMAIN = base_url YOUR_DOMAIN = base_url
@ -85,7 +88,9 @@ def sustainers_stripe(request):
if form.is_valid(): if form.is_valid():
order = form.save() order = form.save()
base_url = f'{request.scheme}://{request.get_host()}' 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) return redirect(stripe_checkout_url)
else: else:
form = forms.SustainerForm() form = forms.SustainerForm()
@ -121,7 +126,9 @@ def fulfill_checkout(session_id):
# Checkout Session # Checkout Session
logger.info(f'Session ID {session_id} PAID!') logger.info(f'Session ID {session_id} PAID!')
try: 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() order.paid_time = timezone.now()
if checkout_session['payment_intent']: if checkout_session['payment_intent']:
# Payments get a payment intent directly # Payments get a payment intent directly
@ -151,9 +158,7 @@ def webhook(request):
logger.warning('Missing STRIPE_ENDPOINT_SECRET') logger.warning('Missing STRIPE_ENDPOINT_SECRET')
try: try:
event = stripe.Webhook.construct_event( event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
payload, sig_header, endpoint_secret
)
except ValueError: except ValueError:
# Invalid payload # Invalid payload
return HttpResponse(status=400) return HttpResponse(status=400)