本文整理汇总了Python中userena.utils.get_user_model函数的典型用法代码示例。如果您正苦于以下问题:Python get_user_model函数的具体用法?Python get_user_model怎么用?Python get_user_model使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_user_model函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_permissions
def check_permissions(self):
"""
Checks that all permissions are set correctly for the users.
:return: A set of users whose permissions was wrong.
"""
# Variable to supply some feedback
changed_permissions = []
changed_users = []
warnings = []
# Check that all the permissions are available.
for model, perms in ASSIGNED_PERMISSIONS.items():
if model == 'profile':
model_obj = get_profile_model()
else:
model_obj = get_user_model()
model_content_type = ContentType.objects.get_for_model(model_obj)
for perm in perms:
try:
Permission.objects.get(codename=perm[0],
content_type=model_content_type)
except Permission.DoesNotExist:
changed_permissions.append(perm[1])
Permission.objects.create(name=perm[1],
codename=perm[0],
content_type=model_content_type)
# it is safe to rely on settings.ANONYMOUS_USER_ID since it is a
# requirement of django-guardian
for user in get_user_model().objects.exclude(id=settings.ANONYMOUS_USER_ID):
try:
user_profile = get_user_profile(user=user)
except ObjectDoesNotExist:
warnings.append(_("No profile found for %(username)s") \
% {'username': user.username})
else:
all_permissions = get_perms(user, user_profile) + get_perms(user, user)
for model, perms in ASSIGNED_PERMISSIONS.items():
if model == 'profile':
perm_object = get_user_profile(user=user)
else:
perm_object = user
for perm in perms:
if perm[0] not in all_permissions:
assign_perm(perm[0], user, perm_object)
changed_users.append(user)
return (changed_permissions, changed_users, warnings)
示例2: test_change_email_form
def test_change_email_form(self):
user = get_user_model().objects.get(pk=1)
invalid_data_dicts = [
# No change in e-mail address
{'data': {'email': '[email protected]'},
'error': ('email', ['You\'re already known under this email.'])},
# An e-mail address used by another
{'data': {'email': '[email protected]'},
'error': ('email', ['This email is already in use. Please supply a different email.'])},
]
# Override locale settings since we are checking for existence of error
# messaged written in english. Note: it should not be necessasy but
# we have experienced such locale issues during tests on Travis builds.
# See: https://github.com/bread-and-pepper/django-userena/issues/446
with override('en'):
for invalid_dict in invalid_data_dicts:
form = forms.ChangeEmailForm(user, data=invalid_dict['data'])
self.failIf(form.is_valid())
self.assertEqual(form.errors[invalid_dict['error'][0]],
invalid_dict['error'][1])
# Test a valid post
form = forms.ChangeEmailForm(user,
data={'email': '[email protected]'})
self.failUnless(form.is_valid())
示例3: get_context_data
def get_context_data(self, username, extra_context=None, *args, **kwargs):
context = super(ProfileDetailView, self).get_context_data(*args, **kwargs)
user = get_object_or_404(get_user_model(),
username__iexact=username)
# Get profile
profile_model = get_profile_model()
try:
profile = user.get_profile()
except profile_model.DoesNotExist:
profile = profile_model.objects.create(user=user)
# Lookup badges
services = profile.services.all()
services_detailed = profile.service_detailed.all()
badges = ServiceBadge.objects.filter(services__in=services).distinct().order_by('category')
for b in badges:
b.user_services = []
for service_detailed in services_detailed:
if service_detailed.service in b.services.all():
b.user_services.append(service_detailed)
# Check perms
if not profile.can_view_profile(self.request.user):
return HttpResponseForbidden(_("You don't have permission to view this profile."))
# context
context['profile'] = profile
context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
context['badges'] = badges
return context
示例4: authenticate
def authenticate(self, identification, password=None, check_password=True):
"""
Authenticates a user through the combination email/username with
password.
:param identification:
A string containing the username or e-mail of the user that is
trying to authenticate.
:password:
Optional string containing the password for the user.
:param check_password:
Boolean that defines if the password should be checked for this
user. Always keep this ``True``. This is only used by userena at
activation when a user opens a page with a secret hash.
:return: The signed in :class:`User`.
"""
User = get_user_model()
try:
django.core.validators.validate_email(identification)
try: user = User.objects.get(email__iexact=identification)
except User.DoesNotExist: return None
except django.core.validators.ValidationError:
try: user = User.objects.get(username__iexact=identification)
except User.DoesNotExist: return None
if check_password:
if user.check_password(password):
return user
return None
else: return user
示例5: profile_detail
def profile_detail(request, username,
template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
"""
Detailed view of an user.
:param username:
String of the username of which the profile should be viewed.
:param template_name:
String representing the template name that should be used to display
the profile.
:param extra_context:
Dictionary of variables which should be supplied to the template. The
``profile`` key is always the current profile.
**Context**
``profile``
Instance of the currently viewed ``Profile``.
"""
user = get_object_or_404(get_user_model(), username__iexact=username)
profile = get_user_profile(user=user)
if not profile.can_view_profile(request.user):
raise PermissionDenied
if not extra_context: extra_context = dict()
extra_context['profile'] = profile
extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)
示例6: clean_username
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
``USERENA_FORBIDDEN_USERNAMES`` list.
"""
try:
user = get_user_model().objects.get(username__iexact=self.cleaned_data['username'])
except get_user_model().DoesNotExist:
pass
else:
if userena_settings.USERENA_ACTIVATION_REQUIRED and UserenaSignup.objects.filter(user__username__iexact=self.cleaned_data['username']).exclude(activation_key=userena_settings.USERENA_ACTIVATED):
raise forms.ValidationError(_('This username is already taken but not confirmed. Please check your email for verification steps.'))
raise forms.ValidationError(_('This username is already taken.'))
if self.cleaned_data['username'].lower() in userena_settings.USERENA_FORBIDDEN_USERNAMES:
raise forms.ValidationError(_('This username is not allowed.'))
return self.cleaned_data['username']
示例7: get_queryset
def get_queryset(self):
username = self.kwargs['username']
self.recipient = get_object_or_404(get_user_model(),
username__iexact=username)
queryset = Message.objects.get_conversation_between(self.request.user,
self.recipient)
self._update_unread_messages(queryset)
return queryset
示例8: profile_detail_extended
def profile_detail_extended(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_detail_extended.html', success_url=None,extra_context=None, **kwargs):
user = get_object_or_404(get_user_model(), username__iexact=username)
profile = get_user_profile(user=user)
if not extra_context: extra_context = dict()
extra_context['profile'] = profile
extra_context['profExpData'] = Profile_Experience.objects.filter(profile = profile)
extra_context['projExpData'] = Project_Experience.objects.filter(profile = profile)
extra_context['awardsData'] = Awards.objects.filter(profile = profile)
return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
示例9: create_user_with_name
def create_user_with_name(self, username, first_name, last_name,
email, password, active=False,
send_email=True):
"""
A simple wrapper that creates a new :class:`User`.
:param username:
String containing the username of the new user.
:param email:
String containing the email address of the new user.
:param password:
String containing the password for the new user.
:param active:
Boolean that defines if the user requires activation by clicking
on a link in an e-mail. Defaults to ``False``.
:param send_email:
Boolean that defines if the user should be sent an email. You could
set this to ``False`` when you want to create a user in your own
code, but don't want the user to activate through email.
:return: :class:`User` instance representing the new user.
"""
now = get_datetime_now()
new_user = get_user_model().objects.create_user(
username, email, first_name, last_name, password)
new_user.is_active = active
new_user.save()
userena_profile = self.create_userena_profile(new_user)
# All users have an empty profile
profile_model = get_profile_model()
try:
new_profile = new_user.get_profile()
except profile_model.DoesNotExist:
new_profile = profile_model(user=new_user)
new_profile.save(using=self._db)
# Give permissions to view and change profile
for perm in ASSIGNED_PERMISSIONS['profile']:
assign(perm[0], new_user, new_profile)
# Give permissions to view and change itself
for perm in ASSIGNED_PERMISSIONS['user']:
assign(perm[0], new_user, new_user)
if send_email:
userena_profile.send_activation_email(first_name, last_name)
return new_user
示例10: delete_expired_users
def delete_expired_users(self):
"""
Checks for expired users and delete's the ``User`` associated with
it. Skips if the user ``is_staff``.
:return: A list containing the deleted users.
"""
deleted_users = []
for user in get_user_model().objects.filter(is_staff=False, is_active=False):
if user.userena_signup.activation_key_expired():
deleted_users.append(user)
user.delete()
return deleted_users
示例11: profile_detail
def profile_detail(request, username,extra_context=None, **kwargs):
template_name = 'userena/profile_detail.html'
user = get_object_or_404(get_user_model(),
username__iexact=username)
profile_model = get_profile_model()
try:
profile = user.get_profile()
except profile_model.DoesNotExist:
profile = profile_model.objects.create(user=user)
if not profile.can_view_profile(request.user):
raise PermissionDenied
return render(request, template_name, {'profile': profile,'bulletins' : Post.objects.filter(tag1='announcement').order_by("-time")})
示例12: profile_detail
def profile_detail(request, username,
template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
"""
Detailed view of an user.
:param username:
String of the username of which the profile should be viewed.
:param template_name:
String representing the template name that should be used to display
the profile.
:param extra_context:
Dictionary of variables which should be supplied to the template. The
``profile`` key is always the current profile.
**Context**
``profile``
Instance of the currently viewed ``Profile``.
"""
user = get_object_or_404(get_user_model(),
username__iexact=username)
if Pago.objects.filter(user=user).exists():
last_pago = Pago.objects.filter(user=user).order_by('-fecha_expiracion').get()
else:
last_pago = None
today = date.today()
profile_model = get_profile_model()
try:
profile = user.get_profile()
except profile_model.DoesNotExist:
profile = profile_model.objects.create(user=user)
if not profile.can_view_profile(request.user):
return HttpResponseForbidden(_("You don't have permission to view this profile."))
if not extra_context: extra_context = dict()
extra_context['profile'] = user.get_profile()
extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
if last_pago is None or last_pago.fecha_expiracion < today:
extra_context['suscripcion_status'] = "Inactiva"
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)
示例13: profile_detail
def profile_detail(request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs):
"""
Detailed view of an user.
:param username:
String of the username of which the profile should be viewed.
:param template_name:
String representing the template name that should be used to display
the profile.
:param extra_context:
Dictionary of variables which should be supplied to the template. The
``profile`` key is always the current profile.
**Context**
``profile``
Instance of the currently viewed ``Profile``.
"""
user = get_object_or_404(get_user_model(),
username__iexact=username)
profile_model = get_profile_model()
try:
profile = user.get_profile()
except profile_model.DoesNotExist:
profile = profile_model.objects.create(user=user)
if not profile.can_view_profile(request.user):
return HttpResponseForbidden(_("You don't have permission to view this profile."))
if not extra_context:
extra_context = dict()
extra_context['profile'] = user.get_profile()
extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
extra_context['location'] = request.user_location["user_location_lat_lon"]
extra_context['is_admin'] = user.is_superuser
extra_context['per_page'] = int(request.GET.get('per_page', 6))
tabs_page = "profile-detail"
active_tab = request.session.get(tabs_page, "account-events")
extra_context['active_tab'] = active_tab
return ExtraContextTemplateView.as_view(
template_name=template_name,
extra_context=extra_context
)(request)
示例14: test_signin_redirect
def test_signin_redirect(self):
"""
Test redirect function which should redirect the user after a
succesfull signin.
"""
# Test with a requested redirect
self.failUnlessEqual(signin_redirect(redirect='/accounts/'), '/accounts/')
# Test with only the user specified
user = get_user_model().objects.get(pk=1)
self.failUnlessEqual(signin_redirect(user=user),
'/accounts/%s/' % user.username)
# The ultimate fallback, probably never used
self.failUnlessEqual(signin_redirect(), settings.LOGIN_REDIRECT_URL)
示例15: _friends
def _friends(request,username,
template_name='friends.html', success_url=None,
extra_context=None):
user = get_object_or_404(get_user_model(),
username__iexact=username)
profile = user.get_profile()
user_initial = {'first_name': user.first_name,
'last_name': user.last_name}
data = locals()
if not extra_context: extra_context = dict()
#extra_context['ftype'] = ftype
extra_context['profile'] = profile
#extra_context['user'] = user
#more_data = {'username':username,'ftype':ftype}
#return direct_to_template(template = 'friends.html', kwargs=kwargs)
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)