Here are the examples of the python api django.contrib.auth.get_user_model.objects.get taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
120 Examples
3
Source : models.py
with MIT License
from agamgn
with MIT License
from agamgn
def get_most_recent_conversation(self, recipient):
"""获取最近一次私信互动的用户"""
try:
qs_sent = self.filter(sender=recipient).select_related('sender', 'recipient') # 当前登录用户发送的消息
qs_received = self.filter(recipient=recipient).select_related('sender', 'recipient') # 当前登录用户接收的消息
qs = qs_sent.union(qs_received).latest("created_at") # 最后一条消息
if qs.sender == recipient:
# 如果登录用户有发送消息,返回消息的接收者
return qs.recipient
# 否则返回消息的发送者
return qs.sender
except self.model.DoesNotExist:
# 如果模型实例不存在,则返回当前用户
return get_user_model().objects.get(username=recipient.username)
@python_2_unicode_compatible
3
Source : views.py
with GNU General Public License v3.0
from Archmonger
with GNU General Public License v3.0
from Archmonger
def delete_user(request):
if request.method == "POST":
try:
username = request.GET.get("username", None)
user = get_user_model().objects.get(username=username)
user.delete()
except Exception:
return JsonResponse({"success": False})
return JsonResponse({"success": True})
return HttpResponseForbidden()
@login_required
3
Source : views.py
with GNU General Public License v3.0
from Archmonger
with GNU General Public License v3.0
from Archmonger
def manage_modal(request):
template = loader.get_template("modal/manage_user.html")
username = request.GET.get("username", None)
user = None
try:
user = get_user_model().objects.get(username=username)
except Exception:
pass
context = {"account": user}
return HttpResponse(template.render(context, request))
3
Source : permissions.py
with GNU General Public License v3.0
from artoonie
with GNU General Public License v3.0
from artoonie
def has_permission(self, request, view):
username = request.data.get('username')
if not username:
return False
user = get_user_model().objects.get(username=username)
if user and user.userprofile:
return user.userprofile.canUseApi
return False
class HasAPIAccess(permissions.BasePermission):
3
Source : testRestApi.py
with GNU General Public License v3.0
from artoonie
with GNU General Public License v3.0
from artoonie
def _authenticate_as(self, username):
cache.clear()
if not username:
self.client.force_authenticate() # pylint: disable=no-member
else:
user = get_user_model().objects.get(username=username)
self.client.force_authenticate(user=user) # pylint: disable=no-member
def _upload_file_for_api(self, filename):
3
Source : test_views.py
with Apache License 2.0
from bcgov
with Apache License 2.0
from bcgov
def test_delete(self):
client = APIClient()
client.force_authenticate(
get_user_model().objects.get(
username=self.registered_user_2["credentials"]["username"]
)
)
response = client.delete(
"/hooks/registration/{}".format(
self.registered_user_2["credentials"]["username"]
)
)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
client.logout()
class Subscriptions_Hooks_Views_SubscriptionViewSet_TestCase(APITestCase):
3
Source : test_views.py
with Apache License 2.0
from bcgov
with Apache License 2.0
from bcgov
def test_delete(self, mock_url_check):
mock_url_check.return_value = "SUCCESS"
# delete subscription
client = APIClient()
client.force_authenticate(
get_user_model().objects.get(
username=self.registered_user_2["credentials"]["username"]
)
)
response = client.delete(
"/hooks/registration/{}/subscriptions/{}".format(
self.registered_user_2["credentials"]["username"], 1
)
)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
client.logout()
3
Source : test_s_account_accepted_document.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account accepted_documents - check permission denied """
query = self.accepted_documents
accepted_document = f.AccountAcceptedDocumentFactory.create()
variables = {
"account": to_global_id("AccountNode", accepted_document.account.id)
}
# Create regular user
user = get_user_model().objects.get(pk=accepted_document.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_account_note.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account account_notes - check permission denied """
query = self.account_notes_query
account_note = f.AccountNoteBackofficeFactory.create()
variables = {
'account': to_global_id('AccountNoteNode', account_note.account.id),
'noteType': "BACKOFFICE"
}
# Create regular user
user = get_user_model().objects.get(pk=account_note.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_account_subscription.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account subscriptions - check permission denied """
query = self.subscriptions_query
subscription = f.AccountSubscriptionFactory.create()
variables = {
'accountId': to_global_id('AccountNode', subscription.account.id)
}
# Create regular user
user = get_user_model().objects.get(pk=subscription.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_account_subscription_alt_price.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account subscriptions - check permission denied """
query = self.subscription_alt_prices_query
subscription_alt_price = f.AccountSubscriptionAltPriceFactory.create()
variables = {
'accountSubscription': to_global_id('AccountSubscriptionNode',
subscription_alt_price.account_subscription.id)
}
# Create regular user
user_id = subscription_alt_price.account_subscription.account.id
user = get_user_model().objects.get(pk=user_id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_account_subscription_block.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account subscriptions - check permission denied """
query = self.subscription_blocks_query
subscription_block = f.AccountSubscriptionBlockFactory.create()
variables = {
'accountSubscription': to_global_id('AccountSubscriptionNode', subscription_block.account_subscription.id)
}
# Create regular user
user_id = subscription_block.account_subscription.account.id
user = get_user_model().objects.get(pk=user_id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_account_subscription_credit.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account subscriptions - check permission denied """
query = self.subscription_credits_query
subscription_credit = f.AccountSubscriptionCreditAddFactory.create()
variables = {
'accountSubscription': to_global_id('AccountSubscriptionNode', subscription_credit.account_subscription.id)
}
# Create regular user
user_id = subscription_credit.account_subscription.account.id
user = get_user_model().objects.get(pk=user_id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_account_subscription_pause.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account subscriptions - check permission denied """
query = self.subscription_pauses_query
subscription_pause = f.AccountSubscriptionPauseFactory.create()
variables = {
'accountSubscription': to_global_id('AccountSubscriptionNode', subscription_pause.account_subscription.id)
}
# Create regular user
user_id = subscription_pause.account_subscription.account.id
user = get_user_model().objects.get(pk=user_id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_account_teacher_profile.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account instructor_profiles - check permission denied """
query = self.instructor_profiles_query
instructor_profile = f.InstructorProfileFactory.create()
variables = {
'id': to_global_id('AccountNode', instructor_profile.account.id)
}
# Create regular user
user = get_user_model().objects.get(pk=instructor_profile.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_finance_invoice.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account invoices - check permission denied
A user can query the invoices linked to their account, so an error will never be thrown
But a user shouldn't be able to view orders from other accounts without additional permission
"""
query = self.invoices_query
invoice = f.FinanceInvoiceFactory.create()
other_user = f.InstructorFactory.create()
# Create regular user
user = get_user_model().objects.get(pk=invoice.account.id)
executed = execute_test_client_api_query(query, other_user)
data = executed.get('data')
for item in data['financeInvoices']['edges']:
node = item['node']
self.assertNotEqual(node['account']['id'], to_global_id("AccountNode", user.id))
def test_query_permission_granted(self):
3
Source : test_s_finance_invoice_item.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account invoice items - check permission denied """
query = self.invoice_items_query
invoice_item = f.FinanceInvoiceItemFactory.create()
variables = {
"financeInvoice": to_global_id('FinanceInvoiceItemNode', invoice_item.finance_invoice.pk)
}
# Create regular user
user = get_user_model().objects.get(pk=invoice_item.finance_invoice.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_finance_invoice_payment.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account invoice payments - check permission denied """
query = self.invoice_payments_query
invoice_payment = f.FinanceInvoicePaymentFactory.create()
variables = {
"financeInvoice": to_global_id('FinanceInvoicePaymentNode', invoice_payment.finance_invoice.pk)
}
# Create regular user
user = get_user_model().objects.get(pk=invoice_payment.finance_invoice.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : test_s_finance_order.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of finance orders - check permission denied
A user can query the orders linked to their account, so an error will never be thrown
But a user shouldn't be able to view orders from other accounts without additional permission
"""
query = self.orders_query
order = f.FinanceOrderFactory.create()
other_user = f.InstructorFactory.create()
# Query as another use and verify oder is not visible
user = get_user_model().objects.get(pk=order.account.id)
executed = execute_test_client_api_query(query, other_user)
data = executed.get('data')
for item in data['financeOrders']['edges']:
node = item['node']
self.assertNotEqual(node['account']['id'], to_global_id("AccountNode", user.id))
def test_query_permission_granted(self):
3
Source : test_s_finance_order_item.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account order items - check permission denied """
query = self.order_items_query
order_item = f.FinanceOrderItemClasspassFactory.create()
variables = {
"financeOrder": to_global_id('FinanceOrderItemNode', order_item.finance_order.pk)
}
# Create regular user
user = get_user_model().objects.get(pk=order_item.finance_order.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : _test_s_account_membership.py
with GNU General Public License v2.0
from costasiella
with GNU General Public License v2.0
from costasiella
def test_query_permission_denied(self):
""" Query list of account memberships - check permission denied """
query = self.memberships_query
membership = f.AccountMembershipFactory.create()
variables = {
'accountId': to_global_id('AccountMembershipNode', membership.account.id)
}
# Create regular user
user = get_user_model().objects.get(pk=membership.account.id)
executed = execute_test_client_api_query(query, user, variables=variables)
errors = executed.get('errors')
self.assertEqual(errors[0]['message'], 'Permission denied!')
def test_query_permission_granted(self):
3
Source : backends.py
with GNU General Public License v3.0
from CZ-NIC
with GNU General Public License v3.0
from CZ-NIC
def get_user(self, user_id):
"""Return user based on its ID."""
try:
return get_user_model().objects.get(pk=user_id)
except get_user_model().DoesNotExist:
return None
class Fido2AuthenticationBackend(BaseFido2AuthenticationBackend):
3
Source : views.py
with GNU General Public License v3.0
from CZ-NIC
with GNU General Public License v3.0
from CZ-NIC
def get_user(self: View) -> Optional[AbstractBaseUser]:
"""
Return user which is to be authenticated.
Return None, if no user could be found.
"""
user_pk = self.request.session.get(AUTHENTICATION_USER_SESSION_KEY)
username = self.request.GET.get('username')
if SETTINGS.passwordless_auth:
return None
if SETTINGS.two_step_auth and user_pk is not None:
return get_user_model().objects.get(pk=user_pk)
if not SETTINGS.two_step_auth and username is not None:
return get_user_model().objects.get_by_natural_key(username)
return None
def dispatch(self, request, *args, **kwargs):
3
Source : test_consumers.py
with MIT License
from dibs-devs
with MIT License
from dibs-devs
def prepare_room_and_user():
set_up_data()
room = Room.objects.create()
user = get_user_model().objects.get(username="user0")
room.members.add(user)
room.save()
client = Client()
client.force_login(user=user)
return client, room, user
@pytest.mark.asyncio
3
Source : test_utils.py
with MIT License
from dibs-devs
with MIT License
from dibs-devs
async def test_no_session_id_in_headers():
settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS
set_up_data()
room = Room.objects.create()
user = get_user_model().objects.get(username="user0")
room.members.add(user)
room.save()
client = Client()
client.force_login(user=user)
communicator = WebsocketCommunicator(
multitenant_application, f"/ws/django_chatter/chatrooms/{room.id}/",
headers = [(b'host', b'localhost:8000')]
)
with pytest.raises(KeyError):
connected, subprotocol = await communicator.connect()
3
Source : views.py
with MIT License
from dibs-devs
with MIT License
from dibs-devs
def get(self, request, *args, **kwargs):
rooms_list = Room.objects.filter(members=request.user).order_by('-date_modified')
if rooms_list.exists():
latest_room_uuid = rooms_list[0].id
return HttpResponseRedirect(
reverse('django_chatter:chatroom', args=[latest_room_uuid])
)
else:
# create room with the user themselves
user = get_user_model().objects.get(username=request.user)
room_id = create_room([user])
return HttpResponseRedirect(
reverse('django_chatter:chatroom', args=[room_id])
)
# This fetches a chatroom given the room ID if a user diretly wants to access the chat.
class ChatRoomView(LoginRequiredMixin, TemplateView):
3
Source : utils.py
with MIT License
from emre
with MIT License
from emre
def get_top_voters():
with connection.cursor() as cursor:
cursor.execute("select count(1), user_id from polls_choice_voted_users "
"group by user_id order by count(1) desc limit 5;")
row = cursor.fetchall()
voter_list = []
for vote_count, voter_user_id in row:
voter_list.append(
(vote_count, get_user_model().objects.get(pk=voter_user_id)))
return voter_list
def validate_input(request):
3
Source : views.py
with Mozilla Public License 2.0
from freecodeschoolindy
with Mozilla Public License 2.0
from freecodeschoolindy
def post(self, request, pk):
# name, bio, github_username, avatar, current_level
profile = UserProfile(
**request.data
)
profile.user = get_user_model().objects.get(pk=pk)
profile.save()
return Response('Success')
@permission_classes([IsAuthenticated])
3
Source : test_views.py
with MIT License
from galojix
with MIT License
from galojix
def test_staff_request_update_view_post(init_feasible_db, client):
"""Test leave create view post."""
client.login(username="temporary", password="temporary")
staff_member = get_user_model().objects.get(username="one")
data = {
"request_1": "Yes",
"priority_1": 10,
"request_2": "No",
"priority_2": 10,
}
response = client.post(
reverse("staffrequest_update", args=(staff_member.id,)), data
)
assert response.status_code == 302
assert reverse("staffrequest_list") in response.url
def test_download_csv(init_feasible_db, client):
3
Source : test_user_api.py
with MIT License
from glebmikha
with MIT License
from glebmikha
def test_create_valid_user_success(self):
"""test creating user with valid payload is successfull"""
payload = {
'email': '[email protected]',
'password1': 'hardtocrack',
'password2': 'hardtocrack'
}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
user = get_user_model().objects.get(email=payload['email'])
self.assertTrue(user.check_password(payload['password1']))
self.assertNotIn('password', res.data)
def test_user_exists(self):
3
Source : auth.py
with MIT License
from huychau
with MIT License
from huychau
def authenticate(self, request, username=None, password=None, **kwargs):
try:
assert drfr_settings.LOGIN_USERNAME_FIELDS
filters = Q()
# Build filters with OR condition
for login_field in drfr_settings.LOGIN_USERNAME_FIELDS:
filters |= Q(**{login_field: username})
user = get_user_model().objects.get(filters)
# If user not found or more than one user, will return None
except (get_user_model().DoesNotExist, get_user_model().MultipleObjectsReturned):
return None
else:
if user.check_password(password):
return user
3
Source : views.py
with MIT License
from Jaseci-Labs
with MIT License
from Jaseci-Labs
def get(self, request, code):
"""Perform create override to send out activation Email"""
email = base64.b64decode(code).decode()
user = get_user_model().objects.get(email=email)
if (not user):
return Response('Invalid activation code/link!')
user.is_activated = True
user.save()
return Response('User successfully activated!')
class CreateTokenView(KnoxLoginView):
3
Source : mutations.py
with GNU General Public License v3.0
from JustShip
with GNU General Public License v3.0
from JustShip
def mutate(root, info, email):
try:
user = get_user_model().objects.get(email=email)
temporal_code = user.generate_temporal_code()
user.save()
send_password_recovery_mail.delay(user.email, temporal_code)
except get_user_model().DoesNotExist:
return GraphQLError('Used does not exists')
return PasswordReset(ok=True)
class PasswordResetConfirm(graphene.Mutation):
3
Source : queries.py
with GNU General Public License v3.0
from JustShip
with GNU General Public License v3.0
from JustShip
def resolve_profile(self, info, username):
"""
Given the username (no matter upper or lowercase), returns the user. If this isn't exists throw error
:param info: request and metadata info
:param username: username to search
:return: if user exists returns, else throw error
"""
try:
return get_user_model().objects.get(username__iexact=username)
except get_user_model().DoesNotExist:
return GraphQLError('User does not exists')
3
Source : export_user_catalog.py
with The Unlicense
from Kartones
with The Unlicense
from Kartones
def handle(self, *args: Any, **options: Dict) -> None:
username = cast(str, options["username"])
user = get_user_model().objects.get(username=username)
self._export_user_data(user)
self._export_user_games(user)
self._export_user_wishlisted_games(user)
self._export_filtered_games(user)
# always exporting all platforms as the list is small and we want to know on which platforms a game is available
self._export_platforms()
print("\n> Export finished")
def _export_user_data(self, user: settings.AUTH_USER_MODEL) -> None:
3
Source : models.py
with MIT License
from kiwicom
with MIT License
from kiwicom
def _make_assignee(self, user_last_name, column="solution_assignee"):
if not user_last_name:
return
try:
user = get_user_model().objects.get(last_name=user_last_name)
except get_user_model().DoesNotExist:
logger.error(f"Can't assign user: {user_last_name}")
return
setattr(self, column, user)
def make_solution_assignee(self, user_last_name):
3
Source : views.py
with MIT License
from konradgalczynski07
with MIT License
from konradgalczynski07
def get_queryset(self):
username = self.kwargs['username']
queryset = get_user_model().objects.get(
username=username).followers.all()
return queryset
class GetFollowingView(generics.ListAPIView):
3
Source : tasks.py
with MIT License
from NicolasLM
with MIT License
from NicolasLM
def delete_user(user_id: int):
try:
user = get_user_model().objects.get(pk=user_id)
except ObjectDoesNotExist:
logger.info('Not deleting user with id %s: already deleted', user_id)
return
if not user.um_profile.deletion_pending:
logger.info('Not deleting user %s: deletion not pending', user)
return
if user.last_login > now() - UM_DELETE_ACCOUNT_AFTER:
logger.info('Not deleting user %s: last login %s',
user, user.last_login)
return
logger.info('Deleting user %s', user)
user.delete()
3
Source : backends.py
with MIT License
from oil-rope
with MIT License
from oil-rope
def authenticate(self, request, username=None, password=None, **kwargs):
user = super().authenticate(request, username, password, **kwargs)
# If username is not and email is not even worth try
if '@' not in username:
return user
try:
# Little trick to just get username from existing user
user = get_user_model().objects.get(email=username)
username = user.username
user = super().authenticate(request, username, password, **kwargs)
except get_user_model().DoesNotExist:
return
finally:
return user
3
Source : views.py
with MIT License
from oil-rope
with MIT License
from oil-rope
def form_invalid(self, form):
response = super(LoginView, self).form_invalid(form)
cleaned_data = form.cleaned_data
try:
user = get_user_model().objects.get(username=cleaned_data['username'])
if not user.is_active:
warn_message = '{} {}'.format(
_('seems like this user is inactive.').capitalize(),
cfl(_('have you confirmed your email?')),
)
messages.warning(self.request, warn_message)
except get_user_model().DoesNotExist:
LOGGER.warning('Attempt to access a non existent user, we assume username is just incorrect.')
finally:
return response
def get_context_data(self, **kwargs):
3
Source : views.py
with MIT License
from oil-rope
with MIT License
from oil-rope
def get_user(self):
"""
Gets and returns user model.
Returns
-------
user: Instance
The user instance.
"""
primary_key = self.kwargs['pk']
user = get_user_model().objects.get(pk=primary_key)
return user
def get_token(self) -> str:
3
Source : manage_user.py
with GNU Affero General Public License v3.0
from openedx
with GNU Affero General Public License v3.0
from openedx
def _handle_remove(self, username, email):
"""
If a user with the given username and email exists, delete them.
"""
try:
user = get_user_model().objects.get(username=username)
except get_user_model().DoesNotExist:
self.stderr.write(_('Did not find a user with username "{}" - skipping.').format(username))
return
self._check_email_match(user, email)
self.stderr.write(_('Removing user: "{}"').format(user))
user.delete()
@transaction.atomic
3
Source : models.py
with MIT License
from organizerconnect
with MIT License
from organizerconnect
def user_can_edit(self, user_id):
"""Can the given user edit this resource?"""
if self.created_by.pk == user_id:
return True
user = get_user_model().objects.get(pk=user_id)
if user.has_perm('resources.can_add_resource_anywhere'):
return True
return False
def user_can_delete(self, user_id):
3
Source : customers.py
with MIT License
from oscarychen
with MIT License
from oscarychen
def _get_or_create_stripe_user_from_user_id(user_id):
"""
Returns a StripeUser instance given user_id.
:param str user_id: user id
"""
user = get_user_model().objects.get(id=user_id)
return _get_or_create_stripe_user_from_user_id_email(user.id, user.email)
def _get_or_create_stripe_user_from_customer_id(customer_id):
3
Source : tasks.py
with GNU General Public License v3.0
from rach-sharp
with GNU General Public License v3.0
from rach-sharp
def get_top_repos(user_pk, count=600):
user = get_user_model().objects.get(pk=user_pk)
social_token = SocialToken.objects.get(account__user=user)
github = Github(social_token.token)
top_repos = github.search_repositories("stars:>1")
repos = itertools.islice(top_repos, count) if count is not None else top_repos
for repo_response in repos:
repo, created = Repo.upsert_from_api_obj(repo_response)
if created:
get_image_url.delay(repo.pk)
@shared_task
3
Source : test_views.py
with MIT License
from Raekkeri
with MIT License
from Raekkeri
def get(self, request):
from django.contrib.auth import login
login(request, get_user_model().objects.get())
return Response({})
class ProtectedView(View):
3
Source : tasks.py
with MIT License
from sissbruecker
with MIT License
from sissbruecker
def schedule_bookmarks_without_snapshots(user_id: int):
user = get_user_model().objects.get(id=user_id)
bookmarks_without_snapshots = Bookmark.objects.filter(web_archive_snapshot_url__exact='', owner=user)
for bookmark in bookmarks_without_snapshots:
create_web_archive_snapshot(bookmark.id, False)
3
Source : mixins.py
with MIT License
from tarsil
with MIT License
from tarsil
def get_user(self):
"""Gets a User to whom which the message will be sent"""
try:
return get_user_model().objects.get(pk=self.kwargs.get('user_id'))
except get_user_model().DoesNotExist:
return
def get_thead_by_id(self):
3
Source : tasks.py
with MIT License
from uktrade
with MIT License
from uktrade
def submit_query_for_execution(
query_sql, query_connection, query_id, user_id, page, limit, timeout
):
user = get_user_model().objects.get(id=user_id)
query_log = QueryLog.objects.create(
sql=query_sql,
query_id=query_id,
run_by_user=user,
connection=query_connection,
page=page,
page_size=limit,
)
_run_querylog_query.delay(query_log.id, page, limit, timeout)
return query_log
@celery_app.task()
3
Source : user.py
with Apache License 2.0
from vikifox
with Apache License 2.0
from vikifox
def user_edit(request, ids):
user = get_user_model().objects.get(id=ids)
ldap_name = user.ldap_name
if request.method == 'POST':
form = EditUserForm(request.POST, instance=user)
if form.is_valid():
form.save()
status = 1
else:
status = 2
else:
form = EditUserForm(instance=user)
return render(request, 'accounts/user_edit.html', locals())
@login_required
See More Examples