Python django.contrib.sites.shortcuts.get_current_site() Examples

The following are 30 code examples of django.contrib.sites.shortcuts.get_current_site(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.sites.shortcuts , or try the search function .
Example #1
Source File: jobs.py    From tramcar with MIT License 7 votes vote down vote up
def jobs_mine(request):
    jobs_list = Job.objects.filter(site_id=get_current_site(request).id) \
                           .filter(user_id=request.user.id) \
                           .order_by('-created_at')
    paginator = Paginator(jobs_list, 25)
    page = request.GET.get('page')
    title = 'My Jobs'
    try:
        jobs = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        jobs = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        jobs = paginator.page(paginator.num_pages)
    context = {'jobs': jobs, 'title': title}
    return render(request, 'job_board/jobs_mine.html', context) 
Example #2
Source File: views.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 = []  # all sections' sitemap URLs
    for section, site in sitemaps.items():
        # For each section label, add links of all pages of its sitemap
        # (usually generated by the `sitemap` view).
        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)
        # Add links to all pages of the sitemap.
        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) 
Example #3
Source File: views.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: flatpages.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 '' 
Example #5
Source File: context_processors.py    From django-torina-blog with MIT License 6 votes vote down vote up
def common(request):
    """どのテンプレートにも渡すデータの作成"""
    site = get_current_site(request)
    mysite, _ = SiteDetail.objects.get_or_create(site=site)
    context = {
        # カテゴリを紐付いた記事数順に取得。category.num_postsで件数が取得可
        'categories': Category.objects.annotate(
            num_posts=Count('post')).order_by('-num_posts'),
        # タグを紐付いた記事数順に取得。tag.num_postsで件数が取得可
        'tags': Tag.objects.annotate(
            num_posts=Count('post')).order_by('-num_posts')[:10],
        # コメントを返信コメント数順に取得。comment.num_recommentsで件数が取得可
        'comments': Comment.objects.select_related('target').annotate(
            num_recomments=Count('recomment')).order_by('-created_at')[:10],

        'links': Link.objects.all(),  # 全てのリンク
        'analytics': Analytics.objects.all(),  # アナリティクス
        'ads': Ads.objects.all(),  # 全ての広告
        'global_form': PostSerachForm(request.GET),  # 上部の検索フォーム
        'mysite': mysite,  # サイト詳細情報
        'popular_post_list': PopularPost.objects.order_by('-page_view'),  # 人気記事
    }
    return context 
Example #6
Source File: views.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 = urlresolvers.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) 
Example #7
Source File: views.py    From bioforum with MIT License 6 votes vote down vote up
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 = []  # all sections' sitemap URLs
    for section, site in sitemaps.items():
        # For each section label, add links of all pages of its sitemap
        # (usually generated by the `sitemap` view).
        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)
        # Add links to all pages of the sitemap.
        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) 
Example #8
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def team_listing(request):
    """Return a listing of teams visible to the user."""
    team_list = Team.objects.user_visible(request.user).order_by(Lower('name'))
    desc = _('List of teams on {name} and summary information').format(name=get_current_site(request).name)  # nopep8

    user_teams = set()
    user_invites = set()
    user_pending = set()
    user_owns = set()

    if request.user.is_authenticated:
        user_invites = set(TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False).values_list('team', flat=True))
        user_pending = set(TeamRequest.objects.filter(invitee=request.user, inviter__isnull=True).values_list('team', flat=True))
        user_teams = set(request.user.team_set.values_list('id', flat=True))
        user_owns = set(Team.objects.filter(owner=request.user).values_list('id', flat=True))

    return render(request, 'teams/teams.html', {
        'teams': make_paginator(request, team_list),
        'meta_description': desc,
        'user_teams': user_teams,
        'user_invites': user_invites,
        'user_pending': user_pending,
        'user_owns': user_owns,
    }) 
Example #9
Source File: views.py    From AutoGrader with MIT License 6 votes vote down vote up
def resend_signup_email(request):
    user = request.user

    current_site = get_current_site(request)
    subject = 'Activate Your FAST AutoGrader Account'
    message = render_to_string('account/account_activation_email.html', {
        'user': user,
        'domain': current_site.domain,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'token': account_activation_token.make_token(user),
    })

    user.email_user(subject, message)
    messages.success(request, 'Verification email sent, check your email account.')

    return HttpResponseRedirect(request.META.get('HTTP_REFERER')) 
Example #10
Source File: flatpages.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 '' 
Example #11
Source File: views.py    From django-register-sample with MIT License 6 votes vote down vote up
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') 
Example #12
Source File: views.py    From bioforum with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: views.py    From django-register-sample with MIT License 6 votes vote down vote up
def form_valid(self, form):
        """仮登録と本登録用メールの発行."""
        # 仮登録と本登録の切り替えは、is_active属性を使うと簡単です。
        # 退会処理も、is_activeをFalseにするだけにしておくと捗ります。
        user = form.save(commit=False)
        user.is_active = False
        user.save()

        # アクティベーション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(user.pk),
            'user': user,
        }

        subject = render_to_string('register/mail_template/create/subject.txt', context)
        message = render_to_string('register/mail_template/create/message.txt', context)

        user.email_user(subject, message)
        return redirect('register:user_create_done') 
Example #14
Source File: flatpages.py    From bioforum with MIT License 6 votes vote down vote up
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 '' 
Example #15
Source File: api.py    From volontulo with MIT License 6 votes vote down vote up
def password_reset(request):
    """REST API reset password view"""
    serializer = UsernameSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    username = serializer.validated_data.get('username')
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        pass
    else:
        context = {
            'email': username,
            'domain': get_current_site(request).domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'user': user,
            'token': default_token_generator.make_token(user),
            'protocol': 'https' if request.is_secure() else 'http',
        }
        send_mail(
            request,
            'password_reset',
            [username],
            context=context,
            send_copy_to_admin=False)
    return Response(dict(), status=status.HTTP_201_CREATED) 
Example #16
Source File: views.py    From rdmo with Apache License 2.0 6 votes vote down vote up
def form_valid(self, form):
        # add current site
        form.instance.site = get_current_site(self.request)

        # save the project
        response = super(ProjectCreateView, self).form_valid(form)

        # add all tasks to project
        tasks = Task.objects.filter_current_site().filter_group(self.request.user)
        for task in tasks:
            form.instance.tasks.add(task)

        # add all views to project
        views = View.objects.filter_current_site().filter_catalog(self.object.catalog).filter_group(self.request.user)
        for view in views:
            form.instance.views.add(view)

        # add current user as owner
        membership = Membership(project=form.instance, user=self.request.user, role='owner')
        membership.save()

        return response 
Example #17
Source File: jobs.py    From tramcar with MIT License 6 votes vote down vote up
def jobs_search(request):
    form = SearchForm(request.GET)
    if form.is_valid():
        cd = form.cleaned_data
        jobs = Job.objects.filter(site_id=get_current_site(request).id) \
                          .filter(paid_at__isnull=False) \
                          .filter(expired_at__isnull=True) \
                          .filter(
                              Q(title__icontains=cd['query']) |
                              Q(description__icontains=cd['query'])
                          ).order_by('-paid_at')

        meta_desc = 'Search Results'
        title = 'Search Results'
        context = {'meta_desc': meta_desc,
                   'title': title,
                   'form': form,
                   'jobs': jobs}

        return render(request, 'job_board/jobs_index.html', context) 
Example #18
Source File: categories.py    From tramcar with MIT License 6 votes vote down vote up
def categories_show(request, category_id, slug=None):
    category = get_object_or_404(
                   Category,
                   pk=category_id,
                   site_id=get_current_site(request).id
    )

    if slug is None:
        return HttpResponsePermanentRedirect(category.get_absolute_url())

    jobs = Job.objects.filter(site_id=get_current_site(request).id) \
                      .filter(category_id=category_id) \
                      .filter(paid_at__isnull=False) \
                      .filter(expired_at__isnull=True) \
                      .order_by('-paid_at')
    form = SubscribeForm()
    meta_desc = 'Browse a list of all active %s jobs' % category.name
    feed_url = reverse('categories_feed', args=(category.id, category.slug(),))
    title = '%s Jobs' % category.name
    context = {'meta_desc': meta_desc,
               'link_rss': feed_url,
               'title': title,
               'form': form,
               'jobs': jobs}
    return render(request, 'job_board/jobs_index.html', context) 
Example #19
Source File: domain.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def domain(context, url=''):
    if 'request' in context:
        protocol = 'https' if context['request'].is_secure() else 'http'
        _domain = get_current_site(context['request']).domain
    elif 'protocol' in context and 'domain' in context:
        # Django emails
        protocol, _domain = context['protocol'], context['domain']
    elif 'site' in context:
        # Postman emails
        _domain = context['site'].domain
        protocol = 'https' if 'pasportaservo.org' in _domain else 'http'
    else:
        # Fallback
        if settings.DEBUG:
            protocol, _domain = 'http', 'localhost:8000'
        else:
            protocol, _domain = 'https', settings.ALLOWED_HOSTS[0]

    link = '{}://{}{}'.format(protocol, _domain, url)
    return link 
Example #20
Source File: test_reset_username.py    From djoser with MIT License 5 votes vote down vote up
def test_post_should_send_email_to_custom_user_with_username_reset_link(
        self
    ):  # noqa
        user = create_user(use_custom_data=True)
        data = {"custom_email": get_user_email(user)}

        response = self.client.post(self.base_url, data)
        request = response.wsgi_request

        self.assert_status_equal(response, status.HTTP_204_NO_CONTENT)
        self.assert_emails_in_mailbox(1)
        self.assert_email_exists(to=[get_user_email(user)])
        site = get_current_site(request)
        self.assertIn(site.domain, mail.outbox[0].body)
        self.assertIn(site.name, mail.outbox[0].body) 
Example #21
Source File: context_processors.py    From wagtail-cookiecutter-foundation with MIT License 5 votes vote down vote up
def site_url(request):
    scheme = 'https' if request.is_secure() else 'http'
    site = get_current_site(request)

    return {
        'site_url': "{}://{}".format(scheme, site.domain),
        'site_name': site.name
    } 
Example #22
Source File: tests.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_request_and_django_site(self, url):
        request = RequestFactory().get(url)
        request.META['HTTP_HOST'] = self.site.hostname
        request.META['SERVER_PORT'] = self.site.port
        return request, get_current_site(request) 
Example #23
Source File: viewsets.py    From rdmo with Apache License 2.0 5 votes vote down vote up
def perform_create(self, serializer):
        project = serializer.save(site=get_current_site(self.request))

        # add current user as owner
        membership = Membership(project=project, user=self.request.user, role='owner')
        membership.save() 
Example #24
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #25
Source File: utils.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_site_url(relative_path: str = '') -> str:
    """
    Uses the site framework to build an absolute URL.

    This function can be used to build an absolute URL for the site without
    needing access to the request object.
    """
    domain = get_current_site(request=None).domain
    if settings.DEBUG or 'localhost' in domain:
        scheme = "http"
    else:
        scheme = "https"
    return f"{scheme}://{domain}{relative_path}" 
Example #26
Source File: context_processors.py    From codesy with GNU Affero General Public License v3.0 5 votes vote down vote up
def current_site(request):
    return {'current_site': get_current_site(request)} 
Example #27
Source File: context_processors.py    From tramcar with MIT License 5 votes vote down vote up
def get_site(request):
    return {'current_site': get_current_site(request)} 
Example #28
Source File: jobs.py    From tramcar with MIT License 5 votes vote down vote up
def jobs_expire(request, job_id):
    job = get_object_or_404(
              Job, pk=job_id, site_id=get_current_site(request).id
          )

    if request.user.id != job.user.id:
        return HttpResponseRedirect(job.get_absolute_url())

    job.expire()
    return HttpResponseRedirect(job.get_absolute_url()) 
Example #29
Source File: boards.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def board_listing(request):
    """Return a paginated board listing view showing all boards and their popularity."""
    board_list = Board.objects.user_readable(request.user).order_by('-pub_date')
    metric_timeout_seconds = 60 * 2
    desc = _('List of intelligence boards on {name} and summary information').format(name=get_current_site(request).name)  # nopep8
    context = {
        'boards': make_paginator(request, board_list),
        'contributors': cache.get_or_set('contributor_count', generate_contributor_count(), metric_timeout_seconds),
        'evaluators': cache.get_or_set('evaluator_count', generate_evaluator_count(), metric_timeout_seconds),
        'meta_description': desc,
    }
    return render(request, 'boards/boards.html', context) 
Example #30
Source File: template_context.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def site(request):
    return {'site': get_current_site(request)}