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.
120 Examples
3
Source : arx_utils.py
with MIT License
from Arx-Game
with MIT License
from Arx-Game
def get_full_url(url):
"""
Gets the full url when given a partial, used for formatting links. For this to work
properly, you should define your Site's url under the 'Sites' app in django's admin
site.
Args:
url: A partial url from a few, like '/namespace/view/'
Returns:
A full url, like "http://www.example.com/namespace/view/"
"""
from django.contrib.sites.models import Site
return "http://%s%s" % (Site.objects.get_current(), url)
3
Source : models.py
with MIT License
from Arx-Game
with MIT License
from Arx-Game
def _get_ticket_url(self):
"""
Returns a publicly-viewable URL for this ticket, used when giving
a URL to the submitter of a ticket.
"""
from django.contrib.sites.models import Site
try:
site = Site.objects.get_current()
except:
site = Site(domain="configure-django-sites.com")
return "http://%s%s?ticket=%s&email=%s" % (
site.domain,
reverse("helpdesk_public_view"),
self.ticket_for_url,
self.submitter_email,
)
ticket_url = property(_get_ticket_url)
3
Source : models.py
with MIT License
from Arx-Game
with MIT License
from Arx-Game
def _get_staff_url(self):
"""
Returns a staff-only URL for this ticket, used when giving a URL to
a staff member (in emails etc)
"""
from django.contrib.sites.models import Site
try:
site = Site.objects.get_current()
except:
site = Site(domain="configure-django-sites.com")
return "http://%s%s" % (site.domain, reverse("helpdesk_view", args=[self.id]))
staff_url = property(_get_staff_url)
3
Source : user_attendance.py
with GNU General Public License v3.0
from auto-mat
with GNU General Public License v3.0
from auto-mat
def get_admin_url(self, method="change", protocol="https"):
try:
site = Site.objects.get_current()
except ImproperlyConfigured:
site = Site(domain="configure-django-sites.com")
return "%s://%s.%s%s" % (
protocol,
self.campaign.slug,
site.domain,
reverse(
"admin:%s_%s_%s"
% (self._meta.app_label, self._meta.model_name, method),
args=[self.id],
),
)
def get_admin_delete_url(self):
3
Source : serializers.py
with MIT License
from DjangoChinaOrg
with MIT License
from DjangoChinaOrg
def create(self, validated_data):
post_id = validated_data.get('object_pk')
post_ctype = ContentType.objects.get_for_model(
Post.objects.get(id=int(post_id))
)
site = Site.objects.get_current()
validated_data['content_type'] = post_ctype
validated_data['site'] = site
return super(ReplyCreationSerializer, self).create(validated_data)
class TreeRepliesSerializer(serializers.ModelSerializer):
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from DJWOMS
with BSD 3-Clause "New" or "Revised" License
from DJWOMS
def send_feedback_email(sender, instance, created, **kwargs):
"""Отправка email"""
if created:
full_name = email = phone = subject = message = date = ''
if instance.full_name is not None:
full_name = 'ФИО - {} < br>'.format(instance.full_name)
if instance.email is not None:
email = 'Email - {} < br>'.format(instance.email)
if instance.phone is not None:
phone = 'Номер - {} < br>'.format(instance.phone)
if instance.subject is not None:
subject = 'Тема - {} < br>'.format(instance.subject)
if instance.message is not None:
message = 'Сообщение: < br> {} < br>'.format(instance.message)
topic = 'Новое сообщение обратной связи {}'.format(Site.objects.get_current())
message = """ < p>{}{}{}{}{}{} < /p>""".format(full_name, email, phone, subject, message, date)
send_mail_contact(topic, message)
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from DJWOMS
with BSD 3-Clause "New" or "Revised" License
from DJWOMS
def get_anchor(self):
if self.anchor:
return "{}/#{}".format(Site.objects.get_current().domain, self.anchor)
else:
return False
def __str__(self):
3
Source : storage.py
with GNU Affero General Public License v3.0
from f-droid
with GNU Affero General Public License v3.0
from f-droid
def get_repo_url(self):
url = self.get_url()
if url.startswith('/'):
current_site = Site.objects.get_current()
url = 'https://' + current_site.domain + url
return url + self.get_identifier() + "/" + REPO_DIR
def publish(self):
3
Source : utils.py
with GNU General Public License v3.0
from foonsun
with GNU General Public License v3.0
from foonsun
def send_alert_confirmation(alert):
"""
Send an alert confirmation email.
"""
ctx = {
'alert': alert,
'site': Site.objects.get_current(),
}
code = 'PRODUCT_ALERT_CONFIRMATION'
messages = CommunicationEventType.objects.get_and_render(code, ctx)
if messages and messages['body']:
Dispatcher().dispatch_direct_messages(alert.email, messages)
def send_product_alerts(product): # noqa C901 too complex
3
Source : tasks.py
with Apache License 2.0
from genomicsengland
with Apache License 2.0
from genomicsengland
def revierwer_confirmed_email(user_id):
"Send an email when user has been confirmed as a reviewer"
from .models import User
user = User.objects.get(pk=user_id)
site = Site.objects.get_current()
ctx = {"user": user, "site": site, "settings": settings}
text = render_to_string("registration/emails/reviewer_approved.txt", ctx)
send_email(
user.email,
"Congratulations, you have been approved please authenticate your account",
text,
)
@shared_task
3
Source : tasks.py
with Apache License 2.0
from genomicsengland
with Apache License 2.0
from genomicsengland
def send_verification_email(user_id):
from .models import User
user = User.objects.get(pk=user_id)
site = Site.objects.get_current()
ctx = {"user": user, "site": site, "settings": settings}
text = render_to_string("registration/emails/verify_email.txt", ctx)
send_email(user.email, "Please verify your email address", text)
3
Source : admin.py
with Apache License 2.0
from genomicsengland
with Apache License 2.0
from genomicsengland
def view_example(self, obj):
"Example of how to use this image with markdown syntax"
site = Site.objects.get_current()
return "![{0}](https://{1}{2})".format(obj.alt, site.domain, obj.image.url)
view_example.empty_value_display = ""
3
Source : admin.py
with Apache License 2.0
from genomicsengland
with Apache License 2.0
from genomicsengland
def view_example(self, obj):
"File url"
site = Site.objects.get_current()
return "[{0}](https://{1}{2})".format(obj.title, site.domain, obj.file.url)
view_example.empty_value_display = ""
3
Source : test_sitemaps.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def setUpTestData(cls):
Site = apps.get_model('sites.Site')
current_site = Site.objects.get_current()
current_site.flatpage_set.create(url="/foo/", title="foo")
current_site.flatpage_set.create(url="/private-foo/", title="private foo", registration_required=True)
def test_flatpage_sitemap(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_site_manager(self):
# Make sure that get_current() does not return a deleted Site object.
s = Site.objects.get_current()
self.assertIsInstance(s, Site)
s.delete()
with self.assertRaises(ObjectDoesNotExist):
Site.objects.get_current()
def test_site_cache(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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("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("Example site", site.name)
def test_delete_all_sites_clears_cache(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_delete_all_sites_clears_cache(self):
# When all site objects are deleted the cache should also
# be cleared and get_current() should raise a DoesNotExist.
self.assertIsInstance(Site.objects.get_current(), Site)
Site.objects.all().delete()
with self.assertRaises(Site.DoesNotExist):
Site.objects.get_current()
@override_settings(ALLOWED_HOSTS=['example.com'])
3
Source : models.py
with MIT License
from Hedera-Lang-Learn
with MIT License
from Hedera-Lang-Learn
def students_join_link(self):
domain = Site.objects.get_current().domain
url = reverse("groups_join", args=[self.student_invite_key])
return f"https://{domain}{url}"
def teachers_join_link(self):
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def agenda_txt(request, date=None):
data = agenda_data(date)
return render(request, "iesg/agenda.txt", {
"date": data["date"],
"sections": sorted(data["sections"].items(), key=lambda x:[int(p) for p in x[0].split('.')]),
"domain": Site.objects.get_current().domain,
}, content_type="text/plain; charset=%s"%settings.DEFAULT_CHARSET)
@role_required('Area Director', 'Secretariat')
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def agenda_package(request, date=None):
data = agenda_data(date)
return render(request, "iesg/agenda_package.txt", {
"date": data["date"],
"sections": sorted(data["sections"].items()),
"roll_call": data["sections"]["1.1"]["text"],
"roll_call_url": settings.IESG_ROLL_CALL_URL,
"minutes": data["sections"]["1.3"]["text"],
"minutes_url": settings.IESG_MINUTES_URL,
"management_items": [(num, section) for num, section in data["sections"].items() if "6" < num < "7"],
"domain": Site.objects.get_current().domain,
}, content_type='text/plain')
def agenda_documents_txt(request):
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def send_account_creation_email(request, to_email):
auth = django.core.signing.dumps(to_email, salt="create_account")
domain = Site.objects.get_current().domain
subject = 'Confirm registration at %s' % domain
from_email = settings.DEFAULT_FROM_EMAIL
send_mail(request, to_email, from_email, subject, 'registration/creation_email.txt', {
'domain': domain,
'auth': auth,
'username': to_email,
'expire': settings.DAYS_TO_EXPIRE_REGISTRATION_LINK,
})
def confirm_account(request, auth):
3
Source : site_util.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def get_site_from_request_or_default(request: Optional[HttpRequest] = None) -> Site:
"""
Attempts to retrieve the Site object for the given request. If no request is
passed, or if no Site maps to it, the default site is returned.
"""
if request is None:
return get_default_site()
try:
return Site.objects.get_current(request)
except Site.DoesNotExist:
return get_default_site()
def get_site_of_type(site_type: str) -> Site:
3
Source : emails.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def get_email_base_context():
site = Site.objects.get_current()
logo_url = build_absolute_uri(static('images/logo-document.svg'))
return {
'domain': site.domain,
'logo_url': logo_url,
'site_name': site.name}
3
Source : random_data.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def set_homepage_collection():
homepage_collection = Collection.objects.order_by('?').first()
site = Site.objects.get_current()
site_settings = site.settings
site_settings.homepage_collection = homepage_collection
site_settings.save()
yield 'Homepage collection assigned'
def add_address_to_admin(email):
3
Source : __init__.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def build_absolute_uri(location):
# type: (str) -> str
host = Site.objects.get_current().domain
protocol = 'https' if settings.ENABLE_SSL else 'http'
current_uri = '%s://%s' % (protocol, host)
location = urljoin(current_uri, location)
return iri_to_uri(location)
def get_client_ip(request):
3
Source : weight.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def get_default_weight_unit():
site = Site.objects.get_current()
return site.settings.default_weight_unit
class WeightInput(forms.TextInput):
3
Source : utils.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def create_invoice_pdf(order, absolute_url):
ctx = {
'order': order,
'site': Site.objects.get_current()}
rendered_template = get_template(INVOICE_TEMPLATE).render(ctx)
pdf_file = _create_pdf(rendered_template, absolute_url)
return pdf_file, order
def create_packing_slip_pdf(order, fulfillment, absolute_url):
3
Source : utils.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def create_packing_slip_pdf(order, fulfillment, absolute_url):
ctx = {
'order': order,
'fulfillment': fulfillment,
'site': Site.objects.get_current()}
rendered_template = get_template(PACKING_SLIP_TEMPLATE).render(ctx)
pdf_file = _create_pdf(rendered_template, absolute_url)
return pdf_file, order
def fulfill_order_line(order_line, quantity):
3
Source : email.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def get_organization():
site = Site.objects.get_current()
return {'@type': 'Organization', 'name': site.name}
def get_product_data(line, organization):
3
Source : settings.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def get_host():
from django.contrib.sites.models import Site
return Site.objects.get_current().domain
PAYMENT_HOST = get_host
3
Source : test_site_settings.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def test_new_get_current():
result = Site.objects.get_current()
assert result.name == 'mirumee.com'
assert result.domain == 'mirumee.com'
assert type(result.settings) == SiteSettings
assert str(result.settings) == 'mirumee.com'
def test_new_get_current_from_request():
3
Source : test_site_settings.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def test_new_get_current_from_request():
factory = RequestFactory()
request = factory.get(reverse('dashboard:site-index'))
result = Site.objects.get_current(request)
assert result.name == 'mirumee.com'
assert result.domain == 'mirumee.com'
assert type(result.settings) == SiteSettings
assert str(result.settings) == 'mirumee.com'
3
Source : utils.py
with MIT License
from kiwicom
with MIT License
from kiwicom
def get_absolute_url(rel_url):
"""Return absolute URL according to app configuration."""
protocol = "http" if settings.DEBUG else "https"
domain = Site.objects.get_current().domain
return f"{protocol}://{domain}{rel_url}"
def get_system_option(sort_by=None):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
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)
def test_site_cache(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_delete_all_sites_clears_cache(self):
# When all site objects are deleted the cache should also
# be cleared and get_current() should raise a DoesNotExist.
self.assertIsInstance(Site.objects.get_current(), Site)
Site.objects.all().delete()
self.assertRaises(Site.DoesNotExist, Site.objects.get_current)
@override_settings(ALLOWED_HOSTS=['example.com'])
3
Source : serializers.py
with Apache License 2.0
from mandiant
with Apache License 2.0
from mandiant
def validate_redirect_url(self, value):
current_site = Site.objects.get_current().domain
redirect_url = value
parsed_redirect_url = urlparse(redirect_url)
if current_site != parsed_redirect_url.netloc:
raise serializers.ValidationError("Oauth redirect_url must match the current site's domain")
return redirect_url
def to_representation(self, instance):
3
Source : emails.py
with MIT License
from marcosgabarda
with MIT License
from marcosgabarda
def get_context(self) -> Dict:
"""Hook to customize context."""
# Add default context
current_site = Site.objects.get_current()
self.default_context.update({"site": current_site})
return self.default_context
def preview(self) -> str:
3
Source : forms.py
with GNU General Public License v2.0
from puncoder
with GNU General Public License v2.0
from puncoder
def send_confirm_mail(self, request, activation_key,
template_name='registration/confirm_email.html'):
current_site = Site.objects.get_current()
confirm_url = '%s%s' % (
request_host_link(request, current_site.domain),
reverse('tcms-confirm',
args=[activation_key.activation_key, ])
)
mailto(
template_name=template_name, recipients=self.cleaned_data['email'],
subject='Your new %s account confirmation' % current_site.domain,
context={
'user': self.instance,
'site': current_site,
'active_key': activation_key,
'confirm_url': confirm_url,
}
)
3
Source : base.py
with GNU General Public License v2.0
from puncoder
with GNU General Public License v2.0
from puncoder
def get_full_url(self):
site = Site.objects.get_current()
host_link = request_host_link(None, site.domain)
return '{}/{}'.format(host_link, self._get_absolute_url().strip('/'))
class TCMSContentTypeBaseModel(models.Model):
3
Source : installation_utils.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def send_app_token(target_url: str, token: str):
domain = Site.objects.get_current().domain
headers = {
"Content-Type": "application/json",
# X- headers will be deprecated in Saleor 4.0, proper headers are without X-
"x-saleor-domain": domain,
"saleor-domain": domain,
}
json_data = {"auth_token": token}
response = requests.post(
target_url, json=json_data, headers=headers, timeout=REQUEST_TIMEOUT
)
response.raise_for_status()
def install_app(
3
Source : create_app.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def send_app_data(self, target_url, data: Dict[str, Any]):
domain = Site.objects.get_current().domain
headers = {
# X- headers will be deprecated in Saleor 4.0, proper headers are without X-
"x-saleor-domain": domain,
"saleor-domain": domain,
}
try:
response = requests.post(target_url, json=data, headers=headers, timeout=15)
except RequestException as e:
raise CommandError(f"Request failed. Exception: {e}")
response.raise_for_status()
def handle(self, *args: Any, **options: Any) -> Optional[str]:
3
Source : utils.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def get_site_context():
site: Site = Site.objects.get_current()
site_context = {
"domain": site.domain,
"site_name": site.name,
}
return site_context
3
Source : __init__.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def build_absolute_uri(location: str) -> Optional[str]:
"""Create absolute uri from location.
If provided location is absolute uri by itself, it returns unchanged value,
otherwise if provided location is relative, absolute uri is built and returned.
"""
host = Site.objects.get_current().domain
protocol = "https" if settings.ENABLE_SSL else "http"
current_uri = "%s://%s" % (protocol, host)
location = urljoin(current_uri, location)
return iri_to_uri(location)
def get_client_ip(request):
3
Source : weight.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def get_default_weight_unit():
site = Site.objects.get_current()
return site.settings.default_weight_unit
def convert_weight_to_default_weight_unit(weight: Weight) -> Weight:
3
Source : __init__.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def append_shipping_to_data(
data: List[Dict],
shipping_method_channel_listings: Optional["ShippingMethodChannelListing"],
):
charge_taxes_on_shipping = (
Site.objects.get_current().settings.charge_taxes_on_shipping
)
if charge_taxes_on_shipping and shipping_method_channel_listings:
shipping_price = shipping_method_channel_listings.price
append_line_to_data(
data,
quantity=1,
amount=shipping_price.amount,
tax_code=COMMON_CARRIER_CODE,
item_code="Shipping",
)
def get_checkout_lines_data(
3
Source : digital_products.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def get_default_digital_content_settings() -> dict:
site = Site.objects.get_current()
settings = site.settings
return {
"automatic_fulfillment": (settings.automatic_fulfillment_digital_products),
"max_downloads": settings.default_digital_max_downloads,
"url_valid_days": settings.default_digital_url_valid_days,
}
def digital_content_url_is_valid(content_url: DigitalContentUrl) -> bool:
3
Source : email.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def get_organization():
site = Site.objects.get_current()
return {"@type": "Organization", "name": site.name}
def get_product_data(line: "OrderLine", organization: dict) -> dict:
3
Source : settings.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def get_host():
from django.contrib.sites.models import Site
return Site.objects.get_current().domain
PAYMENT_HOST = get_host
3
Source : test_site_settings.py
with GNU General Public License v3.0
from Saleor-Multi-Vendor
with GNU General Public License v3.0
from Saleor-Multi-Vendor
def test_new_get_current():
result = Site.objects.get_current()
assert result.name == "mirumee.com"
assert result.domain == "mirumee.com"
assert type(result.settings) == SiteSettings
assert str(result.settings) == "mirumee.com"
3
Source : setup.py
with MIT License
from ustclug
with MIT License
from ustclug
def handle(self, *args, **options):
site = Site.objects.get_current()
app = SocialApp.objects.create(
provider='google',
name='Google',
client_id=settings.GOOGLE_APP_ID,
secret=settings.GOOGLE_APP_SECRET,
key='',
)
app.sites.add(site)
app = SocialApp.objects.create(
provider='microsoft',
name='Microsoft',
client_id=settings.MICROSOFT_APP_ID,
secret=settings.MICROSOFT_APP_SECRET,
key=''
)
app.sites.add(site)
See More Examples