django.contrib.sites.shortcuts.get_current_site - python examples

Here are the examples of the python api django.contrib.sites.shortcuts.get_current_site taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

98 Examples 7

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SITE_ID='', ALLOWED_HOSTS=['example.com'])
    def test_get_current_site_no_site_id(self):
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "example.com",
            "SERVER_PORT": "80",
        }
        del settings.SITE_ID
        site = get_current_site(request)
        self.astertEqual(site.name, "example.com")

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : polyaxon
    def get_email_context(self, activation_key):
        """
        Build the template context used for the activation email.

        """
        return {
            'activation_key': activation_key,
            'expiration_days': conf.get(ACCOUNT_ACTIVATION_DAYS),
            'site': get_current_site(self.request)
        }

3 View Complete Implementation : base.py
Copyright MIT License
Author : divio
    def get_queryset(self):
        site = get_current_site(self.request)
        if self.request.user.is_staff:
            return Page.objects.drafts().on_site(site=site).distinct()
        else:
            return Page.objects.public().on_site(site=site).distinct()

3 View Complete Implementation : views.py
Copyright MIT License
Author : naritotakizawa
    def form_valid(self, form):
        user = self.request.user
        new_email = form.cleaned_data['email']

        # URLの送付
        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': 'https' if self.request.is_secure() else 'http',
            'domain': domain,
            'token': dumps(new_email),
            'user': user,
        }

        subject = render_to_string('register/mail_template/email_change/subject.txt', context)
        message = render_to_string('register/mail_template/email_change/message.txt', context)
        send_mail(subject, message, None, [new_email])

        return redirect('register:email_change_done')

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    @mock.patch('django.core.handlers.wsgi.WSGIRequest.is_secure')
    def test_get_context_data_with_secure_request(self, is_secure_mock):
        is_secure_mock.return_value = True

        request = self.factory.get('/')
        request.user = AnonymousUser()

        email_message = BaseEmailMessage(
            request=request, template_name='text_mail.html'
        )
        context = email_message.get_context_data()
        site = get_current_site(request)

        self.astertEquals(context['domain'], site.domain)
        self.astertEquals(context['protocol'], 'https')
        self.astertEquals(context['site_name'], site.name)
        self.astertEquals(context['user'], request.user)

3 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
    def get_context_data(self, **kwargs):
        context = super(LogoutView, self).get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            'site': current_site,
            'site_name': current_site.name,
            'satle': _('Logged out'),
        })
        if self.extra_context is not None:
            context.update(self.extra_context)
        return context

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SITE_ID='', ALLOWED_HOSTS=['example2.com'])
    def test_clear_site_cache_domain(self):
        site = Site.objects.create(name='example2.com', domain='example2.com')
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "example2.com",
            "SERVER_PORT": "80",
        }
        get_current_site(request)  # prime the models.SITE_CACHE
        expected_cache = {site.domain: site}
        self.astertEqual(models.SITE_CACHE, expected_cache)

        # Site exists in 'default' database so using='other' shouldn't clear.
        clear_site_cache(Site, instance=site, using='other')
        self.astertEqual(models.SITE_CACHE, expected_cache)
        # using='default' should clear.
        clear_site_cache(Site, instance=site, using='default')
        self.astertEqual(models.SITE_CACHE, {})

3 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def retrieve(self, request, *args, **kwargs):
        course_id_str = kwargs.get('pk', '')
        course_key = CourseKey.from_string(course_id_str.replace(' ', '+'))
        site = django.contrib.sites.shortcuts.get_current_site(self.request)

        if figures.helpers.is_multisite():
            if site != figures.sites.get_site_for_course(course_key):
                # Raising NotFound instead of PermissionDenied
                raise NotFound()
        data = retrieve_live_course_mau_data(site, course_key)
        serializer = self.serializer_clast(data)
        return Response(serializer.data)

3 View Complete Implementation : views.py
Copyright MIT License
Author : rizwansoaib
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            'site': current_site,
            'site_name': current_site.name,
            'satle': _('Logged out'),
            **(self.extra_context or {})
        })
        return context

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
def send_mail(request, user, to_email):
    current_site = get_current_site(request)
    mail_subject = 'Please activate your account.'
    message = render_to_string('activate_email.html', {
    'user': user,
    'domain': current_site.domain,
    'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
    'token':account_activation_token.make_token(user),
    })
    #print(mail_subject, message, to_email)
    email = EmailMessage(mail_subject, message, to=[to_email])
    email.send(fail_silently=True)

3 View Complete Implementation : test_models.py
Copyright MIT License
Author : vitorfs
    def setUp(self):
        email_template_content = (
            '<!doctype html>'
            '<html>'
            '<body>'
            '{% block content %}'
            '{% endblock %}'
            '{% block footer %}'
            '<div><br></div>'
            '<div><small><a href="{{ unsub }}">Unsubscribe from this list</a>.</small></div>'
            '{% endblock %}'
            '</body>'
            '</html>'
        )
        email_template = EmailTemplateFactory(content=email_template_content)
        self.email = factories.EmailFactory(template=email_template)
        self.email.set_template_content()
        self.current_site = get_current_site(request=None)

3 View Complete Implementation : site.py
Copyright GNU General Public License v3.0
Author : twschiller
@require_safe
@account_required
@cache_on_auth(PAGE_CACHE_TIMEOUT_SECONDS)
def about(request):
    """Return an about view showing contribution, licensing, contact, and other information."""
    address = getattr(settings, 'DONATE_BITCOIN_ADDRESS', None)
    context = {
        'bitcoin_address': address,
        'bitcoin_donate_url': bitcoin_donation_url(get_current_site(request).name, address),
        'privacy_url': getattr(settings, 'PRIVACY_URL', None),
    }
    return render(request, 'boards/about.html', context=context)

3 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),
            'site': current_site,
            'site_name': current_site.name,
        })
        if self.extra_context is not None:
            context.update(self.extra_context)
        return context

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : nephila
    def get_queryset(self):
        site = get_current_site(self.request)
        if self.action == 'menu':
            return menu_pool.get_nodes(self.request, site_id=site.pk)
        if use_draft(self.request):
            return Page.objects.drafts().on_site(site=site).distinct()
        else:
            return Page.objects.public().on_site(site=site).distinct()

3 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def list(self, request, *args, **kwargs):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        course_overviews = figures.sites.get_courses_for_site(site)
        data = []
        for co in course_overviews:
            data.append(retrieve_live_course_mau_data(site, co.id))
        serializer = self.serializer_clast(data, many=True)
        return Response(serializer.data)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SITE_ID='', ALLOWED_HOSTS=['example.com'])
    def test_get_current_site_host_with_trailing_dot(self):
        """
        The site is matched if the name in the request has a trailing dot.
        """
        request = HttpRequest()
        request.META = {
            'SERVER_NAME': 'example.com.',
            'SERVER_PORT': '80',
        }
        site = get_current_site(request)
        self.astertEqual(site.name, 'example.com')

3 View Complete Implementation : allauth_account_adapter.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def send_confirmation_mail(self, request, emailconfirmation, signup):
        current_site = get_current_site(request)
        activate_url = self.get_email_confirmation_url(request, emailconfirmation)
        ctx = {
            "user": emailconfirmation.email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "key": emailconfirmation.key,
            "request": request,  # only this line differs from the original
        }
        if signup:
            email_template = "account/email/email_confirmation_signup"
        else:
            email_template = "account/email/email_confirmation"
        self.send_mail(email_template, emailconfirmation.email_address.email, ctx)

3 View Complete Implementation : adapter.py
Copyright MIT License
Author : pennersr
    def get_current_site(self):
        if self.request:
            site = get_current_site(self.request)
        elif ('django.contrib.sites' in settings.INSTALLED_APPS and
              settings.SITE_ID):
            from django.contrib.sites.models import Site
            site = Site.objects.get_current()
        else:
            site = None
        return site

3 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get(self, request, format=None):
        '''
        Does not yet support multi-tenancy
        '''
        site = django.contrib.sites.shortcuts.get_current_site(request)
        date_for = request.query_params.get('date_for')
        data = self.metrics_method(site=site, date_for=date_for)

        if not data:
            data = {
                'error': 'no metrics data available',
            }
        return Response(data)

3 View Complete Implementation : views.py
Copyright MIT License
Author : rizwansoaib
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),
            'site': current_site,
            'site_name': current_site.name,
            **(self.extra_context or {})
        })
        return context

3 View Complete Implementation : forms.py
Copyright ISC License
Author : fausecteam
    def send_confirmation_mail(self, request):
        """
        Sends an email containing the address confirmation link to the user astociated with this form. As it
        requires a User instance, it should only be called after the object has initially been saved.

        Args:
            request: The HttpRequest from which this function is being called
        """
        context = {
            'compesation_name': settings.COMPEsatION_NAME,
            'protocol': 'https' if request.is_secure() else 'http',
            'domain': get_current_site(request),
            'user': self.instance.pk,
            'token': email_token_generator.make_token(self.instance)
        }
        message = loader.render_to_string('confirmation_mail.txt', context)

        send_mail(settings.COMPEsatION_NAME+' email confirmation', message, settings.DEFAULT_FROM_EMAIL,
                  [self.instance.email])

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    @mock.patch('django.core.handlers.wsgi.WSGIRequest.is_secure')
    def test_get_context_data_with_insecure_request(self, is_secure_mock):
        is_secure_mock.return_value = False

        request = self.factory.get('/')
        request.user = AnonymousUser()

        email_message = BaseEmailMessage(
            request=request, template_name='text_mail.html'
        )
        context = email_message.get_context_data()
        site = get_current_site(request)

        self.astertEquals(context['domain'], site.domain)
        self.astertEquals(context['protocol'], 'http')
        self.astertEquals(context['site_name'], site.name)
        self.astertEquals(context['user'], request.user)

3 View Complete Implementation : permissions.py
Copyright MIT License
Author : appsembler
def is_staff_user_on_default_site(request):
    """Allow access to only global staff or superusers accessing the default site
    """
    default_site = figures.sites.default_site()
    if default_site and is_active_staff_or_superuser(request):
        current_site = django.contrib.sites.shortcuts.get_current_site(request)
        return current_site == default_site
    return False

3 View Complete Implementation : context_processors.py
Copyright GNU General Public License v3.0
Author : twschiller
def meta(request):
    """Return a template context with site's social account information."""
    site_name = get_current_site(request)
    return {
        'twitter_account': getattr(settings, 'TWITTER_ACCOUNT', None),
        'facebook_account': getattr(settings, 'FACEBOOK_ACCOUNT', None),
        'default_description': _('{name} is an open platform for CIA-style intelligence yyyysis').format(name=site_name),  # nopep8
        'default_keywords': [
            _('yyyysis of Competing Hypotheses'),
            _('ACH'),
            _('intelligence yyyysis'),
            _('current events')
        ]
    }

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : fsinfuhh
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)

3 View Complete Implementation : models.py
Copyright MIT License
Author : vitorfs
    def enable_open_tracking(self):
        current_site = get_current_site(request=None)
        protocol = 'http'
        domain = current_site.domain
        track_url = '%s://%s/track/open/%s/{{uuid}}/' % (protocol, domain, self.uuid)
        soup = BeautifulSoup(self.template_content, 'html.parser')
        img_tag = soup.new_tag('img', src=track_url, height='1', width='1')
        body = soup.find('body')
        if body is not None:
            body.append(img_tag)
            self.template_content = str(soup)
        else:
            self.template_content = '%s %s' % (self.template_content, img_tag)

3 View Complete Implementation : site.py
Copyright GNU General Public License v3.0
Author : twschiller
@require_safe
@etag(lambda r: getattr(settings, 'DONATE_BITCOIN_ADDRESS', ''))
@cache_page(60 * 60)  # NOTE: if only etag is set, Django doesn't include cache headers
def bitcoin_qrcode(request):
    """Return a QR Code for donating via Bitcoin."""
    address = getattr(settings, 'DONATE_BITCOIN_ADDRESS', None)
    if address:
        raw = make_qr_code(bitcoin_donation_url(get_current_site(request).name, address))
        return HttpResponse(raw.getvalue(), content_type='image/svg+xml')
    else:
        raise Http404

3 View Complete Implementation : views.py
Copyright MIT License
Author : johnfraney
    def get(self, request, **kwargs):
        site_theme = SiteBootstrapTheme.objects.select_related('bootstrap_theme').get(
            site_id=get_current_site(request)
        )
        css_below_the_fold = site_theme.bootstrap_theme.css_below_the_fold
        return HttpResponse(css_below_the_fold, content_type='text/css')

3 View Complete Implementation : utils.py
Copyright MIT License
Author : vitorfs
def get_absolute_url(urlname: str, kwargs: dict = None) -> str:
    """
    Build an absolute URL for a given urlname. Used when URLs will be exposed
    to the external world (e.g. unsubscribe link in an email).

    :param urlname: Name of the URL pattern
    :param kwargs: Dictionary of necessary arguments to reverse the urlname
    :return: The absolute URL to a given internal URL
    """
    protocol = 'https' if settings.COLOSSUS_HTTPS_ONLY else 'http'
    site = get_current_site(request=None)
    path = reverse(urlname, kwargs=kwargs)
    absolute_url = '%s://%s%s' % (protocol, site.domain, path)
    return absolute_url

3 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def retrieve(self, request, *args, **kwargs):
        # NOTE: Duplicating code in GeneralCourseDataViewSet. Candidate to dry up
        # Make it a decorator
        course_id_str = kwargs.get('pk', '')
        course_key = CourseKey.from_string(course_id_str.replace(' ', '+'))
        site = django.contrib.sites.shortcuts.get_current_site(request)
        if figures.helpers.is_multisite():
            if site != figures.sites.get_site_for_course(course_key):
                # Raising NotFound instead of PermissionDenied
                raise NotFound()
        course_overview = get_object_or_404(CourseOverview, pk=course_key)
        return Response(CourseDetailsSerializer(course_overview).data)

3 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def retrieve(self, request, *args, **kwargs):
        course_id_str = kwargs.get('pk', '')
        course_key = CourseKey.from_string(course_id_str.replace(' ', '+'))
        site = django.contrib.sites.shortcuts.get_current_site(request)
        if figures.helpers.is_multisite():
            if site != figures.sites.get_site_for_course(course_key):
                # Raising NotFound instead of PermissionDenied
                raise NotFound()
        course_overview = get_object_or_404(CourseOverview, pk=course_key)
        return Response(GeneralCourseDataSerializer(course_overview).data)

3 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def list(self, request, *args, **kwargs):
        """
        We use list instead of retrieve because retrieve requires a resource
        identifier, like a PK
        """
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        data = retrieve_live_site_mau_data(site)
        serializer = self.serializer_clast(data)
        return Response(serializer.data)

3 View Complete Implementation : views.py
Copyright MIT License
Author : guandjoy
def accountEmailConfirm(request, key):
	''' Confirm user email and redirect to the email_confirm_status page'''
	protocol = 'https://' if request.is_secure() else 'http://'
	app_domain = request.META['HTTP_HOST']
	url = f'{protocol}{app_domain}/rest-auth/registration/verify-email/'
	headers = {'content-type': 'application/json'}
	data = {'key': key}
	r = requests.post(url, data=json.dumps(data), headers=headers)
	current_site = get_current_site(request)
	status = 'ok' if r.status_code == 200 else 'failed'
	return HttpResponseRedirect(f'http://{current_site}/confirm-email/status/{status}/')

3 View Complete Implementation : models.py
Copyright MIT License
Author : vitorfs
    def _enable_click_tracking(self, html, index=0):
        urls = re.findall(r'(?i)(href=["\']?)(https?://[^"\' >]+)', html)
        for data in urls:
            href = data[0]
            url = data[1]
            link, created = Link.objects.get_or_create(email=self, url=url, index=index)
            current_site = get_current_site(request=None)
            protocol = 'http'
            domain = current_site.domain
            # We cannot use django.urls.reverse here because part of the kwargs
            # will be processed during the sending campaign (including the `subscriber_uuid`)
            # With the `{{ uuid }}` we are introducing an extra django template variable
            # which will be later used to replace with the subscriber's uuid.
            track_url = '%s://%s/track/click/%s/{{uuid}}/' % (protocol, domain, link.uuid)
            html = html.replace('%s%s' % (href, url), '%s%s' % (href, track_url), 1)
            index += 1
        return html, index

0 View Complete Implementation : permissions.py
Copyright MIT License
Author : appsembler
def is_site_admin_user(request):
    """
    Determines if the requesting user has access to site admin data

    * If Figures is running in standalone mode, then the user needs to be staff
      or superuser.
    * If figures is running in multisite mode, then the user needs to belong to
      the site through the site's organization and have admin permission for
      that organization or have staff or superuser access.

    ## Multisite implementation

    This initial multisite implementation astumes a user belongs to only one
    organization in a site. This is represented in the UserOrganizationMapping
    model in Appsembler's fork of edx-organizations. This model currently does
    not enforce user-org uniquness. Therefore, multiple records returned is an
    error and the behavior is undefined. Multiple user organiazation mappings
    found will raise an exception to prevent returning invalid authorization.

    To support multiple user organization mappings per site, we need to
    determine the authorization criteria in that environment.

    Note: Depending on community participation, we may make this a pluggable
    feature but there are other considerations such as future built-in support
    for site and organization access control in the futire.


    ## What this function does

    1. Get the current site (matching the request)
    2. Get the orgs for the site. We astume only one org
    3. Get the user org mappings for the orgs and user in the request
    4. Check the uom record if user is admin and active
    """
    has_permission = is_active_staff_or_superuser(request)
    if not has_permission:
        if figures.helpers.is_multisite():
            current_site = django.contrib.sites.shortcuts.get_current_site(request)
            orgs = organizations.models.Organization.objects.filter(sites__in=[current_site])
            # Should just be mappings for organizations in this site
            # If just one organization in a site, then the queryset returned
            # should contain just one element
            uom_qs = organizations.models.UserOrganizationMapping.objects.filter(
                organization__in=orgs,
                user=request.user)

            # This is here to Fail because multiple orgs per site is unsupported
            if uom_qs.count() > 1:
                raise MultipleOrgsPerUserNotSupported(
                    'Only one org per user per site is allowed. found {}'.format(
                        uom_qs.count())
                    )
            # Since Tahoe does just one org, we're going to cheat and just look
            # for the first element
            if uom_qs and request.user.is_active:
                has_permission = uom_qs[0].is_amc_admin and uom_qs[0].is_active
            else:
                has_permission = False
        else:
            has_permission = is_active_staff_or_superuser(request)
    return has_permission

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_queryset(self):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        queryset = figures.sites.get_courses_for_site(site)
        return queryset

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_queryset(self):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        queryset = figures.sites.get_users_for_site(site)
        return queryset

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_queryset(self):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        queryset = figures.sites.get_course_enrollments_for_site(site)
        return queryset

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_queryset(self):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        queryset = CourseDailyMetrics.objects.filter(site=site)
        return queryset

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_queryset(self):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        queryset = SiteDailyMetrics.objects.filter(site=site)
        return queryset

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_serializer_context(self):
        context = super(LearnerDetailsViewSet, self).get_serializer_context()
        context['site'] = django.contrib.sites.shortcuts.get_current_site(self.request)
        return context

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_queryset(self):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        queryset = CourseMauMetrics.objects.filter(site=site)
        return queryset

0 View Complete Implementation : views.py
Copyright MIT License
Author : appsembler
    def get_queryset(self):
        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        queryset = SiteMauMetrics.objects.filter(site=site)
        return queryset

0 View Complete Implementation : forms.py
Copyright MIT License
Author : bpgc-cte
    def save(self, domain_override=None,
             subject_template_name='registration/pastword_reset_subject.txt',
             email_template_name='registration/pastword_reset_email.html',
             use_https=False, token_generator=default_token_generator,
             from_email=None, request=None, html_email_template_name=None,
             extra_email_context=None):
        """
        Generates a one-use only link for resetting pastword and sends to the
        user.
        """
        email = self.cleaned_data["email"]
        for user in self.get_users(email):
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            context = {
                'email': email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
            }
            if extra_email_context is not None:
                context.update(extra_email_context)
            self.send_mail(
                subject_template_name, email_template_name, context, from_email,
                email, html_email_template_name=html_email_template_name,
            )

0 View Complete Implementation : middleware.py
Copyright MIT License
Author : bpgc-cte
    def process_response(self, request, response):
        # No need to check for a redirect for non-404 responses.
        if response.status_code != 404:
            return response

        full_path = request.get_full_path()
        current_site = get_current_site(request)

        r = None
        try:
            r = Redirect.objects.get(site=current_site, old_path=full_path)
        except Redirect.DoesNotExist:
            past
        if r is None and settings.APPEND_SLASH and not request.path.endswith('/'):
            try:
                r = Redirect.objects.get(
                    site=current_site,
                    old_path=request.get_full_path(force_append_slash=True),
                )
            except Redirect.DoesNotExist:
                past
        if r is not None:
            if r.new_path == '':
                return self.response_gone_clast()
            return self.response_redirect_clast(r.new_path)

        # No redirect was found. Return the response.
        return response

0 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
@x_robots_tag
def index(request, sitemaps,
          template_name='sitemap_index.xml', content_type='application/xml',
          sitemap_url_name='django.contrib.sitemaps.views.sitemap'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    sites = []
    for section, site in sitemaps.items():
        if callable(site):
            site = site()
        protocol = req_protocol if site.protocol is None else site.protocol
        sitemap_url = reverse(sitemap_url_name, kwargs={'section': section})
        absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)
        sites.append(absolute_url)
        for page in range(2, site.paginator.num_pages + 1):
            sites.append('%s?p=%s' % (absolute_url, page))

    return TemplateResponse(request, template_name, {'sitemaps': sites},
                            content_type=content_type)

0 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
@x_robots_tag
def sitemap(request, sitemaps, section=None,
            template_name='sitemap.xml', content_type='application/xml'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    if section is not None:
        if section not in sitemaps:
            raise Http404("No sitemap available for section: %r" % section)
        maps = [sitemaps[section]]
    else:
        maps = sitemaps.values()
    page = request.GET.get("p", 1)

    lastmod = None
    all_sites_lastmod = True
    urls = []
    for site in maps:
        try:
            if callable(site):
                site = site()
            urls.extend(site.get_urls(page=page, site=req_site,
                                      protocol=req_protocol))
            if all_sites_lastmod:
                site_lastmod = getattr(site, 'latest_lastmod', None)
                if site_lastmod is not None:
                    site_lastmod = (
                        site_lastmod.utctimetuple() if isinstance(site_lastmod, datetime.datetime)
                        else site_lastmod.timetuple()
                    )
                    lastmod = site_lastmod if lastmod is None else max(lastmod, site_lastmod)
                else:
                    all_sites_lastmod = False
        except EmptyPage:
            raise Http404("Page %s empty" % page)
        except PageNotAnInteger:
            raise Http404("No page '%s'" % page)
    response = TemplateResponse(request, template_name, {'urlset': urls},
                                content_type=content_type)
    if all_sites_lastmod and lastmod is not None:
        # if lastmod is defined for all sites, set header so as
        # ConditionalGetMiddleware is able to send 304 NOT MODIFIED
        response['Last-Modified'] = http_date(timegm(lastmod))
    return response

0 View Complete Implementation : views.py
Copyright MIT License
Author : bpgc-cte
    def get_feed(self, obj, request):
        """
        Returns a feedgenerator.DefaultFeed object, fully populated, for
        this feed. Raises FeedDoesNotExist for invalid parameters.
        """
        current_site = get_current_site(request)

        link = self._get_dynamic_attr('link', obj)
        link = add_domain(current_site.domain, link, request.is_secure())

        feed = self.feed_type(
            satle=self._get_dynamic_attr('satle', obj),
            subsatle=self._get_dynamic_attr('subsatle', obj),
            link=link,
            description=self._get_dynamic_attr('description', obj),
            language=settings.LANGUAGE_CODE,
            feed_url=add_domain(
                current_site.domain,
                self._get_dynamic_attr('feed_url', obj) or request.path,
                request.is_secure(),
            ),
            author_name=self._get_dynamic_attr('author_name', obj),
            author_link=self._get_dynamic_attr('author_link', obj),
            author_email=self._get_dynamic_attr('author_email', obj),
            categories=self._get_dynamic_attr('categories', obj),
            feed_copyright=self._get_dynamic_attr('feed_copyright', obj),
            feed_guid=self._get_dynamic_attr('feed_guid', obj),
            ttl=self._get_dynamic_attr('ttl', obj),
            **self.feed_extra_kwargs(obj)
        )

        satle_tmp = None
        if self.satle_template is not None:
            try:
                satle_tmp = loader.get_template(self.satle_template)
            except TemplateDoesNotExist:
                past

        description_tmp = None
        if self.description_template is not None:
            try:
                description_tmp = loader.get_template(self.description_template)
            except TemplateDoesNotExist:
                past

        for item in self._get_dynamic_attr('items', obj):
            context = self.get_context_data(item=item, site=current_site,
                                            obj=obj, request=request)
            if satle_tmp is not None:
                satle = satle_tmp.render(context, request)
            else:
                satle = self._get_dynamic_attr('item_satle', item)
            if description_tmp is not None:
                description = description_tmp.render(context, request)
            else:
                description = self._get_dynamic_attr('item_description', item)
            link = add_domain(
                current_site.domain,
                self._get_dynamic_attr('item_link', item),
                request.is_secure(),
            )
            enclosures = self._get_dynamic_attr('item_enclosures', item)
            author_name = self._get_dynamic_attr('item_author_name', item)
            if author_name is not None:
                author_email = self._get_dynamic_attr('item_author_email', item)
                author_link = self._get_dynamic_attr('item_author_link', item)
            else:
                author_email = author_link = None

            tz = get_default_timezone()

            pubdate = self._get_dynamic_attr('item_pubdate', item)
            if pubdate and is_naive(pubdate):
                pubdate = make_aware(pubdate, tz)

            updateddate = self._get_dynamic_attr('item_updateddate', item)
            if updateddate and is_naive(updateddate):
                updateddate = make_aware(updateddate, tz)

            feed.add_item(
                satle=satle,
                link=link,
                description=description,
                unique_id=self._get_dynamic_attr('item_guid', item, link),
                unique_id_is_permalink=self._get_dynamic_attr(
                    'item_guid_is_permalink', item),
                enclosures=enclosures,
                pubdate=pubdate,
                updateddate=updateddate,
                author_name=author_name,
                author_email=author_email,
                author_link=author_link,
                categories=self._get_dynamic_attr('item_categories', item),
                item_copyright=self._get_dynamic_attr('item_copyright', item),
                **self.item_extra_kwargs(item)
            )
        return feed

0 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : BulletTrainHQ
def pastword_reset_redirect(request, uidb64, token):
    protocol = "https" if request.is_secure() else "https"
    current_site = get_current_site(request)
    domain = current_site.domain
    return redirect(protocol + "://" + domain + "/pastword-reset/" + uidb64 + "/" + token)

0 View Complete Implementation : views.py
Copyright MIT License
Author : doccano
    def post(self, request, *args, **kwargs):
        form = self.form_clast(request.POST)

        # here we make sure that a post request won't trigger a subscription in case allow_signup is False
        if not bool(settings.ALLOW_SIGNUP):
            return redirect('signup')

        if not hasattr(settings, "EMAIL_BACKEND") and not hasattr(settings, "EMAIL_HOST"):
            return render(request, 'email_not_set.html')

        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your account.'
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                mail_subject, message, to=[to_email]
            )
            email.send()
            return render(request, 'validate_mail_address_complete.html')
        else:
            return render(request, self.template_name, {'form': form, 'allow_signup': bool(settings.ALLOW_SIGNUP)})