Anna Sirota
239efb267f
Looks like 806e9e2d0d
changed behaviour of `FIELD_set` causing `ValueError` when
`.billing_address` and `.subscription_set` are accessed on a `Customer`
that hadn't been yet saved to the database.
42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
import logging
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.db import transaction
|
|
from django.db.models.signals import post_save
|
|
from django.dispatch import receiver
|
|
|
|
from looper.models import Customer
|
|
|
|
User = get_user_model()
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@receiver(post_save, sender=User)
|
|
def _create_customer(sender, instance: User, created, raw, **kwargs):
|
|
if raw:
|
|
return
|
|
|
|
if not created:
|
|
return
|
|
|
|
try:
|
|
customer = instance.customer
|
|
except Customer.DoesNotExist:
|
|
pass
|
|
else:
|
|
log_args = [instance.pk, customer.pk]
|
|
logger.debug('User pk=%d already has a customer pk=%d, not creating new one', *log_args)
|
|
billing_address = customer.billing_address
|
|
if not billing_address.pk:
|
|
logger.info('Creating billing address for user pk=%d customer pk=%d', *log_args)
|
|
billing_address.email = instance.email
|
|
billing_address.save()
|
|
return
|
|
|
|
logger.info('Creating new Customer due to creation of user %s', instance.pk)
|
|
with transaction.atomic():
|
|
customer = Customer.objects.create(user=instance)
|
|
billing_address = customer.billing_address
|
|
billing_address.email = instance.email
|
|
billing_address.save()
|