我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.AUTH_USER_MODEL。
def skipIfCustomUser(test_func): """ Skip a test if a custom user model is in use. """ warnings.warn( "django.contrib.auth.tests.utils.skipIfCustomUser is deprecated.", RemovedInDjango20Warning, stacklevel=2) return skipIf(settings.AUTH_USER_MODEL != 'auth.User', 'Custom user model in use')(test_func)
def get_user_model(): """ Returns the User model that is active in this project. """ try: return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL )
def __init__(self, real_apps, models, ignore_swappable=False): # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) self.real_models = [] for app_label in real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): self.real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [AppConfigStub(label) for label in sorted(real_apps + list(app_labels))] super(StateApps, self).__init__(app_configs) self.render_multiple(list(models.values()) + self.real_models) # There shouldn't be any operations pending at this point. from django.core.checks.model_checks import _check_lazy_references ignore = {make_model_tuple(settings.AUTH_USER_MODEL)} if ignore_swappable else set() errors = _check_lazy_references(self, ignore=ignore) if errors: raise ValueError("\n".join(error.msg for error in errors))
def forwards(apps, schema_editor): user_model = apps.get_model(settings.AUTH_USER_MODEL) ph_model = apps.get_model('cms', 'Placeholder') page_model = apps.get_model('cms', 'Page') try: ph_ctype = ContentType.objects.get_for_model(ph_model) page_ctype = ContentType.objects.get_for_model(page_model) permission, __ = Permission.objects.get_or_create( codename='use_structure', content_type=ph_ctype, name=u"Can use Structure mode") page_permission, __ = Permission.objects.get_or_create(codename='change_page', content_type=page_ctype) for user in user_model.objects.filter(is_superuser=False, is_staff=True): if user.user_permissions.filter(codename='change_page', content_type_id=page_ctype.pk).exists(): user.user_permissions.add(permission.pk) for group in Group.objects.all(): if page_permission in group.permissions.all(): group.permissions.add(permission.pk) except Exception: warnings.warn(u'Users not migrated to use_structure permission, please add the permission manually')
def __init__(self, real_apps, models, ignore_swappable=False): # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) self.real_models = [] for app_label in real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): self.real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [AppConfigStub(label) for label in sorted(real_apps + list(app_labels))] super(StateApps, self).__init__(app_configs) self.render_multiple(list(models.values()) + self.real_models) # There shouldn't be any operations pending at this point. pending_models = set(self._pending_operations) if ignore_swappable: pending_models -= {make_model_tuple(settings.AUTH_USER_MODEL)} if pending_models: raise ValueError(self._pending_models_error(pending_models))
def get_user_model(): """ Returns the User model that is active in this project. """ try: return django_apps.get_model(settings.AUTH_USER_MODEL) except ValueError: raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL )
def test_check_custom_user_model_default_admin(self): # Django doesn't re-register admins when using `override_settings`, # so we have to do it manually in this test case. admin.site.register(get_user_model(), UserAdmin) warnings = checks.check_custom_user_model(HijackAdminConfig) expected_warnings = [ Warning( 'django-hijack-admin does not work out the box with a custom user model.', hint='Please mix HijackUserAdminMixin into your custom UserAdmin.', obj=settings.AUTH_USER_MODEL, id='hijack_admin.W001', ) ] self.assertEqual(warnings, expected_warnings) admin.site.unregister(get_user_model())
def check_custom_user_model(app_configs, **kwargs): warnings = [] if (settings.AUTH_USER_MODEL != DEFAULT_AUTH_USER_MODEL and not _using_hijack_admin_mixin()): warnings.append( Warning( 'django-hijack-admin does not work out the box with a custom user model.', hint='Please mix HijackUserAdminMixin into your custom UserAdmin.', obj=settings.AUTH_USER_MODEL, id='hijack_admin.W001', ) ) return warnings
def subscriber(request): subscriber_ = mommy.make(settings.AUTH_USER_MODEL) def fin(): subscriber_.delete() request.addfinalizer(fin) return subscriber_
def profile_forward(apps, schema_editor): User = apps.get_model(settings.AUTH_USER_MODEL) Profile = apps.get_model("accounts", "Profile") db_alias = schema_editor.connection.alias for user in User.objects.using(db_alias).all(): Profile.objects.using(db_alias).get_or_create(user=user)
def test_custom_user_model(): assert settings.AUTH_USER_MODEL == 'accounts.User'
def skipIfCustomUser(test_func): """ Skip a test if a custom user model is in use. """ return skipIf(settings.AUTH_USER_MODEL != 'auth.User', 'Custom user model in use')(test_func)
def test_check_horizontal_meta_without_horitontal_group(self): class WithoutHorizontalGroupModel(AbstractHorizontalModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, db_constraint=False, ) class Meta(object): horizontal_key = 'user' errors = WithoutHorizontalGroupModel.check() self.assertEqual(1, len(errors)) self.assertEqual('horizon.E001', errors[0].id)
def test_check_horizontal_meta_without_horitontal_key(self): class WithoutHorizontalKeyModel(AbstractHorizontalModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, db_constraint=False, ) class Meta(object): horizontal_group = 'a' errors = WithoutHorizontalKeyModel.check() self.assertEqual(1, len(errors)) self.assertEqual('horizon.E001', errors[0].id)
def test_check_horizontal_meta_wrong_horizontal_group(self): class WrongGroupModel(AbstractHorizontalModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, db_constraint=False, ) class Meta(object): horizontal_group = 'wrong' horizontal_key = 'user' errors = WrongGroupModel.check() self.assertEqual(1, len(errors)) self.assertEqual('horizon.E002', errors[0].id)
def test_check_horizontal_meta_wrong_horizontal_key(self): class WrongKeyModel(AbstractHorizontalModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, db_constraint=False, ) class Meta(object): horizontal_group = 'a' horizontal_key = 'wrong' errors = WrongKeyModel.check() self.assertEqual(1, len(errors)) self.assertEqual('horizon.E003', errors[0].id)
def register_pre_save_on_AUTH_USER_MODER_change(sender, setting, value, enter, **kwargs): if setting == "AUTH_USER_MODEL" and value != USER_MODEL: if enter: pre_save.connect(useraudit.password_expiry.user_pre_save, sender=value) else: pre_save.disconnect(useraudit.password_expiry.user_pre_save, sender=value)
def in_role(self): member_model = apps.get_model(settings.AUTH_USER_MODEL) return member_model.objects.filter( application__position__role=self, application__status='appointed', application__position__term_from__lte=date.today(), application__position__term_to__gte=date.today(), )
def backwards(apps, schema_editor): user_model = apps.get_model(settings.AUTH_USER_MODEL) ph_model = apps.get_model('cms', 'Placeholder') ph_ctype = ContentType.objects.get(app_label=ph_model._meta.app_label, model=ph_model._meta.model_name) try: permission, __ = Permission.objects.get_or_create( codename='use_structure', content_type=ph_ctype, name=u"Can use Structure mode") for user in user_model.objects.filter(is_superuser=False, is_staff=True): user.user_permissions.remove(permission.pk) for group in Group.objects.all(): if permission in group.permissions.all(): group.permissions.remove(permission.pk) except Exception: warnings.warn(u'use_structure not removed from all the users, please check the permission manually')
def UserModelString(): try: return settings.AUTH_USER_MODEL except AttributeError: return 'auth.User'
def setUp(self): self.old_auth_model = getattr(settings, 'AUTH_USER_MODEL', None) settings.AUTH_USER_MODEL = 'test_app.CustomUser' # The form's Meta class is created on import. We have to reload() # to apply the new AUTH_USER_MODEL to the Meta class. reload(forms)
def tearDown(self): settings.AUTH_USER_MODEL = self.old_auth_model
def create_schedule_abc(user_model=None): """Abstract base schedule model factory. :param user_model: User model to use as schedule owners. :type user_model: :class:`~news.models.AbstractModel` implemenatation :returns: A abstract base schedule model. :rtype: Abstract base django model of :class:`~news.models.AbstractSchedule` implementation. """ user_model = user_model or settings.AUTH_USER_MODEL class AbstractBaseSchedule(models.Model, AbstractSchedule): owner = models.ForeignKey( user_model, related_name='schedules', db_index=True, blank=True, null=True, ) url = models.URLField() cycle = models.IntegerField(default=DEFAULT_SCHEDULE_CYCLE) enabled = models.BooleanField(default=False) type = models.CharField(max_length=SCHEDULE_TYPE_MAX_LENGTH, default=DEFAULT_SCHEDULE_TYPE) options = JSONField(default=DEFAULT_OPTIONS) class Meta: abstract = True unique_together = (('owner', 'url'),) return AbstractBaseSchedule