Python django.conf.settings.SITE_ID Examples

The following are 30 code examples for showing how to use django.conf.settings.SITE_ID(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: django-usersettings2   Author: mishbahr   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_current(self):
        """
        Returns the current ``UserSettings`` based on the SITE_ID in the
        project's settings. The ``UserSettings`` object is cached the first
        time it's retrieved from the database.
        """
        from django.conf import settings
        try:
            site_id = settings.SITE_ID
        except AttributeError:
            raise ImproperlyConfigured(
                'You\'re using the Django "sites framework" without having '
                'set the SITE_ID setting. Create a site in your database and '
                'set the SITE_ID setting to fix this error.')

        try:
            current_usersettings = USERSETTINGS_CACHE[site_id]
        except KeyError:
            current_usersettings = self.get(site_id=site_id)
            USERSETTINGS_CACHE[site_id] = current_usersettings
        return current_usersettings 
Example 2
Project: GTDWeb   Author: lanbing510   File: flatpages.py    License: GNU General Public License v2.0 6 votes vote down vote up
def render(self, context):
        if 'request' in context:
            site_pk = get_current_site(context['request']).pk
        else:
            site_pk = settings.SITE_ID
        flatpages = FlatPage.objects.filter(sites__id=site_pk)
        # If a prefix was specified, add a filter
        if self.starts_with:
            flatpages = flatpages.filter(
                url__startswith=self.starts_with.resolve(context))

        # If the provided user is not authenticated, or no user
        # was provided, filter the list to only public flatpages.
        if self.user:
            user = self.user.resolve(context)
            if not user.is_authenticated():
                flatpages = flatpages.filter(registration_required=False)
        else:
            flatpages = flatpages.filter(registration_required=False)

        context[self.context_name] = flatpages
        return '' 
Example 3
Project: GTDWeb   Author: lanbing510   File: models.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_current(self, request=None):
        """
        Returns the current Site based on the SITE_ID in the project's settings.
        If SITE_ID isn't defined, it returns the site with domain matching
        request.get_host(). The ``Site`` object is cached the first time it's
        retrieved from the database.
        """
        from django.conf import settings
        if getattr(settings, 'SITE_ID', ''):
            site_id = settings.SITE_ID
            return self._get_site_by_id(site_id)
        elif request:
            return self._get_site_by_request(request)

        raise ImproperlyConfigured(
            "You're using the Django \"sites framework\" without having "
            "set the SITE_ID setting. Create a site in your database and "
            "set the SITE_ID setting or pass a request to "
            "Site.objects.get_current() to fix this error."
        ) 
Example 4
Project: kobo-predict   Author: awemulya   File: tools.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def create_organization_object(org_name, creator, attrs={}):
    '''Creates an OrganizationProfile object without saving to the database'''
    name = attrs.get('name', org_name)
    first_name, last_name = _get_first_last_names(name)
    email = attrs.get('email', u'')
    new_user = User(username=org_name, first_name=first_name,
                    last_name=last_name, email=email, is_active=True)
    new_user.save()
    registration_profile = RegistrationProfile.objects.create_profile(new_user)
    if email:
        site = Site.objects.get(pk=settings.SITE_ID)
        registration_profile.send_activation_email(site)
    profile = OrganizationProfile(
        user=new_user, name=name, creator=creator,
        created_by=creator,
        city=attrs.get('city', u''),
        country=attrs.get('country', u''),
        organization=attrs.get('organization', u''),
        home_page=attrs.get('home_page', u''),
        twitter=attrs.get('twitter', u''))
    return profile 
Example 5
Project: DCRM   Author: 82Flex   File: managers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_queryset(self):
        """
        Return the first preferences object for the current site.
        If preferences do not exist create it.
        """
        queryset = super(SingletonManager, self).get_queryset()

        # Get current site
        current_site = None
        if getattr(settings, 'SITE_ID', None) is not None:
            current_site = Site.objects.get_current()

        # If site found limit queryset to site.
        if current_site is not None:
            queryset = queryset.filter(sites=settings.SITE_ID)

        try:
            queryset.get()
        except self.model.DoesNotExist:
            # Create object (for current site) if it doesn't exist.
            obj = self.model.objects.create()
            if current_site is not None:
                obj.sites.add(current_site)

        return queryset 
Example 6
Project: DCRM   Author: 82Flex   File: test_all.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_queryset(self):
        # Should return preferences without sites.
        # Shouldn't fail on duplicates.
        self.failIf(MyPreferences.singleton.get().sites.all(), "Without \
                SITE_ID should not have any preferences with sites.")

        # Should return preferences for current site.
        # Shouldn't fail on duplicates.
        settings.SITE_ID = 1
        current_site = Site.objects.get_current()
        obj = MyPreferences.singleton.get()
        self.failUnlessEqual(current_site, obj.sites.get(), "With SITE_ID \
                should have preferences for current site.")

        # Should return preferences for current site.
        # Shouldn't fail on duplicates.
        settings.SITE_ID = 2
        second_site, created = Site.objects.get_or_create(id=2)
        obj = MyPreferences.singleton.get()
        self.failUnlessEqual(second_site, obj.sites.get(), "With SITE_ID \
                should have preferences for current site.") 
Example 7
Project: bioforum   Author: reBiocoder   File: flatpages.py    License: MIT License 6 votes vote down vote up
def render(self, context):
        if 'request' in context:
            site_pk = get_current_site(context['request']).pk
        else:
            site_pk = settings.SITE_ID
        flatpages = FlatPage.objects.filter(sites__id=site_pk)
        # If a prefix was specified, add a filter
        if self.starts_with:
            flatpages = flatpages.filter(
                url__startswith=self.starts_with.resolve(context))

        # If the provided user is not authenticated, or no user
        # was provided, filter the list to only public flatpages.
        if self.user:
            user = self.user.resolve(context)
            if not user.is_authenticated:
                flatpages = flatpages.filter(registration_required=False)
        else:
            flatpages = flatpages.filter(registration_required=False)

        context[self.context_name] = flatpages
        return '' 
Example 8
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: flatpages.py    License: MIT License 6 votes vote down vote up
def render(self, context):
        if 'request' in context:
            site_pk = get_current_site(context['request']).pk
        else:
            site_pk = settings.SITE_ID
        flatpages = FlatPage.objects.filter(sites__id=site_pk)
        # If a prefix was specified, add a filter
        if self.starts_with:
            flatpages = flatpages.filter(
                url__startswith=self.starts_with.resolve(context))

        # If the provided user is not authenticated, or no user
        # was provided, filter the list to only public flatpages.
        if self.user:
            user = self.user.resolve(context)
            if not user.is_authenticated:
                flatpages = flatpages.filter(registration_required=False)
        else:
            flatpages = flatpages.filter(registration_required=False)

        context[self.context_name] = flatpages
        return '' 
Example 9
Project: yournextrepresentative   Author: mysociety   File: settings.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_form_kwargs(self):
        kwargs = super(SettingsView, self).get_form_kwargs()
        # We're getting the current site settings in such a way as to
        # avoid using any of the convenience methods that return the
        # cached current UserSettings object, since is_valid may
        # subsequently update the object we set here.  (is_valid
        # doesn't save it to the database, but because the cached
        # object is updated, it still means that the object returned
        # by those conveninence method, including the
        # self.request.usersettings attribute set by the middleware,
        # may not be in sync with the database any more.
        kwargs['instance'], _ = SiteSettings.objects.get_or_create(
            site_id=settings.SITE_ID,
            defaults={'user': self.request.user}
        )
        return kwargs 
Example 10
Project: openhgsenti   Author: drexly   File: flatpages.py    License: Apache License 2.0 6 votes vote down vote up
def render(self, context):
        if 'request' in context:
            site_pk = get_current_site(context['request']).pk
        else:
            site_pk = settings.SITE_ID
        flatpages = FlatPage.objects.filter(sites__id=site_pk)
        # If a prefix was specified, add a filter
        if self.starts_with:
            flatpages = flatpages.filter(
                url__startswith=self.starts_with.resolve(context))

        # If the provided user is not authenticated, or no user
        # was provided, filter the list to only public flatpages.
        if self.user:
            user = self.user.resolve(context)
            if not user.is_authenticated():
                flatpages = flatpages.filter(registration_required=False)
        else:
            flatpages = flatpages.filter(registration_required=False)

        context[self.context_name] = flatpages
        return '' 
Example 11
Project: openhgsenti   Author: drexly   File: models.py    License: Apache License 2.0 6 votes vote down vote up
def get_current(self, request=None):
        """
        Returns the current Site based on the SITE_ID in the project's settings.
        If SITE_ID isn't defined, it returns the site with domain matching
        request.get_host(). The ``Site`` object is cached the first time it's
        retrieved from the database.
        """
        from django.conf import settings
        if getattr(settings, 'SITE_ID', ''):
            site_id = settings.SITE_ID
            return self._get_site_by_id(site_id)
        elif request:
            return self._get_site_by_request(request)

        raise ImproperlyConfigured(
            "You're using the Django \"sites framework\" without having "
            "set the SITE_ID setting. Create a site in your database and "
            "set the SITE_ID setting or pass a request to "
            "Site.objects.get_current() to fix this error."
        ) 
Example 12
Project: python2017   Author: bpgc-cte   File: flatpages.py    License: MIT License 6 votes vote down vote up
def render(self, context):
        if 'request' in context:
            site_pk = get_current_site(context['request']).pk
        else:
            site_pk = settings.SITE_ID
        flatpages = FlatPage.objects.filter(sites__id=site_pk)
        # If a prefix was specified, add a filter
        if self.starts_with:
            flatpages = flatpages.filter(
                url__startswith=self.starts_with.resolve(context))

        # If the provided user is not authenticated, or no user
        # was provided, filter the list to only public flatpages.
        if self.user:
            user = self.user.resolve(context)
            if not user.is_authenticated:
                flatpages = flatpages.filter(registration_required=False)
        else:
            flatpages = flatpages.filter(registration_required=False)

        context[self.context_name] = flatpages
        return '' 
Example 13
Project: promgen   Author: line   File: checks.py    License: MIT License 6 votes vote down vote up
def sites(app_configs, **kwargs):
    if models.Site.objects.count() == 0:
        yield checks.Warning(
            "Site not configured",
            hint="Missing django site configuration",
            id="promgen.W006",
        )

    for site in models.Site.objects.filter(
        pk=settings.SITE_ID, domain__in=["example.com"]
    ):
        yield checks.Warning(
            "Promgen is configured to example domain",
            obj=site,
            hint="Please update from admin page /admin/",
            id="promgen.W007",
        )


# See notes in bootstrap.py
# @custom.register(checks.Tags.models) 
Example 14
Project: figures   Author: appsembler   File: models.py    License: MIT License 5 votes vote down vote up
def default_site():
    """
    Wrapper aroung `django.conf.settings.SITE_ID` so we do not have to create a
    new migration if we change how we get the default site ID
    """
    return settings.SITE_ID 
Example 15
Project: figures   Author: appsembler   File: sites.py    License: MIT License 5 votes vote down vote up
def default_site():
    """Returns the default site instance if Django settings defines SITE_ID, else None

    Tech debt note: Open edX monkeypatches django.contrib.sites to override
    behavior for getting the current site.
    """
    if getattr(settings, 'SITE_ID', ''):
        return Site.objects.get(pk=settings.SITE_ID)

    return None 
Example 16
Project: figures   Author: appsembler   File: sites.py    License: MIT License 5 votes vote down vote up
def get_site_for_course(course_id):
    """
    Given a course, return the related site or None

    For standalone mode, will always return the site
    For multisite mode, will return the site if there is a mapping between the
    course and the site. Otherwise `None` is returned

    # Implementation notes

    There should be only one organization per course.
    TODO: Figure out how we want to handle ``DoesNotExist``
    whether to let it raise back up raw or handle with a custom exception
    """
    if figures.helpers.is_multisite():
        org_courses = organizations.models.OrganizationCourse.objects.filter(
            course_id=str(course_id))
        if org_courses:
            # Keep until this assumption analyzed
            msg = 'Multiple orgs found for course: {}'
            assert org_courses.count() == 1, msg.format(course_id)
            first_org = org_courses.first().organization
            if hasattr(first_org, 'sites'):
                msg = 'Must have one and only one site. Org is "{}"'
                assert first_org.sites.count() == 1, msg.format(first_org.name)
                site = first_org.sites.first()
            else:
                site = None
        else:
            # We don't want to make assumptions of who our consumers are
            # TODO: handle no organizations found for the course
            site = None
    else:
        # Operating in single site / standalone mode, return the default site
        site = Site.objects.get(id=settings.SITE_ID)
    return site 
Example 17
def setUp(self):
        Site.objects.get_or_create(id=settings.SITE_ID, domain='example.com', name='example.com')
        self.usersettings_model.objects.create(**self.usersettings_data) 
Example 18
def test_request(self):
        """ Makes sure that the request has correct `usersettings` attribute. """
        middleware = CurrentUserSettingsMiddleware()
        request = HttpRequest()
        middleware.process_request(request)
        self.assertEqual(request.usersettings.site.id, settings.SITE_ID) 
Example 19
def setUp(self):
        Site.objects.get_or_create(id=settings.SITE_ID, domain='example.com', name='example.com')
        self.usersettings_model.objects.create(**self.usersettings_data) 
Example 20
Project: django-usersettings2   Author: mishbahr   File: test_models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        Site.objects.get_or_create(id=settings.SITE_ID, domain='example.com', name='example.com') 
Example 21
Project: django-usersettings2   Author: mishbahr   File: test_admin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_save_model_saves_logged_in_user(self):
        self.settings_admin.save_model(self.request, self.obj, form=None, change=False)
        usersettings = get_usersettings_model().objects.get(site_id=settings.SITE_ID)
        self.assertEqual(usersettings.user, self.user) 
Example 22
Project: django-usersettings2   Author: mishbahr   File: test_admin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_chagelist_view_redirects_to_add_view(self):
        """
        We have 1 site in database, we should redirect to add view,
        """
        # we delete the object created at setUp()
        self.obj.delete()

        add_url = '%s?site_id=%s' % (
            reverse('admin:%s_%s_add' % self.get_model_info()),
            settings.SITE_ID)
        # if we try to access the changelist, it should redirect to add view
        changelist_url = reverse('admin:%s_%s_changelist' % self.get_model_info())
        resp = self.client.get(changelist_url)
        self.assertRedirects(resp, add_url) 
Example 23
Project: django-usersettings2   Author: mishbahr   File: test_admin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_view_redirects_to_changeview_for_existing_usersettings(self):
        add_url = '%s?site_id=%s' % (
            reverse('admin:%s_%s_add' % self.get_model_info()),
            settings.SITE_ID)
        change_url = reverse('admin:%s_%s_change' % self.get_model_info(), args=(self.obj.pk,))
        resp = self.client.get(add_url)
        self.assertRedirects(resp, change_url) 
Example 24
def setUp(self):
        Site.objects.get_or_create(id=settings.SITE_ID, domain='example.com', name='example.com')
        self.usersettings_model.objects.create(**self.usersettings_data) 
Example 25
Project: GTDWeb   Author: lanbing510   File: managers.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_queryset(self):
        return super(CurrentSiteManager, self).get_queryset().filter(
            **{self._get_field_name() + '__id': settings.SITE_ID}) 
Example 26
Project: readux   Author: ecds   File: 0003_set_site_domain_and_name.py    License: MIT License 5 votes vote down vote up
def update_site_forward(apps, schema_editor):
    """Set site domain and name."""
    Site = apps.get_model("sites", "Site")
    Site.objects.update_or_create(
        id=settings.SITE_ID,
        defaults={
            "domain": "readux.ecds.emory.edu",
            "name": "Readux",
        },
    ) 
Example 27
Project: readux   Author: ecds   File: 0003_set_site_domain_and_name.py    License: MIT License 5 votes vote down vote up
def update_site_backward(apps, schema_editor):
    """Revert site domain and name to default."""
    Site = apps.get_model("sites", "Site")
    Site.objects.update_or_create(
        id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"}
    ) 
Example 28
Project: kobo-predict   Author: awemulya   File: user_profile_serializer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create(self, validated_data):
        user = validated_data.get('user', {})
        username = user.get('username', None)
        password = user.get('password', None)
        email = user.get('email', None)

        site = Site.objects.get(pk=settings.SITE_ID)
        new_user = RegistrationProfile.objects.create_inactive_user(
            site,
            username=username,
            password=password,
            email=email,
            send_email=True)
        new_user.is_active = True
        new_user.save()

        created_by = self.context['request'].user
        created_by = None if created_by.is_anonymous() else created_by
        profile = UserProfile.objects.create(
            user=new_user, name=validated_data.get('name', u''),
            created_by=created_by,
            city=validated_data.get('city', u''),
            country=validated_data.get('country', u''),
            organization=validated_data.get('organization', u''),
            home_page=validated_data.get('home_page', u''),
            twitter=validated_data.get('twitter', u''))

        return profile 
Example 29
def test_site_name(self):
        context = site_name(None)
        self.assertEqual(context, {'SITE_NAME': 'example.com'})
        restore_site_id = settings.SITE_ID
        settings.SITE_ID = 100
        context = site_name(None)
        self.assertEqual(context, {'SITE_NAME': 'example.org'})
        settings.SITE_ID = restore_site_id 
Example 30
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _html_submission_response(request, instance):
    data = {}
    data['username'] = instance.xform.user.username
    data['id_string'] = instance.xform.id_string
    data['domain'] = Site.objects.get(id=settings.SITE_ID).domain

    return render(request, "submission.html", data)