Python django.contrib.sites.models.Site() Examples
The following are 30
code examples of django.contrib.sites.models.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.models
, or try the search function
.
Example #1
Source File: test_admin.py From django-usersettings2 with BSD 3-Clause "New" or "Revised" License | 8 votes |
def setUp(self): Site.objects.get_or_create(id=settings.SITE_ID, domain='example.com', name='example.com') self.obj = get_usersettings_model().objects.create(**self.usersettings_data) self.user = get_user_model().objects.create_superuser( self.username, self.email, self.password) self.assertTrue(self.client.login( username=self.username, password=self.password), 'Failed to login user %s' % self.email) factory = RequestFactory() request = factory.get('/admin') request.user = self.user request.session = {} self.request = request self.settings_admin = SettingsAdmin(get_usersettings_model(), AdminSite()) # Hack to test this function as it calls 'messages.add' # See https://code.djangoproject.com/ticket/17971 setattr(self.request, 'session', 'session') messages = FallbackStorage(self.request) setattr(self.request, '_messages', messages)
Example #2
Source File: test_middleware.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain='example.com', name='example.com') cls.site1.save() cls.fp1 = FlatPage.objects.create( url='/flatpage/', title='A Flatpage', content="Isn't it flat!", enable_comments=False, template_name='', registration_required=False ) cls.fp2 = FlatPage.objects.create( url='/location/flatpage/', title='A Nested Flatpage', content="Isn't it flat and deep!", enable_comments=False, template_name='', registration_required=False ) cls.fp3 = FlatPage.objects.create( url='/sekrit/', title='Sekrit Flatpage', content="Isn't it sekrit!", enable_comments=False, template_name='', registration_required=True ) cls.fp4 = FlatPage.objects.create( url='/location/sekrit/', title='Sekrit Nested Flatpage', content="Isn't it sekrit and deep!", enable_comments=False, template_name='', registration_required=True ) cls.fp1.sites.add(cls.site1) cls.fp2.sites.add(cls.site1) cls.fp3.sites.add(cls.site1) cls.fp4.sites.add(cls.site1)
Example #3
Source File: init-basic-data.py From django-aws-template with MIT License | 6 votes |
def handle(self, *args, **options): if Account.objects.count() == 0: # If there are no Accounts, we can assume this is a new Env # create a super user self._create_super_users() if SocialApp.objects.count() == 0: # Also fixup the Site info site = Site.objects.get_current() site.domain_name = getattr(settings, 'DOMAIN_NAME') site.display_name = getattr(settings, 'COMPANY_NAME') site.save() if not getattr(settings, 'PRODUCTION'): self._create_social_accounts(site) else: print('Admin accounts can only be initialized if no Accounts exist')
Example #4
Source File: test_commands.py From credentials with GNU Affero General Public License v3.0 | 6 votes |
def test_update_site(self): """ Verify the command updates Site and SiteConfiguration. """ expected_site_domain = self.faker.domain_name() expected_site_name = 'Fake Credentials Server' site = SiteFactory() self._call_command( site_id=site.id, site_domain=expected_site_domain, site_name=expected_site_name ) site.refresh_from_db() self.assertEqual(site.domain, expected_site_domain) self.assertEqual(site.name, expected_site_name) self._check_site_configuration(site.siteconfiguration)
Example #5
Source File: models.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def get_payment_processors(self): """ Returns payment processor classes enabled for the corresponding Site Returns: list[BasePaymentProcessor]: Returns payment processor classes enabled for the corresponding Site """ all_processors = self._all_payment_processors() all_processor_names = {processor.NAME for processor in all_processors} missing_processor_configurations = self.payment_processors_set - all_processor_names if missing_processor_configurations: processor_config_repr = ", ".join(missing_processor_configurations) log.warning( 'Unknown payment processors [%s] are configured for site %s', processor_config_repr, self.site.id ) return [ processor for processor in all_processors if processor.NAME in self.payment_processors_set and processor.is_enabled() ]
Example #6
Source File: test_commands.py From credentials with GNU Affero General Public License v3.0 | 6 votes |
def _check_site_configuration(self, site_configuration): """ Helper method for verifying that the Site is properly configured. Args: site_configuration (SiteConfiguration): SiteConfiguration that's being verified. """ self.assertEqual(site_configuration.lms_url_root, self.site_configuration.lms_url_root) self.assertEqual(site_configuration.platform_name, self.site_configuration.platform_name) self.assertEqual(site_configuration.catalog_api_url, self.site_configuration.catalog_api_url) self.assertEqual(site_configuration.tos_url, self.site_configuration.tos_url) self.assertEqual(site_configuration.privacy_policy_url, self.site_configuration.privacy_policy_url) self.assertEqual(site_configuration.homepage_url, self.site_configuration.homepage_url) self.assertEqual(site_configuration.company_name, self.site_configuration.company_name) self.assertEqual(site_configuration.certificate_help_url, self.site_configuration.certificate_help_url) self.assertEqual(site_configuration.records_help_url, self.site_configuration.records_help_url) self.assertEqual(site_configuration.twitter_username, self.site_configuration.twitter_username) self.assertEqual(site_configuration.facebook_app_id, self.site_configuration.facebook_app_id) self.assertEqual(site_configuration.segment_key, self.site_configuration.segment_key) self.assertEqual(site_configuration.theme_name, self.site_configuration.theme_name) # Social sharing is disabled by default, if the flag is not passed self.assertFalse(site_configuration.enable_linkedin_sharing) self.assertFalse(site_configuration.enable_twitter_sharing) self.assertFalse(site_configuration.enable_facebook_sharing)
Example #7
Source File: tests.py From django-seo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_sites(self): """ Tests the django.contrib.sites support. A separate metadata definition is used, WithSites, which has turned on sites support. """ path = "/abc/" site = Site.objects.get_current() path_metadata = WithSites._meta.get_model('path').objects.create(_site=site, title="Site Path title", _path=path) self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, 'Site Path title') # Metadata with site=null should work path_metadata._site_id = None path_metadata.save() self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, 'Site Path title') # Metadata with an explicitly wrong site should not work path_metadata._site_id = site.id + 1 path_metadata.save() self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, None)
Example #8
Source File: views.py From opentaps_seas with GNU Lesser General Public License v3.0 | 6 votes |
def about_view(request): g = hszinc.Grid() g.column['vendorUri'] = {} g.column['productUri'] = {} g.column['tz'] = {} g.column['serverName'] = {} g.column['productName'] = {} g.column['haystackVersion'] = {} g.column['productVersion'] = {} g.column['serverTime'] = {} g.column['serverBootTime'] = {} g.column['vendorName'] = {} g.extend([{ 'vendorUri': 'https://www.opensourcestrategies.com', 'productUri': 'https://www.opensourcestrategies.com', 'tz': timezone.get_default_timezone_name(), 'serverName': Site.objects.get_current().domain, 'productName': 'Opentaps-SEAS Haystack', 'haystackVersion': '2.0', 'productVersion': '1.0', 'serverTime': timezone.now(), 'vendorName': 'Opentaps-SEAS Haystack' }]) return _hzinc_response(g)
Example #9
Source File: update_site_oauth_settings.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def handle(self, *args, **options): site_id = options.get('site_id') sso_client_id = options.get('sso_client_id') sso_client_secret = options.get('sso_client_secret') backend_service_client_id = options.get('backend_service_client_id') backend_service_client_secret = options.get('backend_service_client_secret') site = Site.objects.get(id=site_id) site_configuration = SiteConfiguration.objects.get(site=site) oauth_settings = site_configuration.oauth_settings lms_url_root = site_configuration.lms_url_root oauth_settings.update({ 'SOCIAL_AUTH_EDX_OAUTH2_URL_ROOT': lms_url_root, 'SOCIAL_AUTH_EDX_OAUTH2_LOGOUT_URL': '{lms_url_root}/logout'.format(lms_url_root=lms_url_root), 'SOCIAL_AUTH_EDX_OAUTH2_ISSUERS': [lms_url_root], 'SOCIAL_AUTH_EDX_OAUTH2_KEY': sso_client_id, 'SOCIAL_AUTH_EDX_OAUTH2_SECRET': sso_client_secret, 'BACKEND_SERVICE_EDX_OAUTH2_KEY': backend_service_client_id, 'BACKEND_SERVICE_EDX_OAUTH2_SECRET': backend_service_client_secret, }) site_configuration.save()
Example #10
Source File: testcase.py From coursys with GNU General Public License v3.0 | 6 votes |
def _pre_setup(self): """Disable transaction methods, and clear some globals.""" # Repeat stuff from TransactionTestCase, because I'm not calling its # _pre_setup, because that would load fixtures again. cache.cache.clear() settings.TEMPLATE_DEBUG = settings.DEBUG = False self.client = self.client_class() #self._fixture_setup() self._urlconf_setup() mail.outbox = [] # Clear site cache in case somebody's mutated Site objects and then # cached the mutated stuff: from django.contrib.sites.models import Site Site.objects.clear_cache()
Example #11
Source File: models.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def get_theme(site): """ Get SiteTheme object for given site, returns default site theme if it can not find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value. Args: site (django.contrib.sites.models.Site): site object related to the current site. Returns: SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME` """ if not site: return None theme = site.themes.first() if (not theme) and settings.DEFAULT_SITE_THEME: theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) return theme
Example #12
Source File: test_create_or_update_site_theme.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def test_update_site(self): """ Test that site is updated properly if site-id belongs to an existing site. """ # Create a site to update site = Site.objects.create(domain="test.localhost", name="Test Site") call_command( "create_or_update_site_theme", "--site-id={}".format(site.id), "--site-name=updated name", "--site-domain=test.localhost", '--site-theme=test', ) # Verify updated site name site = Site.objects.get(id=site.id) self.assertEqual(site.name, "updated name")
Example #13
Source File: test_create_or_update_site_theme.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def test_update_site_theme(self): """ Test that site theme is updated properly when site and site theme already exist. """ # Create a site and site theme to update site = Site.objects.create(domain="test.localhost", name="Test Site") site_theme = SiteTheme.objects.create(site=site, theme_dir_name="site_theme_1") call_command( "create_or_update_site_theme", "--site-domain=test.localhost", '--site-theme=site_theme_2', ) # Verify updated site name site_theme = SiteTheme.objects.get(id=site_theme.id) self.assertEqual(site_theme.theme_dir_name, "site_theme_2")
Example #14
Source File: test_utils.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def with_comprehensive_theme(theme_dir_name): """ A decorator to run a test with a comprehensive theming enabled. Arguments: theme_dir_name (str): directory name of the site for which we want comprehensive theming enabled. """ # This decorator creates Site and SiteTheme models for given domain def _decorator(func): # pylint: disable=missing-docstring @wraps(func) def _decorated(*args, **kwargs): # pylint: disable=missing-docstring # make a domain name out of directory name domain = "{theme_dir_name}.org".format(theme_dir_name=re.sub(r"\.org$", "", theme_dir_name)) site, __ = Site.objects.get_or_create(domain=domain, name=domain) site_theme, __ = SiteTheme.objects.get_or_create(site=site, theme_dir_name=theme_dir_name) with patch('ecommerce.theming.helpers.get_current_site_theme', return_value=site_theme): return func(*args, **kwargs) return _decorated return _decorator
Example #15
Source File: create_sites_and_partners.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def handle(self, *args, **options): if options['devstack']: configuration_prefix = 'devstack' else: configuration_prefix = 'sandbox' self.configuration_filename = '{}_configuration.json'.format(configuration_prefix) self.dns_name = options['dns_name'] self.theme_path = options['theme_path'] logger.info("Using %s configuration...", configuration_prefix) logger.info('DNS name: %s', self.dns_name) logger.info('Theme path: %s', self.theme_path) all_sites = self._get_site_partner_data() for site_name, site_data in all_sites.items(): logger.info('Creating %s Site', site_name) self._create_sites( site_data['site_domain'], site_data['theme_dir_name'], site_data['configuration'], site_data['partner_code'], options['demo_course'] )
Example #16
Source File: tests.py From django-seo2 with MIT License | 6 votes |
def test_sites(self): """ Tests the django.contrib.sites support. A separate metadata definition is used, WithSites, which has turned on sites support. """ path = "/abc/" site = Site.objects.get_current() path_metadata = WithSites._meta.get_model('path').objects.create( _site=site, title="Site Path title", _path=path) self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, 'Site Path title') # Metadata with site=null should work path_metadata._site_id = None path_metadata.save() self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, 'Site Path title') # Metadata with an explicitly wrong site should not work path_metadata._site_id = site.id + 1 path_metadata.save() self.assertEqual(seo_get_metadata(path, name="WithSites").title.value, None)
Example #17
Source File: tests.py From django-seo2 with MIT License | 6 votes |
def test_use_cache_site(self): """Checks that the cache plays nicely with sites.""" if 'dummy' not in settings.CACHE_BACKEND: path = '/' site = Site.objects.get_current() hexpath = hashlib.md5(iri_to_uri(site.domain + path)).hexdigest() # text_type(seo_get_metadata(path, name="Coverage")) text_type(seo_get_metadata(path, name="WithCacheSites", site=site)) self.assertEqual( cache.get('djangoseo.Coverage.%s.title' % hexpath), None) self.assertEqual( cache.get('djangoseo.WithCacheSites.%s.title' % hexpath), "1234") self.assertEqual( cache.get('djangoseo.WithCacheSites.%s.subtitle' % hexpath), "")
Example #18
Source File: tasks.py From figures with MIT License | 6 votes |
def populate_course_mau(site_id, course_id, month_for=None, force_update=False): """Populates the MAU for the given site, course, and month """ if month_for: month_for = as_date(month_for) else: month_for = datetime.datetime.utcnow().date() site = Site.objects.get(id=site_id) start_time = time.time() obj, _created = collect_course_mau(site=site, courselike=course_id, month_for=month_for, overwrite=force_update) if not obj: msg = 'populate_course_mau failed for course {course_id}'.format( course_id=str(course_id)) logger.error(msg) elapsed_time = time.time() - start_time logger.info('populate_course_mau Elapsed time (seconds)={}. cdm_obj={}'.format( elapsed_time, obj))
Example #19
Source File: test_views.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain='example.com', name='example.com') cls.site1.save() cls.fp1 = FlatPage.objects.create( url='/flatpage/', title='A Flatpage', content="Isn't it flat!", enable_comments=False, template_name='', registration_required=False ) cls.fp2 = FlatPage.objects.create( url='/location/flatpage/', title='A Nested Flatpage', content="Isn't it flat and deep!", enable_comments=False, template_name='', registration_required=False ) cls.fp3 = FlatPage.objects.create( url='/sekrit/', title='Sekrit Flatpage', content="Isn't it sekrit!", enable_comments=False, template_name='', registration_required=True ) cls.fp4 = FlatPage.objects.create( url='/location/sekrit/', title='Sekrit Nested Flatpage', content="Isn't it sekrit and deep!", enable_comments=False, template_name='', registration_required=True ) cls.fp1.sites.add(cls.site1) cls.fp2.sites.add(cls.site1) cls.fp3.sites.add(cls.site1) cls.fp4.sites.add(cls.site1)
Example #20
Source File: test_templatetags.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain='example.com', name='example.com') cls.site1.save() cls.fp1 = FlatPage.objects.create( url='/flatpage/', title='A Flatpage', content="Isn't it flat!", enable_comments=False, template_name='', registration_required=False ) cls.fp2 = FlatPage.objects.create( url='/location/flatpage/', title='A Nested Flatpage', content="Isn't it flat and deep!", enable_comments=False, template_name='', registration_required=False ) cls.fp3 = FlatPage.objects.create( url='/sekrit/', title='Sekrit Flatpage', content="Isn't it sekrit!", enable_comments=False, template_name='', registration_required=True ) cls.fp4 = FlatPage.objects.create( url='/location/sekrit/', title='Sekrit Nested Flatpage', content="Isn't it sekrit and deep!", enable_comments=False, template_name='', registration_required=True ) cls.fp1.sites.add(cls.site1) cls.fp2.sites.add(cls.site1) cls.fp3.sites.add(cls.site1) cls.fp4.sites.add(cls.site1)
Example #21
Source File: test_sites_view.py From figures with MIT License | 6 votes |
def test_get(self, query_params, filter_args): qp_msg = 'query_params={query_params}' expected_data = Site.objects.filter(**filter_args) request = APIRequestFactory().get(self.request_path + query_params) request.user = self.staff_user view = self.view_class.as_view({'get': 'list'}) response = view(request) assert response.status_code == 200, qp_msg.format(query_params=query_params) assert set(response.data.keys()) == set( ['count', 'next', 'previous', 'results']) assert len(response.data['results']) == len(expected_data), qp_msg.format( query_params=query_params) results = response.data['results'] # Validate just the first object's structure for field_name in self.expected_result_keys: assert field_name in results[0] # Validate the ids match up expected_ids = expected_data.values_list('id', flat=True) actual_ids = [o['id'] for o in results] assert set(actual_ids) == set(expected_ids)
Example #22
Source File: backends.py From django-seo2 with MIT License | 5 votes |
def on_current_site(self, site=None): if isinstance(site, Site): site_id = site.id elif site is not None: site_id = site and Site.objects.get(domain=site).id else: site_id = settings.SITE_ID # Exclude entries for other sites where = ['_site_id IS NULL OR _site_id=%s'] return self.get_queryset().extra(where=where, params=[site_id])
Example #23
Source File: test_sites_view.py From figures with MIT License | 5 votes |
def setup(self, db): super(TestSiteViewSet, self).setup(db) assert Site.objects.count() == 1 self.sites = [ Site.objects.first(), SiteFactory(domain=u'alpha.test.site', name=u'Alpha Group'), SiteFactory(domain=u'bravo.test.site', name=u'Bravo Organization'), ] self.expected_result_keys = ['id', 'domain', 'name']
Example #24
Source File: adapters.py From django-invitations with GNU General Public License v3.0 | 5 votes |
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 #25
Source File: models.py From connect with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __str__(self): return _('Site configuration for {}'.format(self.site.name))
Example #26
Source File: test_commands.py From credentials with GNU Affero General Public License v3.0 | 5 votes |
def test_create_site(self): """ Verify the command creates Site and SiteConfiguration. """ site_domain = self.faker.domain_name() self._call_command( site_domain=site_domain, site_name=self.site_configuration.site.name ) site = Site.objects.get(domain=site_domain) self._check_site_configuration(site.siteconfiguration)
Example #27
Source File: sites.py From django-leonardo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, *args, **kwargs): super(SiteSelectField, self).__init__( label=_("Site"), queryset=Site.objects.all(), search_fields=('name', 'domain'), cls_name='sites.Site', empty_label='---', *args, **kwargs)
Example #28
Source File: signals.py From credentials with GNU Affero General Public License v3.0 | 5 votes |
def clear_site_cache(sender, **kwargs): # pylint: disable=unused-argument Site.objects.clear_cache() # Clear the Site cache to force a refresh of related SiteConfiguration objects
Example #29
Source File: profiles.py From GetTogether with BSD 2-Clause "Simplified" License | 5 votes |
def full_img_url(self): if self.card_img_url.startswith("http"): return self.card_img_url else: site = Site.objects.get(id=1) return "https://%s%s" % (site.domain, self.card_img_url)
Example #30
Source File: profiles.py From GetTogether with BSD 2-Clause "Simplified" License | 5 votes |
def get_full_url(self): site = Site.objects.get(id=1) return "https://%s%s" % (site.domain, self.get_absolute_url())