def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ Same as `django.core.urlresolvers.reverse`, but optionally takes a request and returns a fully qualified URL, using the request to get the base URL. """ if format is not None: kwargs = kwargs or {} kwargs['format'] = format try: viewname_to_try = viewname if request: try: namespace = request.resolver_match.namespace except AttributeError: try: namespace = resolve(request.path).namespace except Http404: namespace=None if namespace and ':' not in viewname: viewname_to_try = '{namespace}:{viewname}'.format(namespace=namespace, viewname=viewname) url = django_reverse(viewname_to_try, args=args, kwargs=kwargs, **extra) except NoReverseMatch: url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) if request: return request.build_absolute_uri(url) return url
def reverse(route, target=None): if target: return django_reverse(route, kwargs={ 'target': target.pk, 'slug': slugify(target.name) }) return django_reverse(route)
def reverse(route, target=None): if target: return django_reverse(route, kwargs={ 'target': target.pk, 'slug': target.username_slug }) return django_reverse(route)
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None, query_kwargs=None): """ Wrapper of django.core.urlresolvers.reverse that attaches arguments in kwargs as query string parameters """ if query_kwargs: return '%s?%s' % (django_reverse(viewname, urlconf, args, None, prefix, current_app), '&'.join(['%s=%s' % (k, v) for k, v in query_kwargs.items()])) else: return django_reverse(viewname, urlconf, args, kwargs, prefix, current_app)
def reverse(route, target=None): if target: if route == 'admin_newsletters_send': return django_reverse(route, kwargs={ 'target': target.pk, 'token': target.token }) return django_reverse(route, kwargs={'target': target.pk}) return django_reverse(route)
def resync_forums(request, forum=0, progress=0): progress = int(progress) forums = request.session.get('sync_forums') if not forums: messages.info(request, _('No forums to resynchronize.'), 'forums') return redirect(reverse('admin_forums')) try: if not forum: forum = request.session['sync_forums'].pop() forum = Forum.objects.get(id=forum) except Forum.DoesNotExist: del request.session['sync_forums'] messages.error(request, _('Forum for resynchronization does not exist.'), 'forums') return redirect(reverse('admin_forums')) # Sync 50 threads threads_total = forum.thread_set.count() for thread in forum.thread_set.all()[progress:(progress + 1)]: thread.sync() thread.save(force_update=True) progress += 1 if not threads_total: return redirect(django_reverse('admin_forums_resync')) # Render Progress response = render_to_response('processing.html', { 'task_name': _('Resynchronizing Forums'), 'target_name': forum.name, 'message': _('Resynchronized %(progress)s from %(total)s threads') % { 'progress': progress, 'total': threads_total }, 'progress': progress * 100 / threads_total, 'cancel_link': reverse('admin_forums'), }, context_instance=RequestContext(request)) # Redirect where to? if progress >= threads_total: forum.sync() forum.save(force_update=True) response['refresh'] = '2;url=%s' % django_reverse( 'admin_forums_resync') else: response['refresh'] = '2;url=%s' % django_reverse( 'admin_forums_resync', kwargs={ 'forum': forum.pk, 'progress': progress }) return response
def _mails(self, users_and_watches): """Send readiness mails. """ revision = self.revision document = revision.document log.debug('Sending ready notifications for revision (id=%s)' % revision.id) for user, watches in users_and_watches: if hasattr(user, 'profile'): locale = user.profile.locale else: locale = document.locale with email_utils.uselocale(locale): subject = _(u'{title} has a revision ready for ' 'localization').format(title=document.title) template = 'wiki/email/ready_for_l10n.ltxt' c = context_dict(revision, ready_for_l10n=True) # TODO: Expose all watches c['watch'] = watches[0] c['url'] = django_reverse('wiki.select_locale', args=[document.slug]) msg = email_utils.render_email(template, c) yield EmailMessage(subject, msg, settings.TIDINGS_FROM_ADDRESS, [user.email])
def user(request, username): user = get_object_or_404(User, username=username, is_active=True) via = request.GET.get('f') delta = datetime.datetime.now() - user.date_joined data = {'username': username, 'profile': user.profile, 'logged_in': request.user.is_authenticated(), 'date_joined_delta': _total_seconds(delta), 'is_user_page': True, 'countries': json.dumps(countries[request.locale]), 'sparked_countries': json.dumps(user.profile.sparked_countries), 'twitter_url': urlquote(user.profile.twitter_sharing_url), 'twitter_msg': urlquote(unicode(TWITTER_SHARE_MSG)), 'facebook_url': user.profile.facebook_sharing_url, 'facebook_redirect': absolute_url(django_reverse('desktop.close_popup')), 'facebook_title': urlquote(unicode(FACEBOOK_SPARK_TITLE)), 'facebook_spark_msg': urlquote(unicode(FACEBOOK_SPARK_MSG)), 'stats': get_global_stats(), 'FB_APP_ID': settings.FB_APP_ID} if not request.user.is_authenticated(): data.update({'login_next_url': request.path}) response = jingo.render(request, 'desktop/user.html', data) return set_sharing_cookies(response, username, via)
def _mails(self, users_and_watches): """Send readiness mails. """ revision = self.revision document = revision.document log.debug('Sending ready notifications for revision (id=%s)' % revision.id) ready_subject = _( u'{title} has a revision ready for localization').format( title=document.title, creator=revision.creator, locale=document.locale) ready_template = loader.get_template( 'wiki/email/ready_for_l10n.ltxt') c = context_dict(revision, ready_for_l10n=True) for user, watches in users_and_watches: c['watch'] = watches[0] # TODO: Expose all watches. try: profile = user.profile except Profile.DoesNotExist: locale = settings.WIKI_DEFAULT_LANGUAGE else: locale = profile.locale c['url'] = django_reverse('wiki.select_locale', args=[document.slug]) yield EmailMessage(ready_subject, ready_template.render(Context(c)), settings.TIDINGS_FROM_ADDRESS, [user.email])
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): original_kwargs = kwargs if urlconf is None: urlconf = get_urlconf() or settings.ROOT_URLCONF # We behave differently if we're using the no-region urlconf with the # no-region django-hosts host. if urlconf == 'main.urls_no_region': if kwargs and kwargs.get('region'): del kwargs['region'] try: return django_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, prefix=prefix, current_app=current_app) except NoReverseMatch as e: if urlconf == 'main.urls_no_region': # Try the base urlconf and original kwargs host = settings.DEFAULT_HOST return reverse_full(host, viewname, view_args=args, view_kwargs=original_kwargs) else: raise e
def sharebadge(request): badge_id = request.GET.get('id') try: # Verify that this badge exists badge = Challenge.objects.get(pk=badge_id) # Verify also that this user has earned this badge profile = request.user.profile has_badge = profile.has_badge(badge_id) if has_badge: data = {'badge_name': get_badge_name(badge.id), 'twitter_url': urlquote(profile.twitter_sharing_url), 'twitter_badge_msg': TWITTER_BADGE_MSG, 'facebook_url': profile.facebook_sharing_url, 'facebook_redirect': absolute_url(django_reverse('mobile.home')), 'facebook_title': urlquote(unicode(FACEBOOK_SPARK_TITLE)), 'facebook_badge_msg': FACEBOOK_BADGE_MSG, 'facebook_img': absolute_url(settings.MEDIA_URL+'img/badges/fb/'+badge.id.replace('_','-')+'.png'), 'facebook_desc': urlquote(badge.badge_description), 'FB_APP_ID': settings.FB_APP_ID} return jingo.render(request, 'mobile/sharebadge.html', data) except Challenge.DoesNotExist: # Ignore invalid badges pass # Return to earned badges page if the querystring contains an invalid badge id # or if the user tried to share a badge he/she has not earned yet. return HttpResponseRedirect(reverse('mobile.badges'))
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None): """ This monkey patch will add the journal_code to reverse kwargs if the URL_CONFIG setting is set to 'patch' """ if not viewname.startswith('djdt'): local_request = GlobalRequestMiddleware.get_current_request() if settings.URL_CONFIG == 'path': code = local_request.journal.code if local_request.journal else 'press' if kwargs and not args: kwargs['journal_code'] = code else: kwargs = {'journal_code': code} # Drop kwargs if user is accessing admin site. if local_request.path.startswith('/admin/'): kwargs.pop('journal_code') # Drop kwargs if we have args (most likely from the template if args: kwargs = None args = [code] + args url = django_reverse(viewname, urlconf, args, kwargs, current_app) # Ensure any unicode characters in the URL are escaped. return iri_to_uri(url)
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None, force_locale=False, locale=None, unprefixed=False): """Wraps Django's reverse to prepend the correct locale. force_locale -- Ordinarily, if get_url_prefixer() returns None, we return an unlocalized URL, which will be localized via redirect when visited. Set force_locale to True to force the insertion of a default locale when there is no set prefixer. If you are writing a test and simply wish to avoid LocaleURLMiddleware's initial 301 when passing in an unprefixed URL, it is probably easier to substitute LocalizingClient for any uses of django.test.client.Client and forgo this kwarg. locale -- By default, reverse prepends the current locale (if set) or the default locale if force_locale == True. To override this behavior and have it prepend a different locale, pass in the locale parameter with the desired locale. When passing a locale, the force_locale is not used and is implicitly True. """ if locale: prefixer = Prefixer(locale=locale) else: prefixer = get_url_prefixer() if unprefixed: prefixer = None elif not prefixer and force_locale: prefixer = Prefixer() if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, prefix=prefix, current_app=current_app) # HACK: We rewrite URLs in apps/wiki/middleware.py, but don't have a # concept for pluggable middleware in reverse() as far as I know. So, this # is an app-specific override. ABSOLUTE_URL_OVERRIDES doesn't really do the # trick. # # See apps/wiki/tests/test_middleware.py for a test exercising this hack. if url.startswith('/docs/'): # HACK: Import here, because otherwise it's a circular reference from kuma.wiki.jobs import DocumentZoneURLRemapsJob # Work out a current locale, from some source. zone_locale = locale if not zone_locale: if prefixer: zone_locale = prefixer.locale else: zone_locale = settings.WIKI_DEFAULT_LANGUAGE # Get DocumentZone remaps for the current locale. remaps = DocumentZoneURLRemapsJob().get(zone_locale) for original_path, new_path in remaps: if url.startswith(original_path): url = url.replace(original_path, new_path, 1) break if prefixer: return prefixer.fix(url) else: return url
def _mails(self, users_and_watches): """Send readiness mails. """ revision = self.revision document = revision.document log.debug('Sending ready notifications for revision (id=%s)' % revision.id) ready_subject = _( u'{title} has a revision ready for localization').format( title=document.title, creator=revision.creator, locale=document.locale) ready_template = loader.get_template('wiki/email/ready_for_l10n.ltxt') c = context_dict(revision, ready_for_l10n=True) for user, watches in users_and_watches: c['watch'] = watches[0] # TODO: Expose all watches. try: profile = user.profile except Profile.DoesNotExist: locale = settings.WIKI_DEFAULT_LANGUAGE else: locale = profile.locale c['url'] = django_reverse('wiki.select_locale', args=[document.slug]) yield EmailMessage(ready_subject, ready_template.render(Context(c)), settings.TIDINGS_FROM_ADDRESS, [user.email])
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, force_locale=False, locale=None): """Wraps Django's reverse to prepend the correct locale. force_locale -- Ordinarily, if get_url_prefixer() returns None, we return an unlocalized URL, which will be localized via redirect when visited. Set force_locale to True to force the insertion of a default locale when there is no set prefixer. If you are writing a test and simply wish to avoid LocaleURLMiddleware's initial 301 when passing in an unprefixed URL, it is probably easier to substitute LocalizingClient for any uses of django.test.client.Client and forgo this kwarg. locale -- By default, reverse prepends the current locale (if set) or the default locale if force_locale == True. To override this behavior and have it prepend a different locale, pass in the locale parameter with the desired locale. When passing a locale, the force_locale is not used and is implicitly True. """ if locale: prefixer = Prefixer(locale=locale) else: prefixer = get_url_prefixer() if not prefixer and force_locale: prefixer = Prefixer() if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf, args, kwargs, prefix) if prefixer: return prefixer.fix(url) else: return url
def reverse_url(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): return settings.ASCRIBE_URL_NO_APP[:-1] \ + django_reverse(viewname, urlconf, args, kwargs, prefix, current_app)
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): if format is not None: kwargs = kwargs or {} kwargs['format'] = format _url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) if request: _url = request.build_absolute_uri(url) return _url
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, force_locale=False, locale=None): """Wraps Django's reverse to prepend the correct locale. force_locale -- Ordinarily, if get_url_prefixer() returns None, we return an unlocalized URL, which will be localized via redirect when visited. Set force_locale to True to force the insertion of a default locale when there is no set prefixer. If you are writing a test and simply wish to avoid LocaleURLMiddleware's initial 301 when passing in an unprefixed URL, it is probably easier to substitute LocalizingClient for any uses of django.test.client.Client and forgo this kwarg. locale -- By default, reverse prepends the current locale (if set) or the default locale if force_locale == True. To override this behavior and have it prepend a different locale, pass in the locale parameter with the desired locale. When passing a locale, the force_locale is not used and is implicitly True. """ if locale: prefixer = Prefixer(locale=locale) else: prefixer = get_url_prefixer() if not prefixer and force_locale: prefixer = Prefixer() if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf, args, kwargs, prefix) # HACK: We rewrite URLs in apps/wiki/middleware.py, but don't have a # concept for pluggable middleware in reverse() as far as I know. So, this # is an app-specific override. ABSOLUTE_URL_OVERRIDES doesn't really do the # trick. # # See apps/wiki/tests/test_middleware.py for a test exercising this hack. if url.startswith('/docs/'): # HACK: Import here, because otherwise it's a circular reference from wiki.models import DocumentZone # Work out a current locale, from some source. zone_locale = locale if not zone_locale: if prefixer: zone_locale = prefixer.locale else: zone_locale = settings.WIKI_DEFAULT_LANGUAGE # Get DocumentZone remaps for the current locale. remaps = DocumentZone.objects.get_url_remaps(zone_locale) for remap in remaps: if url.startswith(remap['original_path']): url = url.replace(remap['original_path'], remap['new_path'], 1) break if prefixer: return prefixer.fix(url) else: return url
def rev(self, route_name, **kwargs): self.kwargs.update(kwargs) filter_keys = get_resolver(None).reverse_dict[route_name][0][0][1] filtered_kwargs = { filter_key: self.kwargs.get(filter_key) for filter_key in filter_keys } return full_uri(self.request, django_reverse(route_name, kwargs=filtered_kwargs))
def reverse(viewname, request=None, use_default_base=False, *args, **kwargs): """ Django reverse lookup that returns URLs suitable for iframe-embedding """ # perform standard reverse lookup and strip out script_prefix absolute_url = django_reverse(viewname, *args, **kwargs) script_prefix = get_script_prefix() url = absolute_url[len(script_prefix)-1:] # check if a manual override is defined if rewrites.get(url): return rewrites.get(url) # try to find a suitable internal-external mapping in configuration prefix_internal = None prefix_external = None for pin, pex in mappings: if url.startswith(pin): prefix_internal = pin prefix_external = pex break if prefix_internal is None: # no match found, fall back to standard URL return absolute_url query_url = url[len(prefix_internal):] if use_default_base and default_base is not None: # use default location iframed_url = '%(base)s%(prefix)s?%(query_id)s=%(url)s' % { 'base': default_base, 'prefix': prefix_external, 'query_id': query_id, 'url': query_url, } return iframed_url elif request is not None and hasattr(request, 'referer'): # build absolute URL from referer attribute referer = request.referer if hasattr(request, 'aliased_referer_path'): path = request.aliased_referer_path else: path = referer.path iframed_url = '%(scheme)s://%(netloc)s%(path)s?%(query_id)s=%(url)s' % { 'scheme': referer.scheme, 'netloc': referer.netloc, 'path': path, 'query_id': query_id, 'url': query_url, } return iframed_url else: # referer not set but required, fall back to standard URL return absolute_url
def action_resync(self, items, checked): clean_checked = [] for item in items: if item.pk in checked and item.type == 'forum': clean_checked.append(item.pk) if not clean_checked: return Message(_('Only forums can be resynchronized.'), 'error'), reverse('admin_forums') self.request.session['sync_forums'] = clean_checked return Message('Meh', 'success'), django_reverse('admin_forums_resync')
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): if VERSION < (1, 6): if args: args = [urlquote(x) for x in args] if kwargs: kwargs = dict([(x, urlquote(y)) for x, y in six.iteritems(kwargs)]) return django_reverse(viewname, urlconf, args, kwargs, prefix, current_app)
def resync_forums(request, forum=0, progress=0): progress = int(progress) forums = request.session.get('sync_forums') if not forums: messages.info(request, _('No forums to resynchronize.'), 'forums') return redirect(reverse('admin_forums')) try: if not forum: forum = request.session['sync_forums'].pop() forum = Forum.objects.get(id=forum) except Forum.DoesNotExist: del request.session['sync_forums'] messages.error(request, _('Forum for resynchronization does not exist.'), 'forums') return redirect(reverse('admin_forums')) # Sync 50 threads threads_total = forum.thread_set.count() for thread in forum.thread_set.all()[progress:(progress+1)]: thread.sync() thread.save(force_update=True) progress += 1 if not threads_total: return redirect(django_reverse('admin_forums_resync')) # Render Progress response = render_to_response('processing.html', { 'task_name': _('Resynchronizing Forums'), 'target_name': forum.name, 'message': _('Resynchronized %(progress)s from %(total)s threads') % {'progress': progress, 'total': threads_total}, 'progress': progress * 100 / threads_total, 'cancel_link': reverse('admin_forums'), }, context_instance=RequestContext(request)); # Redirect where to? if progress >= threads_total: forum.sync() forum.save(force_update=True) response['refresh'] = '2;url=%s' % django_reverse('admin_forums_resync') else: response['refresh'] = '2;url=%s' % django_reverse('admin_forums_resync', kwargs={'forum': forum.pk, 'progress': progress}) return response
def __call__(self, request): # Don't apply middleware for EXEMPT_L10N_URLS for view_url in settings.EXEMPT_L10N_URLS: if re.search(view_url, request.path): return self.get_response(request) if not request.user.is_authenticated(): return HttpResponseRedirect(django_reverse('oidc_authentication_init')) return self.get_response(request)
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, locale=None): """Wraps Django's reverse to prepend the requested locale. Keyword Arguments: * locale - Use this locale prefix rather than the current active locale. Keyword Arguments passed to Django's reverse: * viewname * urlconf * args * kwargs * current_app """ if locale: with translation.override(locale): return django_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app) else: return django_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app)
def reverse(viewname, *args, **kwargs): """ Same as `django.core.urlresolvers.reverse`, but optionally takes a request and returns a fully qualified URL, using the request to get the base URL. """ request = kwargs.pop("request", None) url = django_reverse(viewname, *args, **kwargs) if request: return request.build_absolute_uri(url) return url
def authenticate(self, request, **kwargs): """Authenticate a user based on the OIDC code flow.""" # If the request has the /fxa/callback/ path then probably there is a login # with Firefox Accounts. In this case just return None and let # the FxA backend handle this request. if request and not request.path == django_reverse('oidc_authentication_callback'): return None return super(SumoOIDCAuthBackend, self).authenticate(request, **kwargs)
def sharelink(request): data = {'twitter_url': urlquote(request.user.profile.twitter_sharing_url), 'twitter_msg': urlquote(unicode(TWITTER_SPARK_MSG)), 'facebook_url': request.user.profile.facebook_sharing_url, 'facebook_redirect': absolute_url(django_reverse('mobile.home')), 'facebook_title': urlquote(unicode(FACEBOOK_SPARK_TITLE)), 'facebook_spark_msg': urlquote(unicode(FACEBOOK_SPARK_MSG)), 'FB_APP_ID': settings.FB_APP_ID} return jingo.render(request, 'mobile/sharelink.html', data)
def authenticate(self, request, **kwargs): """Authenticate a user based on the OIDC/oauth2 code flow.""" # If the request has the /oidc/callback/ path then probably there is a login # attempt in the admin interface. In this case just return None and let # the OIDC backend handle this request. if request and request.path == django_reverse('oidc_authentication_callback'): return None return super(FXAAuthBackend, self).authenticate(request, **kwargs)
def send(request, target, token): try: newsletter = Newsletter.objects.get(pk=target, token=token) # Build recipients queryset recipients = User.objects if newsletter.ranks.all(): recipients = recipients.filter(rank__in=[x.pk for x in newsletter.ranks.all()]) if not newsletter.ignore_subscriptions: recipients = recipients.filter(receive_newsletters=1) recipients_total = recipients.count() if recipients_total < 1: messages.error(request, _('No recipients for newsletter "%(newsletter)s" could be found.') % {'newsletter': newsletter.name}, 'newsletters') return redirect(reverse('admin_newsletters')) for user in recipients.all()[newsletter.progress:(newsletter.progress + newsletter.step_size)]: tokens = { '{{ board_name }}': settings.board_name, '{{ username }}': user.username, '{{ user_link }}': django_reverse('user', kwargs={'username': user.username_slug, 'user': user.pk}), '{{ board_link }}': settings.BOARD_ADDRESS, } subject = newsletter.parse_name(tokens) user.email_user(request, 'users/newsletter', subject, { 'newsletter': newsletter, 'subject': subject, 'content_html': newsletter.parse_html(tokens), 'content_plain': newsletter.parse_plain(tokens), }) newsletter.progress += 1 newsletter.generate_token() newsletter.save(force_update=True) if newsletter.progress >= recipients_total: newsletter.progress = 0 newsletter.save(force_update=True) messages.success(request, _('Newsletter "%(newsletter)s" has been sent.') % {'newsletter': newsletter.name}, 'newsletters') return redirect(reverse('admin_newsletters')) # Render Progress response = render_to_response('processing.html', { 'task_name': _('Sending Newsletter'), 'target_name': newsletter.name, 'message': _('Sent to %(progress)s from %(total)s users') % {'progress': newsletter.progress, 'total': recipients_total}, 'progress': newsletter.progress * 100 / recipients_total, 'cancel_link': reverse('admin_newsletters'), }, context_instance=RequestContext(request)); response['refresh'] = '2;url=%s' % reverse('admin_newsletters_send', newsletter) return response except Newsletter.DoesNotExist: messages.error(request, _('Requested Newsletter could not be found.'), 'newsletters') return redirect(reverse('admin_newsletters'))
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None): """Wraps Django's reverse to prepend the correct locale.""" prefixer = get_url_prefix() if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf, args, kwargs, prefix) if prefixer: return prefixer.fix(url) else: return url
def reverse(viewname, site_id=None, add_domain=False, urlconf=None, args=None, kwargs=None, current_app=None, qs_kwargs=None): from .domain import get_domain urlconf = (get_domain(site_id).urlconf if site_id is not None and urlconf is None and settings.SITE_ID != site_id else urlconf) site_id = settings.SITE_ID if site_id is None else site_id domain = get_domain(site_id).url if add_domain else '' qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else '' return ''.join((domain, django_reverse(viewname, urlconf, args, kwargs, current_app), qs))
def _mails(self, users_and_watches): """Send approval or readiness mails, as appropriate. If a given user is watching the Ready event and the revision is in fact ready, say so. Otherwise, just send the Approval email. """ revision = self._revision document = revision.document is_ready = revision.is_ready_for_localization log.debug('Sending approved/ready notifications for revision (id=%s)' % revision.id) ready_subject, approved_subject = [s.format( title=document.title, reviewer=revision.reviewer.username, locale=document.locale) for s in [_(u'{title} has a revision ready for localization'), _(u'{title} ({locale}) has a new approved revision ' '({reviewer})')]] ready_template = loader.get_template('wiki/email/ready_for_l10n.ltxt') approved_template = loader.get_template('wiki/email/approved.ltxt') approved_url = reverse('wiki.document', locale=document.locale, args=[document.slug]) for user, watches in users_and_watches: if (is_ready and ReadyRevisionEvent.event_type in (w.event_type for w in watches)): c = context_dict(revision, ready_for_l10n=True) c['watch'] = watches[0] # TODO: Expose all watches. # We should send a "ready" mail. try: profile = user.profile except Profile.DoesNotExist: locale = settings.WIKI_DEFAULT_LANGUAGE else: locale = profile.locale c['url'] = django_reverse('wiki.select_locale', args=[document.slug]) yield EmailMessage(ready_subject, ready_template.render(Context(c)), settings.TIDINGS_FROM_ADDRESS, [user.email]) else: c = context_dict(revision, revision_approved=True) c['url'] = approved_url c['watch'] = watches[0] # TODO: Expose all watches. c['reviewer'] = revision.reviewer.username # Send an "approved" mail: yield EmailMessage(approved_subject, approved_template.render(Context(c)), settings.TIDINGS_FROM_ADDRESS, [user.email])
def _mails(self, users_and_watches): """Send approval or readiness mails, as appropriate. If a given user is watching the Ready event and the revision is in fact ready, say so. Otherwise, just send the Approval email. """ revision = self._revision document = revision.document is_ready = revision.is_ready_for_localization log.debug('Sending approved/ready notifications for revision (id=%s)' % revision.id) ready_subject, approved_subject = [ s.format(title=document.title, reviewer=revision.reviewer.username, locale=document.locale) for s in [ _(u'{title} has a revision ready for localization'), _(u'{title} ({locale}) has a new approved revision ' '({reviewer})') ] ] ready_template = loader.get_template('wiki/email/ready_for_l10n.ltxt') approved_template = loader.get_template('wiki/email/approved.ltxt') approved_url = reverse('wiki.document', locale=document.locale, args=[document.slug]) for user, watches in users_and_watches: if (is_ready and ReadyRevisionEvent.event_type in (w.event_type for w in watches)): c = context_dict(revision, ready_for_l10n=True) c['watch'] = watches[0] # TODO: Expose all watches. # We should send a "ready" mail. try: profile = user.profile except Profile.DoesNotExist: locale = settings.WIKI_DEFAULT_LANGUAGE else: locale = profile.locale c['url'] = django_reverse('wiki.select_locale', args=[document.slug]) yield EmailMessage(ready_subject, ready_template.render(Context(c)), settings.TIDINGS_FROM_ADDRESS, [user.email]) else: c = context_dict(revision, revision_approved=True) c['url'] = approved_url c['watch'] = watches[0] # TODO: Expose all watches. c['reviewer'] = revision.reviewer.username # Send an "approved" mail: yield EmailMessage(approved_subject, approved_template.render(Context(c)), settings.TIDINGS_FROM_ADDRESS, [user.email])
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ Same as `django.core.urlresolvers.reverse`, but optionally takes a request and returns a fully qualified URL, using the request to get the base URL. """ if format is not None: kwargs = kwargs or {} kwargs['format'] = format url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) if request: return request.build_absolute_uri(url) return url
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): """Wraps django's reverse to prepend the correct locale and app.""" prefixer = get_url_prefix() # Blank out the script prefix since we add that in prefixer.fix(). if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf, args, kwargs, prefix, current_app) if prefixer: return prefixer.fix(url) else: return url
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None): """Wraps Django's reverse to prepend the correct locale.""" prefixer = get_url_prefix() if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf, args, kwargs, prefix) if prefixer: url = prefixer.fix(url) # Ensure any unicode characters in the URL are escaped. return iri_to_uri(url)
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ Same as `django.core.urlresolvers.reverse`, but optionally takes a request and returns a fully qualified URL, using the request to get the base URL. """ if format is not None: kwargs = kwargs or {} kwargs["format"] = format url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) if request: return request.build_absolute_uri(url) return url
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): u""" Django ``reverse()`` expects exactly the same arguments as parsed from url. However, sometimes it is more convenient to call ``reverse()`` with complex objects that can be reduced to url arguments automatically. Suppose we have model "Author" that is represented by its "pk" and "name" in the url: url(r'^/(?P<name>\w+)/(?P<pk>\d+)/$', author_view, name='detail') Instead of writing: reverse('detail', kwargs=dict(name=author.name, pk=author.pk)) {% url 'detail' name=author.name pk=author.pk %} We may write simply: reverse('detail', kwargs=dict(author=author)) {% url 'detail' author=author %} If we register the following reverse adaptor: @reverse_adaptor('detail', 'author') def author_adaptor(author): return dict(name=author.name, pk=author.pk) Further, this function strips ``kwargs`` of all None values and ``args`` of all trailing None values as Django ``reverse()`` breaks if given None as an argument. Django resolver may populate arguments with None when parsing certain urls, therefore it's not possible to recostruct such urls with Django ``reverse()``. Unfortunatelly, if None occurs in the middle of ``args`` there is no way to fix it. """ # Make sure urls were included. Otherwise the adaptors don't have to be registered yet if this # is the first call to the resolver. get_resolver(urlconf or get_urlconf())._populate() for argname, adaptor in reverse_adaptors[viewname]: if kwargs and argname in kwargs: kwargs.update(adaptor(kwargs.pop(argname))) if args is not None: while args and args[-1] is None: args = args[:-1] if kwargs is not None: kwargs = dict((k, v) for k, v in kwargs.iteritems() if v is not None) return django_reverse(viewname, urlconf, args, kwargs, prefix, current_app)
def url(name, *args, **kwargs): """ Shortcut filter for reverse url on templates. Is a alternative to django {% url %} tag, but more simple. Usage example: {{ url('web:timeline', userid=2) }} This is a equivalent to django: {% url 'web:timeline' userid=2 %} """ return django_reverse(name, args=args, kwargs=kwargs)
def __call__(self, request): # Don't apply middleware for EXEMPT_L10N_URLS for view_url in settings.EXEMPT_L10N_URLS: if re.search(view_url, request.path): return self.get_response(request) if not request.user.is_authenticated(): return HttpResponseRedirect(django_reverse('oidc_authentication_init')) if request.user.userprofile and request.user.userprofile.is_complete: return HttpResponseRedirect('/beta') return self.get_response(request)
def reverse(value, *args, **kwargs): """ Shortcut filter for reverse url on templates. Is a alternative to django {% url %} tag, but more simple. Usage example: {{ 'web:timeline'|reverse(userid=2) }} This is a equivalent to django: {% url 'web:timeline' userid=2 %} """ return django_reverse(value, args=args, kwargs=kwargs)
def reverse(resource, api=None, namespace=None, **resources): """ Reverse resource by ResourceClass or name string. :param resource: Resource Class or String name. :param api: API intance (if resource is string) :param namespace: Set namespace prefix :param **resources: Uri params :return str: URI string """ if isinstance(resource, basestring): url_name = resource if not api: raise AssertionError("You sould send api parameter") if not api.resources.get(url_name): raise AssertionError("Invalid resource name: %s" % url_name) else: url_name = resource._meta.url_name api = resource.api params = dict() query = defaultdict(list) for name, resource in resources.items(): if isinstance(resource, Model): resource = resource.pk if name in params: query[name].append(params[name]) query[name].append(resource) del params[name] continue params[name] = resource name_ver = '' if not str(api) else '%s-' % str(api) ns_prefix = '' if not namespace else '%s:' % namespace uri = django_reverse('%s%s-%s%s' % (ns_prefix, api.prefix, name_ver, url_name), kwargs=params) if query: uri += '?' for name, values in query: uri += '&'.join('%s=%s' % (name, value) for value in values) return uri
def reverse(resource, api=None, namespace=None, **resources): """ Reverse resource by ResourceClass or name string. :param resource: Resource Class or String name. :param api: API intance (if resource is string) :param namespace: Set namespace prefix :param **resources: Uri params :return str: URI string """ if isinstance(resource, basestring): url_name = resource if not api: raise AssertionError("You sould send api parameter") if not api.resources.get(url_name): raise AssertionError("Invalid resource name: %s" % url_name) else: url_name = resource._meta.url_name api = resource.api params = dict() query = defaultdict(list) for name, resource in resources.items(): if isinstance(resource, Model): resource = resource.pk if name in params: query[name].append(params[name]) query[name].append(resource) del params[name] continue params[name] = resource name_ver = '' if not str(api) else '%s-' % str(api) ns_prefix = '' if not namespace else '%s:' % namespace uri = django_reverse( '%s%s-%s%s' % (ns_prefix, api.prefix, name_ver, url_name), kwargs=params) if query: uri += '?' for name, values in query: uri += '&'.join('%s=%s' % (name, value) for value in values) return uri
def home(request): if request.user.is_authenticated(): profile = request.user.profile delta = datetime.datetime.now() - profile.user.date_joined response = jingo.render(request, 'desktop/dashboard.html', {'username': profile.user.username, 'profile': profile, 'logged_in': True, 'levels': profile.challenge_info, 'date_joined_delta': _total_seconds(delta), 'countries': json.dumps(countries[request.locale]), 'sparked_countries': json.dumps(profile.sparked_countries), 'twitter_url': urlquote(profile.twitter_sharing_url), 'twitter_msg': urlquote(unicode(TWITTER_SPARK_MSG)), 'facebook_url': profile.facebook_sharing_url, 'facebook_redirect': absolute_url(django_reverse('desktop.close_popup')), 'facebook_title': urlquote(unicode(FACEBOOK_SPARK_TITLE)), 'facebook_spark_msg': urlquote(unicode(FACEBOOK_SPARK_MSG)), 'abs_url': profile.generic_sharing_url, 'stats': get_global_stats(), 'boost2_status': 1 if profile.boost2_completed else 0, 'open_boost_popup': 'new_user' in request.COOKIES, 'FB_APP_ID': settings.FB_APP_ID}) response.delete_cookie('new_user') return response else: data = {'is_homepage': True, 'twitter_url': urlquote(absolute_url(django_reverse('desktop.home'))), 'twitter_msg': urlquote(unicode(TWITTER_SHARE_MSG)), 'facebook_url': absolute_url(django_reverse('desktop.home')), 'facebook_redirect': absolute_url(django_reverse('desktop.close_popup')), 'facebook_msg': urlquote(unicode(FACEBOOK_SHARE_MSG)), 'facebook_title': urlquote(unicode(FACEBOOK_SPARK_TITLE)), 'stats': get_global_stats(), 'FB_APP_ID': settings.FB_APP_ID} return jingo.render(request, 'desktop/home.html', data)
def _make_mail(locale, user, watches): if (is_ready and ReadyRevisionEvent.event_type in (w.event_type for w in watches)): c = context_dict(revision, ready_for_l10n=True) # TODO: Expose all watches c['watch'] = watches[0] c['url'] = django_reverse('wiki.select_locale', args=[document.slug]) subject = _(u'{title} has a revision ready for ' 'localization') text_template = 'wiki/email/ready_for_l10n.ltxt' html_template = None else: c = context_dict(revision, revision_approved=True) approved_url = reverse('wiki.document', locale=document.locale, args=[document.slug]) c['url'] = approved_url # TODO: Expose all watches. c['watch'] = watches[0] c['reviewer'] = revision.reviewer.username subject = _(u'{title} ({locale}) has a new approved ' 'revision ({reviewer})') text_template = 'wiki/email/approved.ltxt' html_template = None subject = subject.format( title=document.title, reviewer=revision.reviewer.username, locale=document.locale) msg = EmailMultiAlternatives( subject, email_utils.render_email(text_template, c), settings.TIDINGS_FROM_ADDRESS, [user.email]) if html_template: msg.attach_alternative( email_utils.render_email(html_template, c), 'text/html') return msg
def _make_mail(locale, user, watches): if (is_ready and ReadyRevisionEvent.event_type in (w.event_type for w in watches)): c = context_dict(revision, ready_for_l10n=True) # TODO: Expose all watches c['watch'] = watches[0] url = django_reverse( 'wiki.select_locale', args=[document.slug]) c['l10n_url'] = add_utm(url, 'wiki-ready-l10n') subject = _(u'{title} has a revision ready for ' 'localization') text_template = 'wiki/email/ready_for_l10n.ltxt' html_template = 'wiki/email/ready_for_l10n.html' else: c = context_dict(revision, revision_approved=True) approved_url = reverse('wiki.document', locale=document.locale, args=[document.slug]) c['document_url'] = add_utm(approved_url, 'wiki-approved') # TODO: Expose all watches. c['watch'] = watches[0] c['reviewer'] = revision.reviewer subject = _(u'{title} ({locale}) has a new approved ' 'revision ({reviewer})') text_template = 'wiki/email/approved.ltxt' html_template = 'wiki/email/approved.html' subject = subject.format( title=document.title, reviewer=revision.reviewer.username, locale=document.locale) mail = email_utils.make_mail( subject=subject, text_template=text_template, html_template=html_template, context_vars=c, from_email=settings.TIDINGS_FROM_ADDRESS, to_email=user.email) return mail
def url(name, *args, **kwargs): """ Shortcut filter for reverse url on templates. Is a alternative to django {% url %} tag, but more simple. Usage example: {{ url('web:timeline', userid=2) }} This is a equivalent to django: {% url 'web:timeline' userid=2 %} """ try: return django_reverse(name, args=args, kwargs=kwargs) except NoReverseMatch as exc: logging.error('Error: %s', exc.message) return ''