Python django.contrib.auth.get_user_model() Examples
The following are 30
code examples of django.contrib.auth.get_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.contrib.auth
, or try the search function
.
Example #1
Source File: test_admin.py From django-usersettings2 with BSD 3-Clause "New" or "Revised" License | 8 votes |
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
Source File: base.py From figures with MIT License | 6 votes |
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 #3
Source File: utils.py From resolwe with Apache License 2.0 | 6 votes |
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 #4
Source File: test_blog.py From contributr with MIT License | 6 votes |
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 #5
Source File: channels.py From django-notifs with MIT License | 6 votes |
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 #6
Source File: test_filtering.py From resolwe with Apache License 2.0 | 6 votes |
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 #7
Source File: test_usernotifications.py From django-herald with MIT License | 6 votes |
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 #8
Source File: forms.py From StormOnline with Apache License 2.0 | 6 votes |
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 #9
Source File: test_site_daily_metrics.py From figures with MIT License | 6 votes |
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 #10
Source File: backends.py From django-oidc-rp with MIT License | 6 votes |
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 #11
Source File: test_permissions.py From figures with MIT License | 6 votes |
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 #12
Source File: test_permissions.py From figures with MIT License | 6 votes |
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 #13
Source File: models.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #14
Source File: common.py From django-rest-registration with MIT License | 6 votes |
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 #15
Source File: users.py From django-rest-registration with MIT License | 6 votes |
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 #16
Source File: test_models.py From ideascube with GNU Affero General Public License v3.0 | 5 votes |
def test_create_superuser(): model = get_user_model() user = model.objects.create_superuser('123456', 'passw0rd') assert user.pk is not None assert user.serial == '123456' assert user.is_staff
Example #17
Source File: test_permissions.py From resolwe with Apache License 2.0 | 5 votes |
def setUp(self): self.user1 = get_user_model().objects.create( username="test_user1", email="user1@test.com" ) self.user2 = get_user_model().objects.create( username="test_user2", email="user2@test.com" ) self.user3 = get_user_model().objects.create( username="test_user3", email="user1@test.com" ) self.owner = get_user_model().objects.create(username="owner") # public user is already created bt django-guardian self.public = get_user_model().objects.get(username="public") self.group = Group.objects.create(name="Test group") self.collection = Collection.objects.create( contributor=self.owner, name="Test collection 1" ) assign_perm("owner_collection", self.owner, self.collection) self.process = Process.objects.create( name="Test process", contributor=self.owner, ) self.resource_name = "collection" self.viewset = CollectionViewSet super().setUp()
Example #18
Source File: test_register.py From django-rest-registration with MIT License | 5 votes |
def _get_register_response_user(response): user_id = response.data['id'] user_class = get_user_model() user = user_class.objects.get(id=user_id) return user
Example #19
Source File: 0002_set_process_owners.py From resolwe with Apache License 2.0 | 5 votes |
def set_descriptor_owner(apps, schema_editor): user_model = get_user_model() DescriptorSchema = apps.get_model("flow", "DescriptorSchema") for descriptor in DescriptorSchema.objects.all(): # In migrations contributor is not a real user instance, so we # have to get it. user = user_model.objects.get(pk=descriptor.contributor.pk) assign_contributor_permissions(descriptor, user)
Example #20
Source File: serializers.py From django-rest-registration with MIT License | 5 votes |
def get_authenticated_user(self): data = self.validated_data if data['login'] == 'abra' and data['password'] == 'cadabra': user_model = get_user_model() return user_model.objects.get() return None
Example #21
Source File: checks.py From django-rest-registration with MIT License | 5 votes |
def _are_login_fields_unique() -> bool: user_cls = get_user_model() # type: Type[Model] user_meta = user_cls._meta # pylint: disable=protected-access return all( is_model_field_unique(user_meta.get_field(field_name)) for field_name in get_user_login_field_names())
Example #22
Source File: users.py From django-rest-registration with MIT License | 5 votes |
def get_user_field_names( allow_primary_key: bool = True, non_editable: bool = False): def not_in_seq(names): return lambda name: name not in names user_class = get_user_model() fields = user_class._meta.get_fields() # pylint: disable=protected-access default_field_names = [f.name for f in fields if (getattr(f, 'serialize', False) or getattr(f, 'primary_key', False))] pk_field_names = [f.name for f in fields if getattr(f, 'primary_key', False)] hidden_field_names = set(get_user_setting('HIDDEN_FIELDS')) hidden_field_names = hidden_field_names.union(['last_login', 'password']) public_field_names = get_user_setting('PUBLIC_FIELDS') editable_field_names = get_user_setting('EDITABLE_FIELDS') field_names = (public_field_names if public_field_names is not None else default_field_names) if editable_field_names is None: editable_field_names = field_names editable_field_names = set(filter(not_in_seq(pk_field_names), editable_field_names)) field_names = filter(not_in_seq(hidden_field_names), field_names) if not allow_primary_key: field_names = filter(not_in_seq(pk_field_names), field_names) if non_editable: field_names = filter(not_in_seq(editable_field_names), field_names) field_names = tuple(field_names) return field_names
Example #23
Source File: users.py From django-rest-registration with MIT License | 5 votes |
def build_initial_user(data: Dict[str, Any]) -> 'AbstractBaseUser': user_field_names = get_user_field_names(allow_primary_key=False) user_data = {} for field_name in user_field_names: if field_name in data: user_data[field_name] = data[field_name] user_class = get_user_model() return user_class(**user_data)
Example #24
Source File: users.py From django-rest-registration with MIT License | 5 votes |
def get_user_setting(name): setting_name = 'USER_{name}'.format(name=name) user_class = get_user_model() placeholder = object() value = getattr(user_class, name, placeholder) if value is placeholder: value = getattr(registration_settings, setting_name) return value
Example #25
Source File: test_urls.py From django-classified with MIT License | 5 votes |
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 #26
Source File: users.py From django-rest-registration with MIT License | 5 votes |
def user_with_email_exists(email): user_class = get_user_model() email_field_name = get_user_email_field_name() if not email_field_name: return True queryset = user_class.objects.filter(**{email_field_name: email}) return queryset.exists()
Example #27
Source File: users.py From django-rest-registration with MIT License | 5 votes |
def get_user_login_field_names(): user_class = get_user_model() return get_user_setting('LOGIN_FIELDS') or [user_class.USERNAME_FIELD]
Example #28
Source File: serializers.py From django-rest-registration with MIT License | 5 votes |
def __init__(self, *args, **kwargs): user_class = get_user_model() field_names = get_user_field_names(allow_primary_key=True) field_names = field_names + ('password',) read_only_field_names = get_user_field_names( allow_primary_key=True, non_editable=True) meta_obj = MetaObj() meta_obj.model = user_class meta_obj.fields = field_names meta_obj.read_only_fields = read_only_field_names self.Meta = meta_obj # pylint: disable=invalid-name super().__init__(*args, **kwargs)
Example #29
Source File: serializers.py From django-rest-registration with MIT License | 5 votes |
def __init__(self, *args, **kwargs): user_class = get_user_model() field_names = get_user_field_names(allow_primary_key=True) read_only_field_names = get_user_field_names( allow_primary_key=True, non_editable=True) meta_obj = MetaObj() meta_obj.model = user_class meta_obj.fields = field_names meta_obj.read_only_fields = read_only_field_names self.Meta = meta_obj # pylint: disable=invalid-name super().__init__(*args, **kwargs)
Example #30
Source File: test_middleware.py From django-oidc-rp with MIT License | 5 votes |
def test_can_properly_handle_the_case_where_a_user_was_authenticated_using_the_model_backend( self, rf): request = rf.get('/') SessionMiddleware().process_request(request) request.session.save() user = get_user_model().objects.create_user('test', 'test@example.com', 'insecure') request.user = user auth.authenticate(username='test', password='insecure') auth.login(request, user) middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK') middleware(request) assert request.user == user assert request.user.is_authenticated