[Answered ]-Django โ€“ automatically create User on Athlete create (tied together with a OneToOneField)

1๐Ÿ‘

โœ…

You now use another model as user model, so that means that you also use this to register users, so:

from users.models import User

class Athlete(models.Model):
    user = models.OneToOneField(User, blank=True, null=True, on_delete=models.SET_NULL)
    coach = models.ForeignKey(Coach, blank=True, null=True, on_delete=models.SET_NULL, related_name='coach')

    def save(self, *args, **kwargs, email=None):
        try:
            self.user = User.objects.get(email=email)
        except User.DoesNotExist:
            self.user = new_user = User.objects.create_user(email=email)
        super().save(*args, **kwargs)

Leave a comment