我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.contrib.sites.shortcuts.get_current_site()。
def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or :template:`flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.startswith('/'): url = '/' + url site_id = get_current_site(request).id try: f = get_object_or_404(FlatPage, url=url, sites=site_id) except Http404: if not url.endswith('/') and settings.APPEND_SLASH: url += '/' f = get_object_or_404(FlatPage, url=url, sites=site_id) return HttpResponsePermanentRedirect('%s/' % request.path) else: raise return render_flatpage(request, f)
def _send_invitation_mail(request, invitation, subject, template_name): if not invitation.invitee.email: return old_lang = translation.get_language() translation.activate(invitation.invitee.language) template = loader.get_template('groups/mail_{0}.txt'.format(template_name)) message = template.render({ 'invitation': invitation, 'site': get_current_site(request) }) translation.activate(old_lang) send_mail(settings.EMAIL_SUBJECT_PREFIX + subject, message, settings.DEFAULT_FROM_EMAIL, [invitation.invitee.email], fail_silently=True)
def render(self, context): if 'request' in context: site_pk = get_current_site(context['request']).pk else: site_pk = settings.SITE_ID flatpages = FlatPage.objects.filter(sites__id=site_pk) # If a prefix was specified, add a filter if self.starts_with: flatpages = flatpages.filter( url__startswith=self.starts_with.resolve(context)) # If the provided user is not authenticated, or no user # was provided, filter the list to only public flatpages. if self.user: user = self.user.resolve(context) if not user.is_authenticated(): flatpages = flatpages.filter(registration_required=False) else: flatpages = flatpages.filter(registration_required=False) context[self.context_name] = flatpages return ''
def render(self, context): if 'request' in context: site_pk = get_current_site(context['request']).pk else: site_pk = settings.SITE_ID flatpages = FlatPage.objects.filter(sites__id=site_pk) # If a prefix was specified, add a filter if self.starts_with: flatpages = flatpages.filter( url__startswith=self.starts_with.resolve(context)) # If the provided user is not authenticated, or no user # was provided, filter the list to only public flatpages. if self.user: user = self.user.resolve(context) if not user.is_authenticated: flatpages = flatpages.filter(registration_required=False) else: flatpages = flatpages.filter(registration_required=False) context[self.context_name] = flatpages return ''
def get_tenant(request): if not hasattr(request, '_cached_tenant'): try: request._cached_tenant = get_current_site(request).tenant_site.tenant return request._cached_tenant except (TenantSite.DoesNotExist, Site.DoesNotExist): pass try: tenant_http_header = 'HTTP_' + get_setting('TENANT_HTTP_HEADER').replace('-', '_').upper() request._cached_tenant = Tenant.objects.get(slug=request.META[tenant_http_header]) except LookupError: lazy_tenant = TenantMiddleware.get_current_tenant() if not lazy_tenant: return None lazy_tenant._setup() request._cached_tenant = lazy_tenant._wrapped except Tenant.DoesNotExist: return None return request._cached_tenant
def send_email(self, email): User = get_user_model() protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") current_site = get_current_site(self.request) email_qs = EmailAddress.objects.filter(email__iexact=email) for user in User.objects.filter(pk__in=email_qs.values("user")): uid = int_to_base36(user.id) token = self.make_token(user) password_reset_url = "{0}://{1}{2}".format( protocol, current_site.domain, reverse("account_password_reset_token", kwargs=dict(uidb36=uid, token=token)) ) ctx = { "user": user, "current_site": current_site, "password_reset_url": password_reset_url, } hookset.send_password_reset_email([user.email], ctx)
def get_referer_url(request): """ ?????????? ????????????? ???? REFERER, ???? ?? ? ???????? ?????. ?????, ?????????? MULTILANGUAGE_FALLBACK_URL """ referer = request.META.get('HTTP_REFERER') if not referer: return resolve_url(options.MULTILANGUAGE_FALLBACK_URL) site = get_current_site(request) url_parts = list(urlparse(referer)) if url_parts[1] != site.domain: return resolve_url(options.MULTILANGUAGE_FALLBACK_URL) url_parts[0] = '' url_parts[1] = '' return urlunparse(url_parts)
def dl_link(context, template='footer/dl_link.html'): request = context.get('request') if not request: return '' site = get_current_site(request) website = site.domain page_info = request.path_info set_crc = binascii.crc32(('set:%s:%s' % (website, page_info)).encode()) set_names = tuple(sorted(conf.DL_LINKS.keys())) url_set = conf.DL_LINKS[set_names[set_crc % len(set_names)]] url_crc = binascii.crc32(('url:%s:%s' % (website, page_info)).encode()) records = tuple(sorted(url_set, key=lambda x: x['url'])) record = records[url_crc % len(url_set)] return loader.render_to_string(template, record, request=context.get('request'))
def away_links(request, html): """ ???????? ??? ??????? ?????? ? html-???? ?? ?????? ????? ? ?????????? """ site = get_current_site(request) soup = Soup(html, 'html5lib') for tag in soup.findAll('a'): if tag.get('href'): parsed = parse.urlparse(tag['href']) if '' not in (parsed.scheme, parsed.netloc) \ and not parsed.query \ and not is_same_domain(parsed.netloc, site.domain): tag['target'] = '_blank' tag['href'] = resolve_url('away') + '?url=' + parsed.geturl() if tag.string: tag.string = parse.unquote(tag.string) return soup.body.decode_contents()
def away(request): referer = request.META.get('HTTP_REFERER') if not referer: return redirect(settings.LOGIN_REDIRECT_URL) # ??????????, ??? ? REFERER ???????? ??? referer = urlparse(referer) if '' in (referer.scheme, referer.netloc): return redirect(settings.LOGIN_REDIRECT_URL) # ?????????, ??? ??????? ? ?????? ????? site = get_current_site(request) if not is_same_domain(referer.netloc, site.domain): return redirect(settings.LOGIN_REDIRECT_URL) url = request.GET.get('url') or resolve_url('index') return render(request, 'away/away.html', { 'url': url })
def send(request, receivers, subject, message, fail_silently=True): if not receivers: return True if isinstance(receivers, str): receivers = [receivers] # ??????? ?????? ? subject site = get_current_site(request) subject = subject.format(domain=site.domain) plain = strip_tags(message) plain = re_newline_spaces.sub('\n', plain) plain = re_newlines.sub('\n\n', plain) send_mail( subject=subject, message=plain, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=receivers, html_message=message, fail_silently=fail_silently, )
def send_activation_email(request, user): subject = _('Profile Activation') from_email = settings.DEFAULT_FROM_EMAIL current_site = get_current_site(request) domain = current_site.domain code = get_random_string(20) context = { 'domain': domain, 'code': code, } act = Activation() act.code = code act.user = user act.save() html_content = render_to_string('email/activation_profile.html', context=context, request=request) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email]) msg.attach_alternative(html_content, 'text/html') msg.send()
def send_activation_change_email(request, user, new_email): subject = _('Change email') from_email = settings.DEFAULT_FROM_EMAIL current_site = get_current_site(request) domain = current_site.domain code = get_random_string(20) context = { 'domain': domain, 'code': code, } act = Activation() act.code = code act.user = user act.email = new_email act.save() html_content = render_to_string('email/change_email.html', context=context, request=request) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email]) msg.attach_alternative(html_content, 'text/html') msg.send()
def send_reset_password_email(request, user): from_email = settings.DEFAULT_FROM_EMAIL current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain token_generator = default_token_generator use_https = request.is_secure() context = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } subject = loader.render_to_string('registration/password_reset_subject.txt', context) subject = ''.join(subject.splitlines()) body = loader.render_to_string('registration/password_reset_email.html', context) email_message = EmailMultiAlternatives(subject, body, from_email, [user.email]) email_message.send()
def capabilities(request): """ The capabilities view is like the about page, but for consumption by code instead of humans. It serves to provide information about the Exchange instance. """ capabilities = {} capabilities["versions"] = { 'exchange': get_exchange_version(), 'geonode': get_pip_version('GeoNode'), 'geoserver': get_geoserver_version(), } mobile_extension_installed = "geonode_anywhere" in settings.INSTALLED_APPS capabilities["mobile"] = ( mobile_extension_installed and # check that the OAuth application has been created len(Application.objects.filter(name='Anywhere')) > 0 ) current_site = get_current_site(request) capabilities["site_name"] = current_site.name return JsonResponse({'capabilities': capabilities})
def send_invite(modeladmin, request, queryset): for r in queryset: if not Invite.objects.filter(request=r).exists(): Invite.objects.create(request=r) context = { "site": get_current_site(request).domain, "invite_link": build_absolute_uri( None, "{}?invite={}".format(reverse("account_signup"), r.invite.code) ) } send_mail( "Beta Invite", message=render_to_string("beta/email/invite.txt", context=context), html_message=render_to_string("beta/email/invite.html", context=context), from_email=getattr(settings, "DEFAULT_FROM_EMAIL"), recipient_list=[r.email] )
def send_email(modeladmin, request, queryset): our_email = settings.DEFAULT_FROM_EMAIL users = Subscription.objects.all() recipients = [user.contact_email for user in users] messages = [] site = get_current_site(request) template = get_template('festflow/newsletter.html') for user in users: for newsletter in queryset: content = template.render({ 'newsletter': newsletter.content, 'url': 'http://%s/subscribe?unsubscribe=%s' % ( site, user.identifier), }) messages.append(( "Newsletter", content, our_email, recipients)) send_mass_mail(messages, fail_silently=False)
def clean_username(self): alnum_re = re.compile(r"^\w+$") if not alnum_re.search(self.cleaned_data["username"]): raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores.")) User = get_user_model() lookup_kwargs = get_user_lookup_kwargs({ "{username}__iexact": self.cleaned_data["username"] }) qs = User.objects.filter(**lookup_kwargs) # TODO: Uncomment below lines when unique constraint on auth_user.username is resolved # ids = [user['id'] for user in qs.values()] # site = get_current_site(self.request) # prof = Profile.objects.filter(id__in=ids, site_id=site.id) if not qs.exists(): return self.cleaned_data["username"] raise forms.ValidationError(_("This username is already taken. Please choose another.")) # TODO: Disallow multiple emails per site
def authenticate(self, request, **credentials): User = get_user_model() print "user:" print User current_site = get_current_site(request) try: lookup_kwargs = get_user_lookup_kwargs({ "{username}__iexact": credentials["username"] }) user = User.objects.get(**lookup_kwargs) except (User.DoesNotExist, KeyError): return None else: try: profile = Profile.objects.get(user=user.id) print "profile:" print profile if user.check_password(credentials["password"]) and profile.site_id == current_site.id: return user except KeyError: return None
def email_login_link(request, email): current_site = get_current_site(request) # Create the signed structure containing the time and email address. email = email.lower().strip() data = {"t": int(time.time()), "e": email} data = json.dumps(data).encode("utf8") data = Signer().sign(base64.b64encode(data).decode("utf8")) # Send the link by email. send_mail( render_to_string("tokenauth_login_subject.txt", {"current_site": current_site}, request=request).strip(), render_to_string("tokenauth_login_body.txt", {"current_site": current_site, "data": data}, request=request), ta_settings.DEFAULT_FROM_EMAIL, [email], fail_silently=False, )
def send_confirmation_mail(self, request, emailconfirmation, signup): competition_data = request.session.get('competition_data') if competition_data: current_site = get_current_site(request) activate_url = self.get_email_confirmation_url( request, emailconfirmation ) + f'?competition_slug={competition_data.get("competition_slug")}' ctx = { "user": emailconfirmation.email_address.user, "activate_url": activate_url, "current_site": current_site, "key": emailconfirmation.key, } email_template = 'account/email/email_competition_confirmation' self.send_mail(email_template, emailconfirmation.email_address.email, ctx) else: super().send_confirmation_mail(request, emailconfirmation, signup)
def get_current_tip_of_day(request): user = request.user if user.is_anonymous(): return Response() try: visibility_filter = {'for_staff': True} if user.is_staff else {'for_nonstaff': True} site_filter = None if isinstance(get_current_site(request), Site): site_filter = Q(sites=None) | Q(sites__id__exact=get_current_site(request).id) available_tips = TipOfDay.objects.filter( active=True, **visibility_filter ).exclude( seen_by=user.pk, ).filter( Q(groups=None) | Q(groups__in=user.groups.all()) ).filter(site_filter).order_by('id') serializer = TipOfDaySerializer(available_tips[0]) return Response(serializer.data) except IndexError: return Response()
def form_valid(self, form): """??????????????.""" user = form.save() current_site = get_current_site(self.request) domain = current_site.domain subject_template = get_template( 'easy_regist/mailtemplate/new/subject.txt') message_template = get_template( 'easy_regist/mailtemplate/new/message.txt') context = { 'protocol': 'https' if self.request.is_secure() else 'http', 'domain': domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), 'user': user, } subject = subject_template.render(context) message = message_template.render(context) from_email = settings.EMAIL_HOST_USER to = [user.email] send_mail(subject, message, from_email, to) return super().form_valid(form)
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if request.method == "POST": form = authentication_form(request, data=request.POST) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) # Okay, security check complete. Log the user in. auth_login(request, form.get_user()) return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) current_site = get_current_site(request) context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context)
def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, extra_context=None): """ Logs out the user and displays 'You are logged out' message. """ auth_logout(request) if next_page is not None: next_page = resolve_url(next_page) if (redirect_field_name in request.POST or redirect_field_name in request.GET): next_page = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name)) # Security check -- don't allow redirection to a different host. if not is_safe_url(url=next_page, host=request.get_host()): next_page = request.path if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) current_site = get_current_site(request) context = { 'site': current_site, 'site_name': current_site.name, 'title': _('Logged out') } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context)