Advertisement
horozov86

managers.py

Oct 23rd, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.40 KB | None | 0 0
  1. from django.contrib import auth
  2. from django.contrib.auth import models as auth_models
  3. from django.contrib.auth.hashers import make_password
  4.  
  5.  
  6. class TransgramUserManager(auth_models.BaseUserManager):
  7.     use_in_migrations = True
  8.  
  9.     def _create_user(self, email, password, **extra_fields):
  10.         """
  11.        Create and save a user with the given username, email, and password.
  12.        """
  13.         if not email:
  14.             raise ValueError("The given email must be set")
  15.         email = self.normalize_email(email)
  16.         user = self.model(email=email, **extra_fields)
  17.         user.password = make_password(password)
  18.         user.save(using=self._db)
  19.         return user
  20.  
  21.     def create_user(self, email, password=None, **extra_fields):
  22.         extra_fields.setdefault("is_staff", False)
  23.         extra_fields.setdefault("is_superuser", False)
  24.         return self._create_user(email, password, **extra_fields)
  25.  
  26.     def create_superuser(self, email, password=None, **extra_fields):
  27.         extra_fields.setdefault("is_staff", True)
  28.         extra_fields.setdefault("is_superuser", True)
  29.  
  30.         if extra_fields.get("is_staff") is not True:
  31.             raise ValueError("Superuser must have is_staff=True.")
  32.         if extra_fields.get("is_superuser") is not True:
  33.             raise ValueError("Superuser must have is_superuser=True.")
  34.  
  35.         return self._create_user(email, password, **extra_fields)
  36.  
  37.     def with_perm(
  38.             self, perm, is_active=True, include_superusers=True, backend=None, obj=None
  39.     ):
  40.         if backend is None:
  41.             backends = auth._get_backends(return_tuples=True)
  42.             if len(backends) == 1:
  43.                 backend, _ = backends[0]
  44.             else:
  45.                 raise ValueError(
  46.                     "You have multiple authentication backends configured and "
  47.                     "therefore must provide the `backend` argument."
  48.                 )
  49.         elif not isinstance(backend, str):
  50.             raise TypeError(
  51.                 "backend must be a dotted import path string (got %r)." % backend
  52.             )
  53.         else:
  54.             backend = auth.load_backend(backend)
  55.         if hasattr(backend, "with_perm"):
  56.             return backend.with_perm(
  57.                 perm,
  58.                 is_active=is_active,
  59.                 include_superusers=include_superusers,
  60.                 obj=obj,
  61.             )
  62.         return self.none()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement