django.contrib.sites.models.Site.objects.get_current

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

186 Examples 7

Example 1

Project: ella Source File: test_photo.py
    def test_formatted_photo_has_zero_crop_box_if_smaller_than_format(self):
        format = Format.objects.create(
            name='sample',
            max_width=300,
            max_height=300,
            flexible_height=False,
            stretch=False,
            nocrop=False
        )
        format.sites.add(Site.objects.get_current())

        fp = FormatedPhoto(photo=self.photo, format=format)
        fp.generate(False)
        tools.assert_equals((0, 0, 0, 0), (fp.crop_left, fp.crop_top, fp.crop_width, fp.crop_height))

Example 2

Project: lettuce Source File: tests.py
Function: test_site_cache
    def test_site_cache(self):
        # After updating a Site object (e.g. via the admin), we shouldn't return a
        # bogus value from the SITE_CACHE.
        site = Site.objects.get_current()
        self.assertEqual(u"example.com", site.name)
        s2 = Site.objects.get(id=settings.SITE_ID)
        s2.name = "Example site"
        s2.save()
        site = Site.objects.get_current()
        self.assertEqual(u"Example site", site.name)

Example 3

Project: django-userena Source File: models.py
Function: send_activation_email
    def send_activation_email(self):
        """
        Sends a activation email to the user.

        This email is send when the user wants to activate their newly created
        user.

        """
        context = {'user': self.user,
                  'without_usernames': userena_settings.USERENA_WITHOUT_USERNAMES,
                  'protocol': get_protocol(),
                  'activation_days': userena_settings.USERENA_ACTIVATION_DAYS,
                  'activation_key': self.activation_key,
                  'site': Site.objects.get_current()}

        mailer = UserenaConfirmationMail(context=context)
        mailer.generate_mail("activation")
        mailer.send_mail(self.user.email)

Example 4

Project: django-moderation Source File: moderator.py
Function: send
    def send(self, content_object, subject_template, message_template,
             recipient_list, extra_context=None):
        context = {
            'moderated_object': content_object.moderated_object,
            'content_object': content_object,
            'site': Site.objects.get_current(),
            'content_type': content_object.moderated_object.content_type}

        if extra_context:
            context.update(extra_context)

        message = render_to_string(message_template, context)
        subject = render_to_string(subject_template, context)

        backend = self.get_message_backend()
        backend.send(
            subject=subject,
            message=message,
            recipient_list=recipient_list)

Example 5

Project: django-sellmo Source File: links.py
Function: get_context
def _get_context(**context):
    site = Site.objects.get_current()
    context.update({
        'settings': settings_manager,
        'request' : {
            'site' : site,
        },
        'url': 'http://{0}'.format(site.domain),
        'prefix': 'http://{0}'.format(site.domain),
        'STATIC_URL': 'http://{0}{1}'.format(site.domain, settings.STATIC_URL),
        'MEDIA_URL': 'http://{0}{1}'.format(site.domain, settings.MEDIA_URL),
    })

    return context

Example 6

Project: django-profile Source File: context_processors.py
Function: site
def site(request):
    """
    Adds site-related context variables to the context.
    """
    current_site = Site.objects.get_current()

    return {
        'SITE_NAME': current_site.name,
        'SITE_DOMAIN': current_site.domain,
        'SITE_URL': "http://www.%s" % (current_site.domain),
    }

Example 7

Project: aldryn-newsblog Source File: utilities.py
Function: get_valid_languages
def get_valid_languages(namespace, language_code, site_id=None):
    langs = [language_code]
    if site_id is None:
        site_id = getattr(Site.objects.get_current(), 'pk', None)
    current_language = get_language_object(language_code, site_id)
    fallbacks = current_language.get('fallbacks', None)
    if fallbacks:
        langs += list(fallbacks)
    valid_translations = [
        lang_code for lang_code in langs
        if is_valid_namespace_for_language(namespace, lang_code)]
    return valid_translations

Example 8

Project: callisto-core Source File: models.py
Function: render_body
    def render_body(self, context=None):
        """Format the email as HTML."""
        if context is None:
            context = {}
        current_site = Site.objects.get_current()
        context['domain'] = current_site.domain
        return Template(self.body).render(Context(context))

Example 9

Project: hortonworks-sandbox Source File: views.py
Function: test_current_site_in_context_after_login
    def test_current_site_in_context_after_login(self):
        response = self.client.get(reverse('django.contrib.auth.views.login'))
        self.assertEquals(response.status_code, 200)
        site = Site.objects.get_current()
        self.assertEquals(response.context['site'], site)
        self.assertEquals(response.context['site_name'], site.name)
        self.assert_(isinstance(response.context['form'], AuthenticationForm), 
                     'Login form is not an AuthenticationForm')

Example 10

Project: django-forms-builder Source File: models.py
Function: published
    def published(self, for_user=None):
        if for_user is not None and for_user.is_staff:
            return self.all()
        filters = [
            Q(publish_date__lte=now()) | Q(publish_date__isnull=True),
            Q(expiry_date__gte=now()) | Q(expiry_date__isnull=True),
            Q(status=STATUS_PUBLISHED),
        ]
        if settings.USE_SITES:
            filters.append(Q(sites=Site.objects.get_current()))
        return self.filter(*filters)

Example 11

Project: Dinette Source File: daily_updates.py
Function: handle_noargs
    def handle_noargs(self, **options):
        site = Site.objects.get_current()
        subject = "Daily Digest: %s" %( site.name)
        from_address = '%s notifications <admin@%s>' %(site.name, site.domain)
        to_address = User.objects.filter(dinetteuserprofile__is_subscribed_to_digest=True).values_list('email', flat=True)
        
        yesterday = datetime.datetime.now() - datetime.timedelta(1)
        topics = Ftopics.objects.filter(created_on__gt=yesterday)
        replies = Reply.objects.filter(updated_on__gt=yesterday)
        users = DinetteUserProfile.objects.filter(user__date_joined__gt=yesterday)
        active_users = DinetteUserProfile.objects.filter(user__last_login__gt=yesterday)

        if any([topics, replies, users, active_users]):
            variables = {'site': site, 'topics': topics, 'replies': replies, 'users': users, 'active_users': active_users}
            html_message = render_to_string('dinette/email/daily_updates.html', variables)
            send_html_mail(subject, html_message, html_message, from_address, to_address)

Example 12

Project: votainteligente-portal-electoral Source File: candidatorg_views_tests.py
    def test_candidates_ogp(self):
        site = Site.objects.get_current()
        candidate = self.coquimbo.candidates.get(id=1)
        self.assertTrue(candidate.ogp_enabled)
        self.assertIn(candidate.name, candidate.ogp_title())
        self.assertEquals('website', candidate.ogp_type())
        expected_url = "http://%s%s" % (site.domain,
                                        candidate.get_absolute_url())
        self.assertEquals(expected_url, candidate.ogp_url())
        expected_url = "http://%s%s" % (site.domain,
                                        static('img/logo_vi_og.jpg'))
        self.assertEquals(expected_url, candidate.ogp_image())

Example 13

Project: django-invitations Source File: adapters.py
    def format_email_subject(self, subject):
        prefix = app_settings.EMAIL_SUBJECT_PREFIX
        if prefix is None:
            site = Site.objects.get_current()
            prefix = "[{name}] ".format(name=site.name)
        return prefix + force_text(subject)

Example 14

Project: edx-platform Source File: testutil.py
    def configure_saml_provider(self, **kwargs):
        """ Update the settings for a SAML-based third party auth provider """
        self.assertTrue(
            SAMLConfiguration.is_enabled(Site.objects.get_current()),
            "SAML Provider Configuration only works if SAML is enabled."
        )
        obj = SAMLProviderConfig(**kwargs)
        obj.save()
        return obj

Example 15

Project: django-cms-redirects Source File: tests.py
    def setUp(self):
        settings.APPEND_SLASH = False

        self.site = Site.objects.get_current()

        page = Page()
        page.site = self.site
        page.save()
        page.publish()
        self.page = page

        title = Title(title="Hello world!")
        title.page = page
        title.language = u'en'
        title.save()

Example 16

Project: django-kong Source File: utils.py
def _send_recovery(kong_site, test, content):
    real_site = Site.objects.get_current()
    message = render_to_string(
        'kong/recovered_email.txt', {
            'kong_site': kong_site,
            'test': test,
            'content': content,
            'real_site': real_site
        }
    )
    if getattr(settings, 'KONG_MAIL_MANAGERS', False):
        mail_managers('Kong Test Recovered: %s (%s)' % (test, kong_site), message)
    if getattr(settings, 'KONG_MAIL_ADMINS', False):
        mail_admins('Kong Test Recovered: %s (%s)' % (test, kong_site), message)

Example 17

Project: django-herald Source File: base.py
Function: get_context_data
    def get_context_data(self):
        """
        :return: the context data for rendering the email or text template
        """

        context = self.context or {}

        if settings.DEBUG:
            context['base_url'] = ''
        else:
            site = Site.objects.get_current()
            context['base_url'] = 'http://' + site.domain

        return context

Example 18

Project: django-socialregistration Source File: auth.py
Function: authenticate
    def authenticate(self, github = None):
        try:
            return GithubProfile.objects.get(
                github = github,
                site = Site.objects.get_current()).user
        except GithubProfile.DoesNotExist:
            return None

Example 19

Project: GAE-Bulk-Mailer Source File: tests.py
    def test_site_manager(self):
        # Make sure that get_current() does not return a deleted Site object.
        s = Site.objects.get_current()
        self.assertTrue(isinstance(s, Site))
        s.delete()
        self.assertRaises(ObjectDoesNotExist, Site.objects.get_current)

Example 20

Project: django-secure-auth Source File: models.py
    @classmethod
    def send_link(cls, request, user):
        data = {
            'ip': get_ip(request),
            'user_agent': md5(request.META.get('HTTP_USER_AGENT')),
        }
        link = 'http://%s%s?data=%s' % (
            Site.objects.get_current(),
            reverse('auth_login'),
            Sign().sign(data)
        )
        send_mail(
            [user.email], _('Link for unlock access'), link
        )

Example 21

Project: django-localeurl Source File: tests.py
Function: set_up
    def setUp(self):
        super(SitemapTestCase, self).setUp()
        class DummySite(object):
            domain = 'www.example.com'
        from django.contrib.sites.models import Site
        self._orig_get_current = Site.objects.get_current
        Site.objects.get_current = lambda: DummySite()

Example 22

Project: colab Source File: models.py
Function: as_tweet
    def as_tweet(self):
        if not self.tweet_text:
            current_site = Site.objects.get_current()
            api_url = "http://api.tr.im/api/trim_url.json"
            u = urllib2.urlopen("%s?url=http://%s%s" % (
                api_url,
                current_site.domain,
                self.get_absolute_url(),
            ))
            result = json.loads(u.read())
            self.tweet_text = u"%s %s — %s" % (
                settings.TWITTER_TWEET_PREFIX,
                self.title,
                result["url"],
            )
        return self.tweet_text

Example 23

Project: kikola Source File: tests.py
    def test_index_sitemap(self):
        site = Site.objects.get_current()
        site.name = TEST_SITE_NAME
        site.domain = TEST_SITE_DOMAIN
        site.save()

        url = reverse('index_sitemap')
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/xml')
        self.assertContains(response,
                            '<url><loc>http://%s/</loc><changefreq>daily' \
                            '</changefreq><priority>1.0</priority></url>' % \
                            TEST_SITE_DOMAIN)

Example 24

Project: django-calendartools Source File: context_processors.py
Function: current_site
def current_site(request):
    '''
    A context processor to add the "current site" to the current Context
    '''
    try:
        current_site = Site.objects.get_current()
        return {'current_site': current_site}
    except Site.DoesNotExist:
        return {'current_site':''}

Example 25

Project: brigitte Source File: models.py
    @property
    def ro_url(self):
        if self.repo_type == 'git':
            return 'git://%s/%s' % (Site.objects.get_current(), self.short_path)

        return None

Example 26

Project: django-relationships Source File: tests.py
Function: set_up
    def setUp(self):
        self.walrus = User.objects.get(username='The_Walrus')  # pk 1
        self.john = User.objects.get(username='John')  # pk 2
        self.paul = User.objects.get(username='Paul')  # pk 3
        self.yoko = User.objects.get(username='Yoko')  # pk 4

        self.following = RelationshipStatus.objects.get(from_slug='following')
        self.blocking = RelationshipStatus.objects.get(from_slug='blocking')

        self.site_id = settings.SITE_ID
        settings.SITE_ID = 1

        self.site = Site.objects.get_current()

Example 27

Project: write-it Source File: incoming_mail_tests.py
Function: set_up
    def setUp(self):
        super(EmailReadingExamplesTestCase, self).setUp()
        self.message = Message.objects.get(id=1)
        self.contact = Contact.objects.get(value="[email protected]")
        self.outbound_message = OutboundMessage.objects.create(message=self.message, contact=self.contact, site=Site.objects.get_current())
        self.outbound_message.send()
        identifier = OutboundMessageIdentifier.objects.get(outbound_message=self.outbound_message)
        identifier.key = "7e460e9c462411e38ef81231400178dd"
        identifier.save()
        self.handler = EmailHandler()

Example 28

Project: django-counter Source File: counter_tags.py
Function: counter
def counter(object):
    ctype = ContentType.objects.get_for_model(object)
    return {
        'ctype': ctype,
        'object': object,
        'site': Site.objects.get_current()}

Example 29

Project: djangocms-link Source File: cms_plugins.py
Function: get_form
    def get_form(self, request, obj=None, **kwargs):
        form_class = super(LinkPlugin, self).get_form(request, obj, **kwargs)

        if obj and obj.page and obj.page.site:
            site = obj.page.site
        elif self.page and self.page.site:
            site = self.page.site
        else:
            # this might NOT give the result you expect
            site = Site.objects.get_current()

        class Form(form_class):
            def __init__(self, *args, **kwargs):
                super(Form, self).__init__(*args, **kwargs)
                self.for_site(site)

        return Form

Example 30

Project: pythondotorg Source File: test_views.py
Function: test_redirect
    def test_redirect(self):
        """
        Check that redirects still have priority over pages.
        """
        redirect = Redirect.objects.create(
            old_path='/%s/' % self.p1.path,
            new_path='http://redirected.example.com',
            site=Site.objects.get_current()
        )
        response = self.client.get(redirect.old_path)
        self.assertEqual(response.status_code, 301)
        self.assertEqual(response['Location'], redirect.new_path)
        redirect.delete()

Example 31

Project: ecobasa Source File: mail_patch_postman.py
Function: email
def email(subject_template, message_template, recipient_list, object):
    """Compose and send an email."""
    ctx_dict = {'site': Site.objects.get_current(), 'object': object, 'action': 'acceptance'}
    subject = render_to_string(subject_template, ctx_dict)
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    message = render_to_string(message_template, ctx_dict)
    # during the development phase, consider using the setting: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)

Example 32

Project: django-subdomains Source File: tests.py
Function: set_up
    def setUp(self):
        super(SubdomainTestMixin, self).setUp()
        from django.contrib.sites.models import Site
        self.site = Site.objects.get_current()
        self.site.domain = self.DOMAIN
        self.site.save()

Example 33

Project: django-pusher Source File: push.py
    def allow_connection(self, request, channel):
        """
        Takes a Django request and determines if this request is allowed to
        connect to the given channel. In case of namespace clashes we take the most
        specific (longest) namespace.
        """
        if getattr(settings, "PUSHER_SITE_SPECIFIC_CHANNELS", False):
            current_site = Site.objects.get_current()
            channel = channel[:-len("@%s" % current_site.pk)]

        namespaces = [x for x in self._registry.keys() if channel.startswith(x)]
        if len(namespaces) == 1:
            if self._registry[namespaces[0]] is not None:
                return self._registry[namespaces[0]](request, channel)
        elif len(namespaces) > 1:
            raise NamespaceClash("The channel %s matches the namespace for [%s]" % (channel, ",".join(namespaces)))
        return False

Example 34

Project: django-waitinglist Source File: export_to_trello.py
Function: handle
    def handle(self, *args, **options):
        self.site = Site.objects.get_current()
        self.protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        self.api = trello.Api()
        self.export_contacts()
        self.export_answers()

Example 35

Project: peer Source File: expirationwarnings.py
Function: warn
    def warn(self, entity, valid_until):
        subject = 'The metadata for entity %s is about to expire' % entity.name
        recipients = self.get_recipients(entity)

        template_context = {
            'entity': entity,
            'valid_until': valid_until,
            'is_expired': False,
            'site': Site.objects.get_current(),
        }
        self.send_email(subject, recipients, template_context)

Example 36

Project: djangoembed Source File: providers.py
    def provider_from_url(self, url):
        """
        Given a URL for any of our sites, try and match it to one, returning
        the domain & name of the match.  If no match is found, return current.
        
        Returns a tuple of domain, site name -- used to determine 'provider'
        """
        domain = get_domain(url)
        site_tuples = self.get_cleaned_sites().values()
        for domain_re, name, normalized_domain in site_tuples:
            if re.match(domain_re, domain):
                return normalized_domain, name
        site = Site.objects.get_current()
        return site.domain, site.name

Example 37

Project: aldryn-events Source File: utils.py
Function: get_valid_languages
def get_valid_languages(namespace, language_code, site_id=None):
        langs = [language_code]
        if site_id is None:
            site_id = getattr(Site.objects.get_current(), 'pk', None)
        current_language = get_language_object(language_code, site_id)
        fallbacks = current_language.get('fallbacks', None)
        if fallbacks:
            langs += list(fallbacks)
        valid_translations = [
            lang_code for lang_code in langs
            if is_valid_namespace_for_language(namespace, lang_code)]
        return valid_translations

Example 38

Project: django-notifier Source File: backends.py
Function: send
    def send(self, user, context=None):
        if not context:
            self.context = {}
        else:
            self.context = context

        self.context.update({
            'user': user,
            'site': Site.objects.get_current()
        })

Example 39

Project: django-registration-rest-framework Source File: utils.py
@atomic_decorator
def create_inactive_user(username=None, email=None, password=None):
    user_model = get_user_model()
    if username is not None:
        new_user = user_model.objects.create_user(username, email, password)
    else:
        new_user = user_model.objects.create_user(email=email, password=password)
    new_user.is_active = False
    new_user.save()
    create_profile(new_user)
    site = Site.objects.get_current()
    send_activation_email(new_user, site)
    return new_user

Example 40

Project: django-reporter Source File: base.py
Function: init
    def __init__(self, frequency, date=None, view=False, filename=None,
                 recipients=None, report_args=None):
        if not frequency in self.frequencies:
            raise NotAvailable('The %s frequency is not available for the %s '
                               'report.' % (frequency, self.name))
        self.frequency = frequency
        self.set_dates(date)
        self.view = view
        self.send = True
        if filename or view:
            self.send = False
        self.file = self.get_file(filename)
        self.recipients = None
        if recipients:
            self.recipients = recipients
        self.site = Site.objects.get_current()
        self.args = report_args

Example 41

Project: wolnelektury Source File: models.py
    def notify(self, subject, template_name, extra_context=None):
        context = {
            'funding': self,
            'site': Site.objects.get_current(),
        }
        if extra_context:
            context.update(extra_context)
        with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
            send_mail(
                subject, render_to_string(template_name, context), settings.CONTACT_EMAIL, [self.email],
                fail_silently=False)

Example 42

Project: django-allauth Source File: tests.py
Function: set_up
    def setUp(self):
        super(SocialAccountTests, self).setUp()
        site = Site.objects.get_current()
        for provider in providers.registry.get_list():
            app = SocialApp.objects.create(
                provider=provider.id,
                name=provider.id,
                client_id='app123id',
                key='123',
                secret='dummy')
            app.sites.add(site)

Example 43

Project: django-calendar-sms Source File: sms.py
Function: get_accounts
    def __get_accounts(self):
        self.accounts = CalendarSMSSettings.objects.filter(
            website__site=Site.objects.get_current(),
            website__status=True,
            status=True
        )
        return self.accounts.exists()

Example 44

Project: django-news-sitemaps Source File: views.py
Function: index
def index(request, sitemaps):
    """
    View to create a sitemap index listing other sitemaps
    """
    current_site = Site.objects.get_current()
    sites = []
    protocol = request.is_secure() and 'https' or 'http'
    for section, site in sitemaps.items():
        if callable(site):
            pages = site().paginator.num_pages
        else:
            pages = site.paginator.num_pages
        sitemap_url = urlresolvers.reverse('news_sitemaps_sitemap', kwargs={'section': section})
        sites.append('%s://%s%s' % (protocol, current_site.domain, sitemap_url))
        if pages > 1:
            for page in range(2, pages+1):
                sites.append('%s://%s%s?p=%s' % (protocol, current_site.domain, sitemap_url, page))
    xml = loader.render_to_string('sitemaps/index.xml', {'sitemaps': sites})
    return HttpResponse(xml, content_type='application/xml')

Example 45

Project: froide Source File: csv_import.py
Function: init
    def __init__(self):
        self.user = User.objects.order_by('id')[0]
        self.site = Site.objects.get_current()
        self.topic_cache = {}
        self.default_topic = None
        self.jur_cache = {}

Example 46

Project: talk.org Source File: views.py
Function: index
def index(request, sitemaps):
    current_site = Site.objects.get_current()
    sites = []
    protocol = request.is_secure() and 'https' or 'http'
    for section in sitemaps.keys():
        sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap', kwargs={'section': section})
        sites.append('%s://%s%s' % (protocol, current_site.domain, sitemap_url))
    xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites})
    return HttpResponse(xml, mimetype='application/xml')

Example 47

Project: django-user-accounts Source File: models.py
Function: send
    def send(self, **kwargs):
        current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        activate_url = "{0}://{1}{2}".format(
            protocol,
            current_site.domain,
            reverse(settings.ACCOUNT_EMAIL_CONFIRMATION_URL, args=[self.key])
        )
        ctx = {
            "email_address": self.email_address,
            "user": self.email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "key": self.key,
        }
        hookset.send_confirmation_email([self.email_address.email], ctx)
        self.sent = timezone.now()
        self.save()
        signals.email_confirmation_sent.send(sender=self.__class__, confirmation=self)

Example 48

Project: shortener_project Source File: admin.py
Function: test_url
    def test_url(self, instance):
        site = Site.objects.get_current()
        response = """<a href="{0}{1}/{2}">{0}{1}/{2}</a>""".format(
                "http://",
                site.domain,
                instance.identifier
            )
        return mark_safe(response)

Example 49

Project: django-userprofiles Source File: forms.py
Function: save
    def save(self, user):
        verification = EmailVerification.objects.create(user=user,
            old_email=user.email, new_email=self.cleaned_data['new_email'])

        context = {
            'user': user,
            'verification': verification,
            'site': Site.objects.get_current(),
        }

        subject = ''.join(render_to_string(
            'userprofiles/mails/emailverification_subject.html', context).splitlines())
        body = render_to_string('userprofiles/mails/emailverification.html', context)

        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL,
            [self.cleaned_data['new_email']])

        return verification

Example 50

Project: codesters Source File: models.py
Function: test_expired_account
    def test_expired_account(self):
        """
        ``RegistrationProfile.activation_key_expired()`` is ``True``
        outside the activation window.
        
        """
        new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        new_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        new_user.save()
        profile = RegistrationProfile.objects.get(user=new_user)
        self.failUnless(profile.activation_key_expired())
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4