本文整理匯總了Python中django.contrib.auth.get_user_model方法的典型用法代碼示例。如果您正苦於以下問題:Python auth.get_user_model方法的具體用法?Python auth.get_user_model怎麽用?Python auth.get_user_model使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.contrib.auth
的用法示例。
在下文中一共展示了auth.get_user_model方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: notify
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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()
示例2: test_blog_model
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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"
示例3: test_get_authentication_standalone_mode
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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
示例4: test_get_active_user_count_for_date
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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()
示例5: test_is_site_admin_user
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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)
示例6: test_multiple_user_orgs
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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)
示例7: get_user_by_lookup_dict
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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
示例8: create_test_user
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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
示例9: setUp
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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)
示例10: create_consumer
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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)
示例11: get_or_create_user
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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
示例12: clean
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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
示例13: setUp
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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)
示例14: fetch_user
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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]
示例15: setUpTestData
# 需要導入模塊: from django.contrib import auth [as 別名]
# 或者: from django.contrib.auth import get_user_model [as 別名]
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",
)