managers.py 1.2 KB

123456789101112131415161718192021222324252627282930
  1. from django.contrib.auth.models import UserManager as UM
  2. from django.contrib.auth.hashers import make_password
  3. class UserManager(UM):
  4. def _create_user(self, email, password, **extra_fields):
  5. if not email:
  6. raise ValueError("The given email must be set")
  7. email = self.normalize_email(email)
  8. user = self.model(email=email, **extra_fields)
  9. user.password = make_password(password)
  10. user.save(using=self._db)
  11. return user
  12. def create_user(self, email=None, password=None, **extra_fields):
  13. extra_fields.setdefault("is_staff", False)
  14. extra_fields.setdefault("is_superuser", False)
  15. return self._create_user(email, password, **extra_fields)
  16. def create_superuser(self, email=None, password=None, **extra_fields):
  17. extra_fields.setdefault("is_staff", True)
  18. extra_fields.setdefault("is_superuser", True)
  19. if extra_fields.get("is_staff") is not True:
  20. raise ValueError("Superuser must have is_staff=True.")
  21. if extra_fields.get("is_superuser") is not True:
  22. raise ValueError("Superuser must have is_superuser=True.")
  23. return self._create_user(email, password, **extra_fields)