blender-studio/subscriptions/views/mixins.py
Anna Sirota dd367f1476 Stripe checkout (#104411)
The goal of this change is the following:

* make Stripe a default payment gateway:
	* for newly created subscriptions;
	* for paying for existing orders;
    * for changing payment method on existing subscriptions;

Reviewed-on: #104411
Reviewed-by: Oleg-Komarov <oleg-komarov@noreply.localhost>
2024-06-17 18:08:39 +02:00

58 lines
1.8 KiB
Python

"""Reusable mixins for views handling subscription management."""
from typing import Optional
import logging
from django.contrib.auth.mixins import LoginRequiredMixin
from django.forms.utils import ErrorList
from django.shortcuts import get_object_or_404
from looper.models import Subscription
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class BootstrapErrorList(ErrorList):
"""Render errors with Bootstrap classes."""
def as_ul(self) -> str:
"""Render as ul."""
if not self:
return ''
return '<ul class="errorlist alert alert-danger">{}</ul>'.format(
''.join([f'<li class="error">{e}</li>' for e in self])
)
class SingleSubscriptionMixin(LoginRequiredMixin):
"""Get a single subscription of a logged in user."""
@property
def subscription_id(self) -> int:
"""Retrieve subscription ID."""
return self.kwargs['subscription_id']
def get_subscription(self) -> Subscription:
"""Retrieve Subscription object."""
return get_object_or_404(
self.request.user.customer.subscription_set, pk=self.subscription_id
)
def get_context_data(self, **kwargs) -> dict:
"""Add Subscription to the template context."""
subscription: Optional[Subscription] = self.get_subscription()
return {
**super().get_context_data(**kwargs),
'subscription': subscription,
}
class BootstrapErrorListMixin:
"""Override get_form method changing error_class of the form."""
def get_form(self, *args, **kwargs):
"""Override form error list class with a Bootstrap-compatible one."""
form = super().get_form(*args, **kwargs)
form.error_class = BootstrapErrorList
return form