class User(AbstractBaseUser, PermissionsMixin, IndexedTimeStampedModel): email = models.EmailField(max_length=255, unique=True) is_staff = models.BooleanField( default=False, help_text=_( "Designates whether the user can log into this admin site."), ) is_active = models.BooleanField( default=True, help_text=_("Designates whether this user should be treated as " "active. Unselect this instead of deleting accounts."), ) objects = UserManager() USERNAME_FIELD = "email" def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email
class User(AbstractBaseUser, PermissionsMixin): """ User model class """ first_name = models.CharField(_('first_name'), max_length=50, blank=True, null=True) last_name = models.CharField(_('last_name'), max_length=50, blank=True, null=True) username = models.CharField(_('username'), max_length=120, unique=True) email = models.EmailField(_('email'), unique=True) is_staff = models.BooleanField(_('staff_status'), default=False) is_active = models.BooleanField(_('active'), default=True) date_joined = models.DateTimeField(_('date_joined'), auto_now_add=True) is_deleted = models.BooleanField(_('is_deleted'), default=False) USERNAME_FIELD = 'email' objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') ordering = ('-date_joined', ) def __str__(self): return str(self.email) def soft_delete(self): self.is_deleted = True self.save()
class User(AbstractBaseUser, PermissionsMixin, IndexedTimeStampedModel): email = models.EmailField(max_length=255, unique=True) is_staff = models.BooleanField( default=False, help_text=_( "Designates whether the user can log into this admin site."), ) is_active = models.BooleanField( default=True, help_text= _("Designates whether this user should be treated as active. Unselect this instead of deleting accounts." ), ) organizations = models.ManyToManyField("organizations.Organization", through="users.OrganizationUser") objects = UserManager() USERNAME_FIELD = "email" def get_full_name(self): return self.email def get_short_name(self): return self.email def get_role_assignment(self): try: return self.roleassignment except self.__class__.roleassignment.RelatedObjectDoesNotExist: return None def __str__(self): return self.email
class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True, db_index=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' objects = UserManager()
class UserManagerTestCase(TestCase): TEST_DATA = {'email': '*****@*****.**', 'password': '******'} def setUp(self): self.test_manager = UserManager() self.test_manager.model = User def validate_user(self, user): self.assertEqual(user.email, self.TEST_DATA['email']) self.assertTrue(user.check_password(self.TEST_DATA['password'])) def test_create_user(self): user = self.test_manager.create_user(**self.TEST_DATA) self.validate_user(user) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) def test_create_superuser(self): user = self.test_manager.create_superuser(**self.TEST_DATA) self.validate_user(user) self.assertTrue(user.is_staff) self.assertTrue(user.is_superuser)
class User(AbstractUser): username = None email = models.EmailField(unique=True, null=True, db_index=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) user_type = models.PositiveSmallIntegerField( choices=user_constants.USER_TYPE_CHOICES) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' objects = UserManager()
class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=False, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.'), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' class Meta: verbose_name = _('user') verbose_name_plural = _('users') def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """Return the short name for the user.""" return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs)
class User(AbstractBaseUser, PermissionsMixin): phone = models.CharField(_('username'), max_length=20, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff status'), default=False) user_type = models.IntegerField(choices=UserType.get_choices()) city = models.ForeignKey(City, related_name='user_set', on_delete=models.SET_NULL, null=True) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [ 'user_type', ] class Meta: verbose_name = _('user') verbose_name_plural = _('users') @property def get_avatar(self): """ returns the url of the user avatar :return: """ try: return self.avatar.url except ValueError: return None def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """ Returns the short name for the user. """ return self.first_name
def setUp(self): self.test_manager = UserManager() self.test_manager.model = User
class User(AbstractUser): username = None email = models.EmailField(verbose_name=_('email address'), unique=True) role = models.ForeignKey('users.Role', verbose_name=_('Role'), related_name='users', on_delete=models.CASCADE, null=True) PRESIDENT = 'AD' VICE_PRESIDENT = 'KP' ACCOUNTANT = 'PM' CARBONIZER = 'NA' FUNCTION_CHOICES = ( (PRESIDENT, _('President Malebi')), (VICE_PRESIDENT, _('Vice President')), (ACCOUNTANT, _('Malebi\'s Rep - Accountant')), (CARBONIZER, _('Carbonizer')), ) function = models.CharField(verbose_name=_('Function'), max_length=2, choices=FUNCTION_CHOICES, blank=True) code = models.CharField(verbose_name=_('Code'), max_length=8, blank=True) contact = models.CharField(verbose_name=_('Contact'), max_length=16, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() private_key_str = models.CharField(max_length=128, blank=True) public_key = models.CharField(max_length=128, blank=True) @property def private_key(self): return Secp256k1PrivateKey.from_hex(self.private_key_str) @property def is_superuser_role(self): return self.is_superuser or (self.role is not None and self.role.name == 'SUPER_USER') @property def is_director(self): return self.role is not None and self.role.name == 'DIRECTOR' @property def is_logger(self): return self.role is not None and self.role.name == 'LOGGER' @property def is_carbonizer(self): return self.role is not None and self.role.name == 'CARBONIZER' def save(self, *args, **kwargs): superuser_role, _ = Role.objects.get_or_create(name='SUPER_USER') if self.is_superuser and not self.role: self.role = superuser_role elif not self.is_superuser and self.role == superuser_role: self.role = None if not self.private_key_str: private_key = swt.context.new_random_private_key() self.private_key_str = private_key.as_hex() self.public_key = swt.context.get_public_key(private_key).as_hex() super().save(*args, **kwargs) if not self.code: self.code = f'AM{self.id:03d}{self.function}' self.save() def get_proto(self): return self._build_proto() def _build_proto(self): proto = Agent( email=self.email, role=getattr(Agent, self.role.name), public_key=self.public_key, ) return proto def add_to_chain(self): return BlockTransactionFactory.send( protos=[self._build_proto()], signer_key=self.private_key, payload_type=PayloadFactory.Types.CREATE_AGENT, )
class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField('Имя', max_length=30, blank=True, null=True) last_name = models.CharField('Фамилия', max_length=30, blank=True, null=True) email = models.EmailField('E-mail', unique=True) date_joined = models.DateTimeField('Дата присоединения', default=timezone.now) is_activated = models.BooleanField( 'E-mail подтверждён', default=True, help_text='Указывает, что пользователь подтвердил свой e-mail.') is_staff = models.BooleanField( 'Статус персонала', default=False, help_text= 'Указывает, что пользователь имеет доступ к панели администратора.') is_active = models.BooleanField( 'Активен', default=True, help_text= 'Указывает, что пользователь активен. Используйте вместо удаления аккаунта.' ) moderated = models.BooleanField( 'Прошёл модерацию', default=True, help_text='Указывает, что пользователь прошёл модерацию.') activation_code = models.CharField('Код активации', max_length=32, blank=True, null=True) reset_password_code = models.CharField('Код сброса пароля', max_length=32, blank=True, null=True) USERNAME_FIELD = 'email' objects = UserManager() class Meta: verbose_name = 'пользователь' verbose_name_plural = 'пользователи' def get_short_name(self): if self.first_name: short_name = self.first_name else: short_name = self.email.split('@')[0] return short_name.strip() def get_full_name(self): if self.first_name or self.last_name: full_name = '%s %s' % (self.first_name, self.last_name) else: full_name = self.email.split('@')[0] return full_name.strip() def email_user(self, subject, message, from_email=None): send_mail(subject, message, from_email, [self.email]) def send_activation_email(self, email=None): if email: self.email = email self.is_activated = False self.activation_code = hashlib.sha256( self.email.encode('utf-8') + os.urandom(256)).hexdigest()[:32] self.save() subject = 'Добро пожаловать на {0}!'.format(settings.SITE_NAME) message = render_to_string( 'users/emails/activation.html', { 'code': self.activation_code, 'site_name': settings.SITE_NAME, 'site_domain': settings.SITE_DOMAIN }) self.email_user(subject, message, settings.SITE_EMAIL) def send_new_password_email(self): self.reset_password_code = hashlib.sha256( self.email.encode('utf-8') + os.urandom(256)).hexdigest()[:32] self.save() subject = 'Сброс пароля на {0}.'.format(settings.SITE_NAME) message = render_to_string( 'users/emails/new_password.html', { 'code': self.reset_password_code, 'site_name': settings.SITE_NAME, 'site_domain': settings.SITE_DOMAIN, 'site_email': settings.SITE_EMAIL }) self.email_user(subject, message, settings.SITE_EMAIL)
class User(AbstractBaseUser, PermissionsMixin): """Custom user model. Attributes: first_name (str): First name. last_name (str): Last, family name. email (str): E-mail, uses for authentication. is_active (bool): Can user log in to the system. is_staff (bool): Can user access to admin interface. date_joined (datetime): Date when the account was created. role (str): Role of user (artist or customer). phone_number (str): Phone number. Nested attributes: is_superuser (bool): The user can super access to admin UI. groups(Manager): The groups this user belongs to. user_permissions(Manager): Specified permissions for this user. last_login (datetime): Last date when user login to the system. """ EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' ROLES = models.TextChoices('ROLES', (CUSTOMER_ROLE, ARTIST_ROLE)) first_name = models.CharField( max_length=255, verbose_name=_('First name'), ) last_name = models.CharField( max_length=255, verbose_name=_('Last name'), ) email = models.EmailField( max_length=255, unique=True, verbose_name=_('Email'), ) is_active = models.BooleanField( default=True, verbose_name=_('Is active'), ) is_staff = models.BooleanField( default=False, verbose_name=_('Is staff'), help_text=_('The user will have access to admin interface.'), ) date_joined = models.DateTimeField( auto_now_add=True, verbose_name=_('Date joined'), ) role = models.CharField( max_length=255, choices=ROLES.choices, null=True, verbose_name=_('Role'), help_text=_('The user is artist or customer.'), ) phone_number = PhoneNumberField( null=True, blank=True, verbose_name=_('Phone number'), help_text=_('Users phone number. ' 'It has to be a phone number with country code.'), ) objects = UserManager() class Meta: db_table = 'users' ordering = ('email', ) verbose_name = _('User') verbose_name_plural = _('Users') def __str__(self): return self.email def save(self, *args, **kwargs): """Save user method. Save role field in uppercase. """ if self.role: self.role = self.role.upper() super().save(*args, **kwargs) def get_full_name(self): """Return last name and first name of user.""" full_name = '{first_name} {last_name}'.format( first_name=self.last_name, last_name=self.first_name, ) return full_name.strip() def get_short_name(self): """Return first name of user.""" return self.first_name def get_admin_change_url(self) -> str: """Get admin change URL. Build full url (host + path) to standard Django admin page for object like: https://api.sitename.com/admin/users/user/234/ """ assert self.id, "Instance must have an ID" return urljoin( settings.DJANGO_SITE_BASE_HOST, reverse('admin:users_user_change', args=(self.id, )), ) @property def rating(self): """Return the user's rating for all orders completed by him.""" feedbacks = Masterpiece.objects.filter( artist=self, customer_rate__isnull=False).values_list('customer_rate', flat=True) if feedbacks: return round(mean(feedbacks), 2) @property def completed_orders_count(self): """Return count of completed by user orders.""" return self.masterpieces.filter(order__isnull=False).count()