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
3
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))
3
Example 2
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)
3
Example 3
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)
3
Example 4
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)
3
Example 5
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
3
Example 6
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),
}
3
Example 7
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
3
Example 8
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))
3
Example 9
Project: hortonworks-sandbox Source File: views.py
Function: test_current_site_in_context_after_login
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')
3
Example 10
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)
3
Example 11
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)
3
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())
3
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)
3
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
3
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()
3
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)
3
Example 17
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
3
Example 18
def authenticate(self, github = None):
try:
return GithubProfile.objects.get(
github = github,
site = Site.objects.get_current()).user
except GithubProfile.DoesNotExist:
return None
3
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)
3
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
)
3
Example 21
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()
3
Example 22
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
3
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)
3
Example 24
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':''}
3
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
3
Example 26
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()
3
Example 27
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()
3
Example 28
def counter(object):
ctype = ContentType.objects.get_for_model(object)
return {
'ctype': ctype,
'object': object,
'site': Site.objects.get_current()}
3
Example 29
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
3
Example 30
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()
3
Example 31
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)
3
Example 32
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()
3
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
3
Example 34
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()
3
Example 35
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)
3
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
3
Example 37
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
3
Example 38
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()
})
3
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
3
Example 40
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
3
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)
3
Example 42
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)
3
Example 43
def __get_accounts(self):
self.accounts = CalendarSMSSettings.objects.filter(
website__site=Site.objects.get_current(),
website__status=True,
status=True
)
return self.accounts.exists()
3
Example 44
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')
3
Example 45
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 = {}
3
Example 46
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')
3
Example 47
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)
3
Example 48
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)
3
Example 49
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
3
Example 50
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())