Python django.conf.settings.AUTH_USER_MODEL Examples

The following are 30 code examples of django.conf.settings.AUTH_USER_MODEL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: state.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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)) 
Example #2
Source File: models.py    From django-request-profiler with MIT License 6 votes vote down vote up
def match_user(self, user: AUTH_USER_MODEL) -> bool:
        """Return True if the user passes the various user filters."""
        # treat no user (i.e. has not been added) as AnonymousUser()
        user = user or AnonymousUser()

        if self.user_filter_type == RuleSet.USER_FILTER_ALL:
            return True

        if self.user_filter_type == RuleSet.USER_FILTER_AUTH:
            return user.is_authenticated

        if self.user_filter_type == RuleSet.USER_FILTER_GROUP:
            group = self.user_group_filter.strip()
            return user.groups.filter(name__iexact=group).exists()

        # if we're still going, then it's a no. it's also an invalid
        # user_filter_type, so we may want to think about a warning
        return False 
Example #3
Source File: view_tests.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.view = ClaimStatusView()
        self.url = 'http://github.com/codesy/codesy/issues/37'
        self.issue = mommy.make(Issue, url=self.url)
        self.user1 = mommy.make(
            settings.AUTH_USER_MODEL, email='user1@test.com'
        )
        self.bid1 = mommy.make(
            Bid, user=self.user1, url=self.url, issue=self.issue, offer=0
        )
        self.user2 = mommy.make(
            settings.AUTH_USER_MODEL, email='user2@test.com'
        )
        self.bid2 = mommy.make(
            Bid, user=self.user2, url=self.url, issue=self.issue, offer=10
        )
        self.user3 = mommy.make(
            settings.AUTH_USER_MODEL, email='user3@test.com'
        )

        self.claim = mommy.make(Claim, user=self.user1, issue=self.issue) 
Example #4
Source File: model_tests.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def setUp(self):
        """
        Add a final bid and a user2 claim to the MarketWithBidsTestCase,
        so the final market for the bug is now:
            url: http://github.com/codesy/codesy/issues/37
            user1: ask 50,  offer 0  (ask is met)
            user2: ask 100, offer 10
            user3: ask 0,   offer 30
            user4: ask 200, offer 10
        And user1 is making the claim
        """
        super(NotifyMatchingOfferersTest, self).setUp()
        self.user4 = mommy.make(settings.AUTH_USER_MODEL,
                                email='user4@test.com')
        self.bid4 = mommy.make(Bid, user=self.user4,
                               ask=200, offer=10, url=self.url)
        self.evidence = ('https://github.com/codesy/codesy/commit/'
                         '4f1bcd014ec735918bebd1c386e2f99a7f83ff64') 
Example #5
Source File: model_tests.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_only_send_mail_to_unsent_matching_askers(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        self.bid1.ask_match_sent = timezone.now()
        self.bid1.save()
        subject = "[codesy] There's $100 waiting for you!"

        mock_send_mail.expects_call().with_args(
            subject,
            arg.any(),
            arg.any(),
            ['user2@test.com']
        )

        offer_bid = mommy.make(
            Bid, offer=100, user=user, ask=1000, url=self.url
        )
        offer_bid.save() 
Example #6
Source File: model_tests.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_send_mail_to_matching_askers(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        bid1_subject = "[codesy] There's $50 waiting for you!"
        bid2_subject = "[codesy] There's $100 waiting for you!"
        mock_send_mail.expects_call().with_args(
            bid1_subject,
            arg.any(),
            arg.any(),
            ['user1@test.com']
        )
        mock_send_mail.next_call().with_args(
            bid2_subject,
            arg.any(),
            arg.any(),
            ['user2@test.com']
        )

        offer_bid = mommy.make(
            Bid, offer=100, user=user, ask=1000, url=self.url
        )
        offer_bid.save() 
Example #7
Source File: __init__.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def setUp(self):
        """
        Set up the following claim senarios
            user1: asks 50
            user2: offers 25
            user3: offers 25
            user1 claims
        """
        self.url = 'http://github.com/codesy/codesy/issues/37'
        self.issue = mommy.make(Issue, url=self.url)

        self.user1 = mommy.make(settings.AUTH_USER_MODEL,
                                email='user1@test.com')
        self.user2 = mommy.make(settings.AUTH_USER_MODEL,
                                email='user2@test.com')
        self.user3 = mommy.make(settings.AUTH_USER_MODEL,
                                email='user3@test.com')
        self.bid1 = mommy.make(Bid, user=self.user1,
                               ask=50, offer=0, url=self.url, issue=self.issue)
        self.bid2 = mommy.make(Bid, user=self.user2,
                               ask=0, offer=25, url=self.url, issue=self.issue)
        self.bid3 = mommy.make(Bid, user=self.user3,
                               ask=0, offer=25, url=self.url, issue=self.issue)
        self.claim = mommy.make(Claim, user=self.user1, issue=self.issue) 
Example #8
Source File: config.py    From django-river with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def settings(self):
        if self.cached_settings:
            return self.cached_settings
        else:
            from django.conf import settings
            allowed_configurations = {
                'CONTENT_TYPE_CLASS': ContentType,
                'USER_CLASS': settings.AUTH_USER_MODEL,
                'PERMISSION_CLASS': Permission,
                'GROUP_CLASS': Group,
                'INJECT_MODEL_ADMIN': False
            }
            river_settings = {}
            for key, default in allowed_configurations.items():
                river_settings[key] = getattr(settings, self.get_with_prefix(key), default)

            river_settings['IS_MSSQL'] = connection.vendor == 'microsoft'
            self.cached_settings = river_settings

            return self.cached_settings 
Example #9
Source File: test_checks.py    From django-hijack-admin with MIT License 6 votes vote down vote up
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()) 
Example #10
Source File: utils.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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) 
Example #11
Source File: processors.py    From djangosaml2idp with Apache License 2.0 5 votes vote down vote up
def get_nameid_email(cls, user_id: str, user: settings.AUTH_USER_MODEL = None, **kwargs) -> str:
        if '@' not in user_id:
            raise Exception(f"user_id {user_id} does not contain the '@' symbol, so is not a valid NameID Email address format.")
        return user_id 
Example #12
Source File: 0019_auto_20180730_0211.py    From eventoL with GNU General Public License v3.0 5 votes vote down vote up
def set_owner_defaults(apps, schema_editor):
    Activity = apps.get_model('manager', 'Activity')
    EventUser = apps.get_model('manager', 'EventUser')
    User = apps.get_model(settings.AUTH_USER_MODEL)
    qs = Activity.objects.filter(owner=None)

    for activity in qs:
        email = activity.speaker_contact
        username = "{}-{}".format(email.split("@")[0], get_random_string(4))
        password = make_password(None)
        defaults = {'username': username, 'password': password}
        try:
            user, created = User.objects.get_or_create(email=email, defaults=defaults)
            if created:
                print("new user created: {}, (activity: {})".format(user.email, activity.title))
        except MultipleObjectsReturned:
            print("Multiple EventUser returned: {}, (activity: {})".format(user, activity.title))
            user = User.objects.filter(email=email).first()
        # get a EventUser
        try:
            event_user, created = EventUser.objects.get_or_create(
                user=user, defaults={'event': activity.event})
            if created:
                print("new EventUser created: {}, (activity: {})".format(event_user, activity.title))
        except MultipleObjectsReturned:
            print("Multiple EventUser returned: {}, (activity: {})".format(user, activity.title))
            event_user = EventUser.objects.filter(user=user).first()
        activity.owner = event_user
        activity.save() 
Example #13
Source File: conftest.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def user() -> settings.AUTH_USER_MODEL:
    return UserFactory() 
Example #14
Source File: test_views.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_get_success_url(
        self, user: settings.AUTH_USER_MODEL, request_factory: RequestFactory
    ):
        view = UserUpdateView()
        request = request_factory.get("/fake-url/")
        request.user = user

        view.request = request

        assert view.get_success_url() == f"/users/{user.username}/" 
Example #15
Source File: test_views.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_get_object(
        self, user: settings.AUTH_USER_MODEL, request_factory: RequestFactory
    ):
        view = UserUpdateView()
        request = request_factory.get("/fake-url/")
        request.user = user

        view.request = request

        assert view.get_object() == user 
Example #16
Source File: test_views.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_get_redirect_url(
        self, user: settings.AUTH_USER_MODEL, request_factory: RequestFactory
    ):
        view = UserRedirectView()
        request = request_factory.get("/fake-url")
        request.user = user

        view.request = request

        assert view.get_redirect_url() == f"/users/{user.username}/" 
Example #17
Source File: processors.py    From djangosaml2idp with Apache License 2.0 5 votes vote down vote up
def get_nameid_persistent(cls, user_id: str, sp: ServiceProvider, user: settings.AUTH_USER_MODEL, *args, **kwargs) -> str:
        """ Get PersistentID in TransientID format
            see: http://software.internet2.edu/eduperson/internet2-mace-dir-eduperson-201602.html#eduPersonTargetedID
        """
        return str(PersistentId.objects.get_or_create(sp=sp, user=user)[0].persistent_id) 
Example #18
Source File: processors.py    From djangosaml2idp with Apache License 2.0 5 votes vote down vote up
def get_nameid_persistent(cls, user_id: str, sp: ServiceProvider, user: settings.AUTH_USER_MODEL, *args, **kwargs) -> str:
        """ Get PersistentID in TransientID format
            see: http://software.internet2.edu/eduperson/internet2-mace-dir-eduperson-201602.html#eduPersonTargetedID
        """
        return str(PersistentId.objects.get_or_create(sp=sp, user=user)[0].persistent_id) 
Example #19
Source File: processors.py    From djangosaml2idp with Apache License 2.0 5 votes vote down vote up
def get_nameid_email(cls, user_id: str, user: settings.AUTH_USER_MODEL = None, **kwargs) -> str:
        if '@' not in user_id:
            raise Exception(f"user_id {user_id} does not contain the '@' symbol, so is not a valid NameID Email address format.")
        return user_id 
Example #20
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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
        ) 
Example #21
Source File: apps.py    From openwisp-users with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_default_menu_items(self):
        menu_setting = 'OPENWISP_DEFAULT_ADMIN_MENU_ITEMS'
        items = [
            {'model': settings.AUTH_USER_MODEL},
            {'model': get_model_name('openwisp_users', 'Organization')},
        ]
        if not hasattr(settings, menu_setting):
            setattr(settings, menu_setting, items)
        else:
            current_menu = getattr(settings, menu_setting)
            current_menu += items 
Example #22
Source File: state.py    From python with Apache License 2.0 5 votes vote down vote up
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)

        # The lock gets in the way of copying as implemented in clone(), which
        # is called whenever Django duplicates a StateApps before updating it.
        self._lock = None

        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)) 
Example #23
Source File: tests.py    From django-currentuser with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_is_a_nullable_fk_to_the_user_model(self):
        field = self.field_cls()
        foreignkey_model = self.get_related_model(field)
        assert_that(foreignkey_model, is_(equal_to(settings.AUTH_USER_MODEL)))
        assert_that(field.null, is_(True)) 
Example #24
Source File: tests.py    From django-currentuser with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_no_warning_raised_if_passed_argument_values_match_defaults(self):
        with warnings.catch_warnings(record=True) as my_warnings:
            self.field_cls(default=get_current_authenticated_user)
            self.field_cls(null=True)
            self.field_cls(to=settings.AUTH_USER_MODEL)
            assert_that(my_warnings, has_length(0)) 
Example #25
Source File: checks.py    From django-hijack-admin with MIT License 5 votes vote down vote up
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 
Example #26
Source File: utils.py    From django-request-profiler with MIT License 5 votes vote down vote up
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
    ) 
Example #27
Source File: utils.py    From django-request-profiler with MIT License 5 votes vote down vote up
def skipIfDefaultUser(test_func):
    """
    Skip a test if a default user model is in use.
    """
    return skipIf(settings.AUTH_USER_MODEL == "auth.User", "Default user model in use")(
        test_func
    ) 
Example #28
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def get_user_model():
    """
    Return 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
        ) 
Example #29
Source File: state.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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().__init__(app_configs)

        # The lock gets in the way of copying as implemented in clone(), which
        # is called whenever Django duplicates a StateApps before updating it.
        self._lock = None

        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)) 
Example #30
Source File: test_urls.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_detail(user: settings.AUTH_USER_MODEL):
    assert (
        reverse("users:detail", kwargs={"username": user.username})
        == f"/users/{user.username}/"
    )
    assert resolve(f"/users/{user.username}/").view_name == "users:detail"