本文整理汇总了Python中django.contrib.auth.models.User方法的典型用法代码示例。如果您正苦于以下问题:Python models.User方法的具体用法?Python models.User怎么用?Python models.User使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.contrib.auth.models
的用法示例。
在下文中一共展示了models.User方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def create(self, validated_data):
now = timezone.now()
user = User(
email=validated_data.get('email'),
username=validated_data.get('username'),
last_login=now,
date_joined=now,
is_active=True
)
if validated_data.get('first_name'):
user.first_name = validated_data['first_name']
if validated_data.get('last_name'):
user.last_name = validated_data['last_name']
user.set_password(validated_data['password'])
# Make the first signup an admin / superuser
if not User.objects.filter(is_superuser=True).exists():
user.is_superuser = user.is_staff = True
user.save()
return user
示例2: destroy
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def destroy(self, request, **kwargs):
calling_obj = self.get_object()
target_obj = calling_obj
if request.data.get('username'):
# if you "accidentally" target yourself, that should be fine
if calling_obj.username == request.data['username'] or calling_obj.is_superuser:
target_obj = get_object_or_404(User, username=request.data['username'])
else:
raise PermissionDenied()
# A user can not be removed without apps changing ownership first
if len(models.App.objects.filter(owner=target_obj)) > 0:
msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj)) # noqa
raise AlreadyExists(msg)
try:
target_obj.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except ProtectedError as e:
raise AlreadyExists(e)
示例3: passwd
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def passwd(self, request, **kwargs):
if not request.data.get('new_password'):
raise DeisException("new_password is a required field")
caller_obj = self.get_object()
target_obj = self.get_object()
if request.data.get('username'):
# if you "accidentally" target yourself, that should be fine
if caller_obj.username == request.data['username'] or caller_obj.is_superuser:
target_obj = get_object_or_404(User, username=request.data['username'])
else:
raise PermissionDenied()
if not caller_obj.is_superuser:
if not request.data.get('password'):
raise DeisException("password is a required field")
if not target_obj.check_password(request.data['password']):
raise AuthenticationFailed('Current password does not match')
target_obj.set_password(request.data['new_password'])
target_obj.save()
return Response({'status': 'password set'})
示例4: update
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def update(self, request, **kwargs):
app = self.get_object()
old_owner = app.owner
if request.data.get('owner'):
if self.request.user != app.owner and not self.request.user.is_superuser:
raise PermissionDenied()
new_owner = get_object_or_404(User, username=request.data['owner'])
app.owner = new_owner
# ensure all downstream objects that are owned by this user and are part of this app
# is also updated
for downstream_model in [models.AppSettings, models.Build, models.Config,
models.Domain, models.Release, models.TLS]:
downstream_model.objects.filter(owner=old_owner, app=app).update(owner=new_owner)
app.save()
return Response(status=status.HTTP_200_OK)
示例5: users
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def users(self, request, *args, **kwargs):
app = get_object_or_404(models.App, id=kwargs['id'])
request.user = get_object_or_404(User, username=kwargs['username'])
# check the user is authorized for this app
if not permissions.is_app_user(request, app):
raise PermissionDenied()
data = {request.user.username: []}
keys = models.Key.objects \
.filter(owner__username=kwargs['username']) \
.values('public', 'fingerprint') \
.order_by('created')
if not keys:
raise NotFound("No Keys match the given query.")
for info in keys:
data[request.user.username].append({
'key': info['public'],
'fingerprint': info['fingerprint']
})
return Response(data, status=status.HTTP_200_OK)
示例6: test_init_with_user_custom_names_disabled
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def test_init_with_user_custom_names_disabled(self):
user = User.objects.create(
username='example_user',
email='user@example.com',
first_name='First',
last_name='Last',
)
form = PayFastForm(
initial={
'amount': 100,
'item_name': 'Example item',
},
user=user
)
self.assertEqual({
'amount': 100,
'email_address': 'user@example.com',
'item_name': 'Example item',
'm_payment_id': '1',
'merchant_id': '10000100',
'merchant_key': '46f0cd694581a',
'notify_url': notify_url(),
}, form.initial)
self.assertEqual(user, form.order.user)
示例7: test_it_works
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def test_it_works(self, api_client, settings):
user = User.objects.first() # Get the default user
settings.PEER_APPROVAL_ENFORCED = False
res = api_client.get("/api/v3/service_info/")
assert res.status_code == 200
assert res.data == {
"user": {
"id": user.id,
"first_name": user.first_name,
"last_name": user.last_name,
"email": user.email,
},
"peer_approval_enforced": settings.PEER_APPROVAL_ENFORCED,
"github_url": settings.GITHUB_URL,
}
示例8: login
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def login(request):
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# GET : Return the HTML template used for logging in a User #
# #
# POST : Attempt to login the User and authenticate their credentials. #
# If their login is invalid, let them know. In all cases, return #
# the User back to the main page #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if request.method == 'GET':
return render(request, 'login.html')
user = django.contrib.auth.authenticate(
username=request.POST['username'],
password=request.POST['password'])
if user is None:
return index(request, error='Unable to Authenticate User')
django.contrib.auth.login(request, user)
return django.http.HttpResponseRedirect('/index/')
示例9: clientGetWorkload
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def clientGetWorkload(request):
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# POST : Return a Dictionary of data in order to complete a workload. If #
# there are no tests for the User, 'None' will be returned. If we #
# cannot authenticate the User, 'Bad Credentials' is returned. If #
# the posted Machine does not belong the the User, 'Bad Machine' #
# is returned. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Verify the User's credentials
user = django.contrib.auth.authenticate(
username=request.POST['username'],
password=request.POST['password'])
if user == None: return HttpResponse('Bad Credentials')
# getWorkload() will verify the integrity of the request
return HttpResponse(OpenBench.utils.getWorkload(user, request))
示例10: clientSubmitNPS
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def clientSubmitNPS(request):
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# POST : Report the speed of the engines in the currently running Test #
# for the User and his Machine. We save this value to display #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Verify the User's credentials
user = django.contrib.auth.authenticate(
username=request.POST['username'],
password=request.POST['password'])
if user == None: return HttpResponse('Bad Credentials')
# Verify the Machine belongs to the User
machine = Machine.objects.get(id=int(request.POST['machineid']))
if machine.user != user: return HttpResponse('Bad Machine')
# Update the NPS and return 'None' to signal no errors
machine.mnps = float(request.POST['nps']) / 1e6; machine.save()
return HttpResponse('None')
示例11: user_board_listing
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def user_board_listing(request, account_id):
"""Return a paginated board listing view for account with account_id."""
metric_timeout_seconds = 60 * 2
queries = {
# default to boards contributed to
None: lambda x: ('contributed to', user_boards_contributed(x, viewing_user=request.user)),
'created': lambda x: ('created', user_boards_created(x, viewing_user=request.user)),
'evaluated': lambda x: ('evaluated', user_boards_evaluated(x, viewing_user=request.user)),
'contribute': lambda x: ('contributed to', user_boards_contributed(x, viewing_user=request.user)),
}
user = get_object_or_404(User, pk=account_id)
query = request.GET.get('query')
verb, board_list = queries.get(query, queries[None])(user)
desc = _('List of intelligence boards user {username} has {verb}').format(username=user.username, verb=verb)
context = {
'user': user,
'boards': make_paginator(request, board_list),
'contributors': cache.get_or_set('contributor_count', generate_contributor_count(), metric_timeout_seconds),
'evaluators': cache.get_or_set('evaluator_count', generate_evaluator_count(), metric_timeout_seconds),
'meta_description': desc,
'verb': verb
}
return render(request, 'boards/user_boards.html', context)
示例12: edit_team
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def edit_team(request, team_id):
"""Return a team edit view, or handle the form submission."""
# TODO: if user turns off invitation-required, let everyone in who had outstanding membership requests
team = get_object_or_404(Team, pk=team_id)
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
if request.method == 'POST':
form = TeamCreateForm(request.POST, instance=team)
if form.is_valid():
form.save()
messages.success(request, _('Updated team information'))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
else:
form = TeamCreateForm(instance=team)
return render(request, 'teams/edit_team.html', context={
'team': team,
'form': form
})
示例13: invite_members
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def invite_members(request, team_id):
"""Return a team edit view, or handle the form submission."""
team = get_object_or_404(Team, pk=team_id)
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
if request.method == 'POST':
form = TeamInviteForm(request.POST, team=team)
if form.is_valid():
to_invite = form.cleaned_data['members']
invites = [TeamRequest(team=team, inviter=request.user, invitee=x) for x in to_invite]
TeamRequest.objects.bulk_create(invites)
for user in to_invite:
notify.send(request.user, recipient=user, actor=request.user, verb='invite', action_object=team, target=user)
messages.success(request, _('Invited {count} members to the team').format(count=len(to_invite)))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
else:
form = TeamInviteForm(team=team)
return render(request, 'teams/invite.html', context={
'team': team,
'form': form
})
示例14: decide_invitation
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def decide_invitation(request, invite_id):
invite = get_object_or_404(TeamRequest, pk=invite_id)
team = invite.team
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
elif 'accept' in request.POST:
invite.team.members.add(invite.invitee)
invite.team.save()
notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee)
messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username))
elif 'reject' in request.POST:
notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee)
messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username))
else:
return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject'))
invite.delete()
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
示例15: join_team
# 需要导入模块: from django.contrib.auth import models [as 别名]
# 或者: from django.contrib.auth.models import User [as 别名]
def join_team(request, team_id):
team = get_object_or_404(Team, pk=team_id)
if team.members.filter(id=request.user.id).exists():
raise SuspiciousOperation(_('User is already a member of the team'))
elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required:
team.members.add(request.user)
team.save()
TeamRequest.objects.filter(invitee=request.user, team=team).delete()
messages.success(request, _('Joined team {name}').format(name=team.name))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
elif TeamRequest.objects.filter(invitee=request.user, team=team).exists():
return HttpResponseBadRequest(_('User already has a membership request with the team'))
else:
TeamRequest.objects.create(invitee=request.user, team=team)
if team.owner:
notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team)
messages.success(request, _('Requested invitation to team {name}').format(name=team.name))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))