Coverage for accounts / signals.py: 100%

8 statements  

« prev     ^ index     » next       coverage.py v7.13.2, created at 2026-03-10 14:10 +0000

1from django.db.models.signals import pre_save 

2from django.dispatch import receiver 

3from .models import CustomUser 

4 

5 

6@receiver(pre_save, sender=CustomUser) 

7def email_is_also_username(sender, instance, **kwargs): 

8 '''Force the username field to be the same as the email field 

9 

10 Prevent duplication of email addresses in the CustomUser model at the database level. 

11 

12 - there could be duplicate emails in the database, thus leaving a potential issue with duplicate emails in the database 

13 - We do not want duplicate emails in the database, because we are logging in by email address 

14 - ``Warning``: do not use this CustomUser model if you wish to have usernames that are other than the user's email address 

15 - see: https://docs.allauth.org/en/latest/ 

16 - see: https://docs.allauth.org/en/latest/account/configuration.html 

17 

18 We are using a pre_save signal decorator 

19 to force username field to be set to the records email field value for all CustomUser records 

20 

21 ''' 

22 if instance.username != instance.email: 

23 print(f"{instance.__class__.__name__} changed username from {instance.username} to {instance.email}") 

24 instance.username = instance.email