Python django.contrib.auth.get_user_model() Examples

The following are 30 code examples for showing how to use django.contrib.auth.get_user_model(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.contrib.auth , or try the search function .

Example 1
Project: django-usersettings2   Author: mishbahr   File: test_admin.py    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def setUp(self):
        Site.objects.get_or_create(id=settings.SITE_ID, domain='example.com', name='example.com')
        self.obj = get_usersettings_model().objects.create(**self.usersettings_data)
        self.user = get_user_model().objects.create_superuser(
            self.username, self.email, self.password)

        self.assertTrue(self.client.login(
            username=self.username, password=self.password),
            'Failed to login user %s' % self.email)

        factory = RequestFactory()
        request = factory.get('/admin')
        request.user = self.user
        request.session = {}

        self.request = request
        self.settings_admin = SettingsAdmin(get_usersettings_model(), AdminSite())

        # Hack to test this function as it calls 'messages.add'
        # See https://code.djangoproject.com/ticket/17971
        setattr(self.request, 'session', 'session')
        messages = FallbackStorage(self.request)
        setattr(self.request, '_messages', messages) 
Example 2
Project: django-notifs   Author: danidee10   File: channels.py    License: MIT License 6 votes vote down vote up
def notify(self, message):
        """
        Puts a new message on the queue.
        
        The queue is named based on the username (for Uniqueness)
        """
        connection = self._connect()
        channel = connection.channel()

        # Get user instance
        User = get_user_model()
        source = User.objects.get(id=message['source'])
        recipient = User.objects.get(id=message['recipient'])

        channel.queue_declare(queue=source.username)

        jsonified_messasge = dumps(message)
        channel.basic_publish(
            exchange='', routing_key=recipient.username,
            body=jsonified_messasge
        )

        connection.close() 
Example 3
Project: contributr   Author: Djenesis   File: test_blog.py    License: MIT License 6 votes vote down vote up
def test_blog_model():
    """
    Create a user and a blog post with publish set to false.
    Then assert that number of blog posts equals 1.
    """
    user = get_user_model().objects.create(username="bloghero")
    post = Post(title="Test title blog", author=user,
                body="Blogging here!", publish=False)
    post.save()
    assert Post.objects.all().count() == 1

    """
    Assert that the custom queryset displays posts that has publish
    set to true.
    """
    assert Post.objects.published().count() == 0
    post.publish = True
    post.save()
    assert Post.objects.published().count() == 1

    """
    Asserts wether the post string representation (__str__) is equal
    to the blog title.
    """
    assert str(post) == "Test title blog" 
Example 4
Project: figures   Author: appsembler   File: base.py    License: MIT License 6 votes vote down vote up
def test_get_authentication_standalone_mode(self, username, status_code):
        '''
        Provides authentication testing
        Tests in the inherited classes provide for testing results

        Currently expect the view_class to be derived from the
        Django Rest Framework ViewSetMixin class. This requires
        the action in the 'as_view' call
        '''
        with mock.patch.dict('figures.helpers.settings.FEATURES', {'FIGURES_IS_MULTISITE': False}):
            request = APIRequestFactory().get(self.request_path)
            user = get_user_model().objects.get(username=username)
            force_authenticate(request, user=user)

            # This is a (temporary we hope) hack to support views
            # that can be derived from either APIView or ViewSetMixin
            if self.get_action:
                view = self.view_class.as_view(self.get_action)
            else:
                view = self.view_class.as_view()
            response = view(request)
            assert response.status_code == status_code 
Example 5
Project: figures   Author: appsembler   File: test_site_daily_metrics.py    License: MIT License 6 votes vote down vote up
def test_get_active_user_count_for_date(self, monkeypatch):
        assert not get_user_model().objects.count()
        assert not StudentModule.objects.count()
        modified = as_datetime(self.date_for)

        def mock_student_modules_for_site(site):
            for user in [UserFactory() for i in range(2)]:
                StudentModuleFactory(student=user, modified=modified)
                StudentModuleFactory(student=user, modified=modified)
            return StudentModule.objects.all()

        monkeypatch.setattr(pipeline_sdm, 'get_student_modules_for_site',
                            mock_student_modules_for_site)
        users = pipeline_sdm.get_site_active_users_for_date(site=self.site,
                                                            date_for=self.date_for)
        assert users.count() == get_user_model().objects.count() 
Example 6
Project: figures   Author: appsembler   File: test_permissions.py    License: MIT License 6 votes vote down vote up
def test_is_site_admin_user(self, monkeypatch, settings, username, allow):
        def test_site(request):
            return self.site
        request = APIRequestFactory().get('/')
        request.META['HTTP_HOST'] = self.site.domain
        request.user = get_user_model().objects.get(username=username)
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', test_site)
        settings.FEATURES['FIGURES_IS_MULTISITE'] = True
        assert figures.helpers.is_multisite()
        permission = figures.permissions.IsSiteAdminUser().has_permission(
            request, None)
        assert permission == allow, 'User "{username}" should have access'.format(
            username=username)

        # verify that inactive users are denied permission
        request.user.is_active = False
        permission = figures.permissions.IsSiteAdminUser().has_permission(
            request, None)
        assert permission == False, 'username: "{username}"'.format(
            username=username) 
Example 7
Project: figures   Author: appsembler   File: test_permissions.py    License: MIT License 6 votes vote down vote up
def test_multiple_user_orgs(self, monkeypatch, settings, username, allow):
        """
        We updated `figures.permissions` so that a user can belong to multiple
        organizations
        """
        def test_site(request):
            return self.site
        request = APIRequestFactory().get('/')
        request.META['HTTP_HOST'] = self.site.domain
        request.user = get_user_model().objects.get(username=username)
        monkeypatch.setattr(django.contrib.sites.shortcuts, 'get_current_site', test_site)
        settings.FEATURES['FIGURES_IS_MULTISITE'] = True
        assert figures.helpers.is_multisite()
        org2 = OrganizationFactory(sites=[self.site])
        UserOrganizationMappingFactory(user=request.user, organization=org2)
        permission = figures.permissions.IsSiteAdminUser().has_permission(request, None)
        assert permission == allow, 'User "{username}" should have access'.format(
            username=username) 
Example 8
Project: django-rest-registration   Author: apragacz   File: users.py    License: MIT License 6 votes vote down vote up
def get_user_by_lookup_dict(
        lookup_dict, default=_RAISE_EXCEPTION, require_verified=True):
    verification_enabled = registration_settings.REGISTER_VERIFICATION_ENABLED
    verification_flag_field = get_user_setting('VERIFICATION_FLAG_FIELD')
    user_class = get_user_model()
    kwargs = {}
    kwargs.update(lookup_dict)
    if require_verified and verification_enabled and verification_flag_field:
        kwargs[verification_flag_field] = True
    try:
        user = get_object_or_404(user_class.objects.all(), **kwargs)
    except Http404:
        if default is _RAISE_EXCEPTION:
            raise UserNotFound()
        return default
    else:
        return user 
Example 9
Project: django-rest-registration   Author: apragacz   File: common.py    License: MIT License 6 votes vote down vote up
def create_test_user(**kwargs):
    password = kwargs.pop('password', None)

    user_model = get_user_model()
    fields = user_model._meta.get_fields()  # pylint: disable=protected-access
    user_kwargs = {}

    for field in fields:
        name = field.name
        if name in USER_DEFAULT_FIELD_VALUES:
            user_kwargs[name] = USER_DEFAULT_FIELD_VALUES[name]
        else:
            assert field.null or field.default is not None

    user_kwargs.update(**kwargs)

    user = user_model.objects.create(**user_kwargs)
    if password is not None:
        user.set_password(password)
        user.save()
        user.password_in_plaintext = password
    return user 
Example 10
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_consumer(name, description, owner_userid, admin_contact, permissions):
    """
    Create a new Consumer with all of the info we need recorded. Arguments: (name, description, owner_userid, admin_contact, permissions)

    Could be rolled into a form+view in /sysadmin/, but how many could there possibly be?
    """
    assert set(permissions) <= set(PERMISSION_OPTIONS.keys()), 'Permissions must be chosen from PERMISSION_CHOICES.'

    User = get_user_model()
    c = Consumer(name=name, description=description, status=ACCEPTED,
            user=User.objects.get(username=owner_userid), xauth_allowed=False)
    c.generate_random_codes()
    c.save()

    i = ConsumerInfo(consumer=c)
    i.admin_contact = admin_contact
    i.permissions = list(permissions)
    i.save()

    print("Consumer key:", c.key)
    print("Consumer secret:", c.secret) 
Example 11
Project: django-oidc-rp   Author: impak-finance   File: backends.py    License: MIT License 6 votes vote down vote up
def get_or_create_user(username, email):
    username = smart_text(username)

    users = get_user_model().objects.filter(email=email)

    if len(users) == 0:
        user = get_user_model().objects.create_user(username, email=email)
    elif len(users) == 1:
        return users[0]
    else:  # duplicate handling
        current_user = None
        for u in users:
            current_user = u
            if hasattr(u, 'oidc_user'):
                return u

        return current_user

    return user 
Example 12
Project: StormOnline   Author: stormsha   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data 
Example 13
Project: django-herald   Author: worthwhile   File: test_usernotifications.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        User = get_user_model()

        # create a user who does not want to get MyOtherNotification
        user = User(username='test', password='Safepass1.')
        user.save()
        usernotification = UserNotification(user=user)
        usernotification.save()

        # refresh the user
        self.user = User.objects.get(id=user.id)
        # add a notification
        notification = Notification(notification_class=MyOtherNotification.get_class_path())
        notification.save()

        # disable the notification
        self.user.usernotification.disabled_notifications.add(notification)
        self.user = User.objects.get(id=user.id) 
Example 14
Project: resolwe   Author: genialis   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def fetch_user(query):
    """Get user by ``pk``, ``username`` or ``email``.

    Raise error if user can not be determined.
    """
    lookup = Q(username=query) | Q(email=query)
    if query.isdigit():
        lookup = lookup | Q(pk=query)

    user_model = get_user_model()
    users = user_model.objects.filter(lookup)

    if not users:
        raise exceptions.ParseError("Unknown user: {}".format(query))
    elif len(users) >= 2:
        raise exceptions.ParseError("Cannot uniquely determine user: {}".format(query))
    return users[0] 
Example 15
Project: resolwe   Author: genialis   File: test_filtering.py    License: Apache License 2.0 6 votes vote down vote up
def setUpTestData(cls):
        user_model = get_user_model()
        cls.admin = user_model.objects.create_superuser(
            username="admin",
            email="admin@test.com",
            password="admin",
            first_name="James",
            last_name="Smith",
        )
        cls.contributor = user_model.objects.create_user(
            username="contributor",
            email="contributor@test.com",
            first_name="Joe",
            last_name="Miller",
        )
        cls.user = user_model.objects.create_user(
            username="normal_user",
            email="user@test.com",
            first_name="John",
            last_name="Williams",
        ) 
Example 16
Project: django-classified   Author: slyapustin   File: test_urls.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.username = 'John'
        self.password = 'summer'
        self.email = 'john@example.com'
        self.user = get_user_model().objects.create_user(
            self.username,
            self.email,
            self.password
        )
        self.profile = Profile.get_or_create_for_user(self.user)
        self.profile.phone = '0123456789'
        self.profile.save()

        self.section = Section.objects.create(
            title='Cars'
        )

        self.group = Group.objects.create(
            slug='new-cars',
            title='New cars',
            section=self.section
        )
        self.item = Item.objects.create(
            user=self.user,
            group=self.group,
            title='Tesla Model 3',
            description='Super new 2017 Tesla Model 3 electric Car',
            price=35000.00,
        ) 
Example 17
Project: django-classified   Author: slyapustin   File: test_urls.py    License: MIT License 5 votes vote down vote up
def test_another_user_cannot_update_other_user_item(self):
        another_user = get_user_model().objects.create_user(
            'Andy',
            'andy@hotmail.com',
            'pass'
        )

        self.client.login(
            username=another_user.username,
            password='pass'
        )

        self.assertEqual(another_user.item_set.count(), 0)

        response = self.client.get(reverse('django_classified:item-edit', kwargs={'pk': self.item.pk}))
        self.assertEqual(response.status_code, 403)

        item_data = {
            'image_set-TOTAL_FORMS': 0,
            'image_set-INITIAL_FORMS': 0,
            'group': self.group.pk,
            'title': 'iPhone X',
            'description': 'New, Unlocked. Face ID',
            'price': 999,
            'is_active': True
        }
        response = self.client.post(reverse('django_classified:item-edit', kwargs={'pk': self.item.pk}), item_data,
                                    follow=True)
        self.assertEqual(response.status_code, 403) 
Example 18
Project: pinax-documents   Author: pinax   File: models.py    License: MIT License 5 votes vote down vote up
def shared_with(self, user=None):
        """
        Returns a User queryset of users shared on this folder, or, if user
        is given optimizes the check and returns boolean.
        """
        User = get_user_model()
        qs = self.shared_queryset()
        if user is not None:
            return qs.filter(user=user).exists()
        if not qs.exists():
            return User.objects.none()
        return User.objects.filter(pk__in=qs.values("user")) 
Example 19
Project: pinax-documents   Author: pinax   File: models.py    License: MIT License 5 votes vote down vote up
def shared_with(self, user=None):
        """
        Returns a User queryset of users shared on this folder, or, if user
        is given optimizes the check and returns boolean.
        """
        User = get_user_model()
        qs = self.shared_queryset()
        if user is not None:
            return qs.filter(user=user).exists()
        if not qs.exists():
            return User.objects.none()
        return User.objects.filter(pk__in=qs.values("user")) 
Example 20
Project: pinax-documents   Author: pinax   File: hooks.py    License: MIT License 5 votes vote down vote up
def share_with_options(self, user, folder):
        """
        Return a list of users with whom `user` can share `folder`.
        """
        user_class = get_user_model()
        return user_class.objects.all() 
Example 21
Project: django-notifs   Author: danidee10   File: views.py    License: MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Generate the notification."""
        data = loads(request.body)
        message = data['message']

        # Create/retrieve the user
        User = get_user_model()

        try:
            user = User.objects.get(username='demouser')
        except ObjectDoesNotExist:
            user = User.objects.create_user(
                username='demouser', email='example@gmail.com',
                password='mypassword'
            )

        # notification
        args = {
            'source': user, 'source_display_name': user.get_full_name(),
            'recipient': user, 'category': 'Quote', 'action': 'Sent',
            'obj': user.id,
            'short_description': 'You a message: {}'.format(message),
            'url': 'http://example.com', 'channels': ('websocket',)
        }
        notify.send(sender=self.__class__, **args)

        response = JsonResponse({'message': 'Notification generated'})

        self.add_access_control_headers(response)

        return response 
Example 22
Project: figures   Author: appsembler   File: student_modules.py    License: MIT License 5 votes vote down vote up
def seed_student_modules_fixed(data=None):
    '''
    '''
    if not data:
        data = STUDENT_MODULE_DATA
    for rec in data:
        StudentModule.objects.update_or_create(
            student=get_user_model().objects.get(username=rec['username']),
            course_id=as_course_key(rec['course_id']),
            create=as_datetime(rec['created']),
            modified=as_datetime(rec['modified']),
        ) 
Example 23
Project: figures   Author: appsembler   File: seed.py    License: MIT License 5 votes vote down vote up
def clear_non_admin_users():
    users = get_user_model().objects.exclude(
        is_superuser=True).exclude(is_staff=True)
    users.delete() 
Example 24
Project: figures   Author: appsembler   File: seed.py    License: MIT License 5 votes vote down vote up
def seed_users(data=None):
    if not data:
        data = cans.USER_DATA

    first_date = days_from(LAST_DAY, DAYS_BACK * -1)
    created_users = []
    for rec in data:
        try:
            profile_rec = rec.get('profile', None)
            user = get_user_model().objects.create_user(
                username=rec['username'],
                password=rec['password'],
                email=rec['email'],
                )
            user.is_staff = rec.get('is_staff', False)
            user.is_superuser = rec.get('is_superuser', False)
            user.date_joined = as_datetime(
                FAKE.date_between(first_date, LAST_DAY)).replace(tzinfo=utc)
            user.save()
            created_users.append(user)
            if profile_rec:
                UserProfile.objects.create(
                    user=user,
                    name=profile_rec['fullname'],
                    gender=profile_rec.get('gender', None),
                    country=profile_rec.get('country', None),
                )
        except IntegrityError as e:
            print('skipping duplicate user email {}'.format(e))
    return created_users 
Example 25
Project: figures   Author: appsembler   File: seed.py    License: MIT License 5 votes vote down vote up
def seed_course_access_roles(data=None):
    if not data:
        data = cans.COURSE_ACCESS_ROLE_DATA

    for rec in data:
        print('creating course access role')
        CourseAccessRole.objects.update_or_create(
            user=get_user_model().objects.get(username=rec['username']),
            org=rec['org'],
            course_id=as_course_key(rec['course_id']),
            role=rec['role'],
        ) 
Example 26
Project: figures   Author: appsembler   File: test_general_user_data_view.py    License: MIT License 5 votes vote down vote up
def get_expected_results(self, **filter):
        """returns a list of dicts of the filtered user data
        """
        return list(
            get_user_model().objects.filter(**filter).annotate(
                fullname=F('profile__name'), country=F('profile__country')
                ).values(*self.expected_result_keys)) 
Example 27
Project: figures   Author: appsembler   File: test_learner_details_view.py    License: MIT License 5 votes vote down vote up
def test_get_learner_details_list(self):
        """Tests retrieving a list of users with abbreviated details

        The fields in each returned record are identified by
            `figures.serializers.UserIndexSerializer`

        """
        request = APIRequestFactory().get(self.request_path)
        force_authenticate(request, user=self.staff_user)
        view = self.view_class.as_view({'get': 'list'})
        response = view(request)

        # Later, we'll elaborate on the tests. For now, some basic checks
        assert response.status_code == 200
        assert set(response.data.keys()) == set(
            ['count', 'next', 'previous', 'results'])

        results = response.data['results']
        assert len(results) == len(self.users) + len(self.callers)
        enrollments = get_course_enrollments_for_site(self.site)
        assert enrollments.count() == len(self.enrollments)

        for rec in results:
            assert set(rec.keys()) == set(self.expected_result_keys)
            # fail if we cannot find the user in the models
            user = get_user_model().objects.get(username=rec['username'])
            user_course_enrollments = enrollments.filter(user=user)
            # Check that each course enrollment is represented
            assert len(rec['courses']) == user_course_enrollments.count()
            for ce in user_course_enrollments:
                assert get_course_rec(ce.course_id, rec['courses']) 
Example 28
Project: figures   Author: appsembler   File: test_learner_details_view.py    License: MIT License 5 votes vote down vote up
def test_get_learner_details_list(self):
        """Tests retrieving a list of users with abbreviated details

        The fields in each returned record are identified by
            `figures.serializers.UserIndexSerializer`

        """

        request = APIRequestFactory().get(self.request_path)
        force_authenticate(request, user=self.caller)
        view = self.view_class.as_view({'get': 'list'})
        response = view(request)

        # Later, we'll elaborate on the tests. For now, some basic checks
        assert response.status_code == 200
        assert set(response.data.keys()) == set(
            ['count', 'next', 'previous', 'results'])

        results = response.data['results']
        assert len(results) == len(self.my_site_users)
        enrollments = get_course_enrollments_for_site(self.site)
        assert enrollments.count() == len(self.my_enrollments)

        for rec in results:
            assert set(rec.keys()) == set(self.expected_result_keys)
            # fail if we cannot find the user in the models
            user = get_user_model().objects.get(username=rec['username'])
            user_course_enrollments = enrollments.filter(user=user)
            # Check that each course enrollment is represented
            assert len(rec['courses']) == user_course_enrollments.count()
            for ce in user_course_enrollments:
                assert get_course_rec(ce.course_id, rec['courses']) 
Example 29
Project: figures   Author: appsembler   File: base.py    License: MIT License 5 votes vote down vote up
def staff_user(self):
        return get_user_model().objects.get(username='staff_user') 
Example 30
Project: figures   Author: appsembler   File: test_user_index_view.py    License: MIT License 5 votes vote down vote up
def get_expected_results(self, **filter):
        '''returns a list of dicts of the filtered user data
        
        '''
        return list(
            get_user_model().objects.filter(**filter).annotate(
                fullname=F('profile__name')).values(*self.expected_result_keys))

    # This test fails on 'assert 1'. More users are added after setup called