Ejemplo n.º 1
0
def checks(app_configs, **kwargs):  # noqa
    errors = []

    if not apps.is_installed('django.contrib.admin'):  # pragma: no cover
        errors.append(Error(
            'django.contrib.admin not found',
            hint="Put 'django.contrib.admin' in your INSTALLED_APPS setting",
            id='djangobmf.E001',
        ))

    if not apps.is_installed('django.contrib.contenttypes'):  # pragma: no cover
        errors.append(Error(
            'django.contrib.contenttypes not found',
            hint="Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting",
            id='djangobmf.E002',
        ))

    if 'django.contrib.auth.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS:  # pragma: no cover
        errors.append(Error(
            'django.contrib.auth.context_processors not found',
            hint="Put 'django.contrib.auth.context_processors' in your TEMPLATE_CONTEXT_PROCESSORS setting",
            id='djangobmf.E003',
        ))

    return errors
Ejemplo n.º 2
0
    def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that admin and contenttypes apps are
        installed, as well as the auth context processor.
        """
        if not apps.is_installed('django.contrib.admin'):
            raise ImproperlyConfigured(
                "Put 'django.contrib.admin' in your INSTALLED_APPS "
                "setting in order to use the admin application.")
        if not apps.is_installed('django.contrib.contenttypes'):
            raise ImproperlyConfigured(
                "Put 'django.contrib.contenttypes' in your INSTALLED_APPS "
                "setting in order to use the admin application.")
        try:
            default_template_engine = Engine.get_default()
        except ImproperlyConfigured:
            # Skip the check if the user has a non-trivial TEMPLATES setting
            pass
        else:
            if ('django.contrib.auth.context_processors.auth'
                    not in default_template_engine.context_processors):
                raise ImproperlyConfigured(
                    "Enable 'django.contrib.auth.context_processors.auth' "
                    "in your TEMPLATES setting in order to use the admin "
                    "application.")
Ejemplo n.º 3
0
    def _validate(self):
        """
        :return:
        """
        errors = []
        if not apps.is_installed(HACS_APP_NAME):
            errors.append(_("%s need to be added into settings.INSTALLED_APPS" % HACS_APP_NAME))

        if not apps.is_installed('django.contrib.contenttypes'):
            errors.append(_("django.contrib.contenttypes need to be added into settings.INSTALLED_APPS"))

        if not apps.is_installed('django.contrib.sites'):
            errors.append(_("django.contrib.sites need to be added into settings.INSTALLED_APPS"))

        try:
            site_middleware_position = \
                settings.MIDDLEWARE_CLASSES.index('django.contrib.sites.middleware.CurrentSiteMiddleware')
        except ValueError:
            errors.append(_("django.contrib.sites.middleware.CurrentSiteMiddleware need to be "
                            "added into settings.MIDDLEWARE_CLASSES"))
        else:
            if site_middleware_position > settings.MIDDLEWARE_CLASSES.index(self.name):
                errors.append(_('django.contrib.sites.middleware.CurrentSiteMiddleware\'s position should be before ' +
                                self.name))
        if errors:
            raise ImproperlyConfigured(_("Please fix: %s" % ' | '.join(errors)))

        return True
Ejemplo n.º 4
0
    def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that admin and contenttypes apps are
        installed, as well as the auth context processor.
        """
        if not apps.is_installed('django.contrib.admin'):
            raise ImproperlyConfigured(
                "Put 'django.contrib.admin' in your INSTALLED_APPS "
                "setting in order to use the admin application.")
        if not apps.is_installed('django.contrib.contenttypes'):
            raise ImproperlyConfigured(
                "Put 'django.contrib.contenttypes' in your INSTALLED_APPS "
                "setting in order to use the admin application.")
        try:
            default_template_engine = Engine.get_default()
        except Exception:
            # Skip this non-critical check:
            # 1. if the user has a non-trivial TEMPLATES setting and Django
            #    can't find a default template engine
            # 2. if anything goes wrong while loading template engines, in
            #    order to avoid raising an exception from a confusing location
            # Catching ImproperlyConfigured suffices for 1. but 2. requires
            # catching all exceptions.
            pass
        else:
            if ('django.contrib.auth.context_processors.auth'
                    not in default_template_engine.context_processors):
                raise ImproperlyConfigured(
                    "Enable 'django.contrib.auth.context_processors.auth' "
                    "in your TEMPLATES setting in order to use the admin "
                    "application.")
Ejemplo n.º 5
0
 def test_is_installed(self):
     """
     Tests apps.is_installed().
     """
     self.assertTrue(apps.is_installed("django.contrib.admin"))
     self.assertTrue(apps.is_installed("django.contrib.auth"))
     self.assertTrue(apps.is_installed("django.contrib.staticfiles"))
     self.assertFalse(apps.is_installed("django.contrib.webdesign"))
Ejemplo n.º 6
0
 def test_is_installed(self):
     """
     Tests apps.is_installed().
     """
     self.assertTrue(apps.is_installed('django.contrib.admin'))
     self.assertTrue(apps.is_installed('django.contrib.auth'))
     self.assertTrue(apps.is_installed('django.contrib.staticfiles'))
     self.assertFalse(apps.is_installed('django.contrib.admindocs'))
Ejemplo n.º 7
0
    def ready(self):
        # Install cache purging signal handlers
        if getattr(settings, 'WAGTAILAPI_USE_FRONTENDCACHE', False):
            if apps.is_installed('wagtail.contrib.wagtailfrontendcache'):
                from wagtail.contrib.wagtailapi.signal_handlers import register_signal_handlers
                register_signal_handlers()
            else:
                raise ImproperlyConfigured("The setting 'WAGTAILAPI_USE_FRONTENDCACHE' is True but 'wagtail.contrib.wagtailfrontendcache' is not in INSTALLED_APPS.")

        if not apps.is_installed('rest_framework'):
            warnings.warn(
                "The 'wagtailapi' module now requires 'rest_framework' to be installed. "
                "Please add 'rest_framework' to INSTALLED_APPS.",
                RemovedInWagtail14Warning)
Ejemplo n.º 8
0
    def populate(self):
        if (
            self.request.user.has_perm('filer.change_folder') or self.request.user.has_perm('core.change_emailtemplate') or
            (apps.is_installed('djangocms_forms') and self.request.user.has_perm('djangocms_forms.export_formsubmission'))
        ):
            menu = self.toolbar.get_or_create_menu('core-content',_('Content'))

        if self.request.user.has_perm('filer.change_folder'):
            menu.add_link_item(_('Manage Uploaded Files'), reverse('admin:filer_folder_changelist'))

        if self.request.user.has_perm('core.change_emailtemplate'):
            menu.add_link_item(_('Manage Email Templates'), reverse('admin:core_emailtemplate_changelist'))

        if apps.is_installed('djangocms_forms') and self.request.user.has_perm('djangocms_forms.export_formsubmission'):
            menu.add_link_item(_('View/Export Survey Responses'), reverse('admin:djangocms_forms_formsubmission_changelist'))
Ejemplo n.º 9
0
def get_cart(request):
    """Get the current cart - if the cart app is installed, and user is logged
       in, return a db cart (which may be an unsaved instance). Otherwise,
       return a session cart.

       If there's items in the session_cart, merge them into the db cart.
    """
    session_cart = SessionCart(request)

    if apps.is_installed('shoptools.cart') and request.user.is_authenticated:
        # django doesn't like this to be imported at compile-time if the app is
        # not installed
        from .models import SavedCart

        try:
            cart = SavedCart.objects.get(user=request.user)
        except SavedCart.DoesNotExist:
            cart = SavedCart(user=request.user)

        cart.set_request(request)

        # merge session cart, if it exists
        if session_cart.count():
            if not cart.pk:
                cart.save()
            session_cart.save_to(cart)
            session_cart.clear()
        return cart

    return session_cart
Ejemplo n.º 10
0
    def to_representation(self, instance):
        # if self.context.get('extended_json'):
        #     self.fields['json'] = V1InstanceSerializer(source='extended_json')

        representation = super(BadgeInstanceSerializerV1, self).to_representation(instance)
        representation['json'] = instance.get_json(obi_version="1_1", use_canonical_id=True)
        if self.context.get('include_issuer', False):
            representation['issuer'] = IssuerSerializerV1(instance.cached_badgeclass.cached_issuer).data
        else:
            representation['issuer'] = OriginSetting.HTTP+reverse('issuer_json', kwargs={'entity_id': instance.cached_issuer.entity_id})
        if self.context.get('include_badge_class', False):
            representation['badge_class'] = BadgeClassSerializerV1(instance.cached_badgeclass, context=self.context).data
        else:
            representation['badge_class'] = OriginSetting.HTTP+reverse('badgeclass_json', kwargs={'entity_id': instance.cached_badgeclass.entity_id})

        representation['public_url'] = OriginSetting.HTTP+reverse('badgeinstance_json', kwargs={'entity_id': instance.entity_id})

        if apps.is_installed('badgebook'):
            try:
                from badgebook.models import BadgeObjectiveAward
                from badgebook.serializers import BadgeObjectiveAwardSerializer
                try:
                    award = BadgeObjectiveAward.cached.get(badge_instance_id=instance.id)
                except BadgeObjectiveAward.DoesNotExist:
                    representation['award'] = None
                else:
                    representation['award'] = BadgeObjectiveAwardSerializer(award).data
            except ImportError:
                pass

        return representation
Ejemplo n.º 11
0
    def send(self, sender: Event, **named) -> List[Tuple[Callable, Any]]:
        """
        Send signal from sender to all connected receivers that belong to
        plugins enabled for the given Event.

        sender is required to be an instance of ``pretix.base.models.Event``.
        """
        assert isinstance(sender, Event)

        responses = []
        if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
            return responses

        for receiver in self._live_receivers(sender):
            # Find the Django application this belongs to
            searchpath = receiver.__module__
            app = None
            mod = None
            while "." in searchpath:
                try:
                    if apps.is_installed(searchpath):
                        app = apps.get_app_config(searchpath.split(".")[-1])
                except LookupError:
                    pass
                searchpath, mod = searchpath.rsplit(".", 1)

            # Only fire receivers from active plugins and core modules
            if (searchpath, mod) in settings.CORE_MODULES or (app and app.name in sender.get_plugins()):
                if not hasattr(app, 'compatibility_errors') or not app.compatibility_errors:
                    response = receiver(signal=self, sender=sender, **named)
                    responses.append((receiver, response))
        return responses
Ejemplo n.º 12
0
    def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that admin and contenttypes apps are
        installed, as well as the auth context processor.
        """
        if not apps.is_installed('django.contrib.admin'):
            raise ImproperlyConfigured("Put 'django.contrib.admin' in "
                "your INSTALLED_APPS setting in order to use the admin application.")
        if not apps.is_installed('django.contrib.contenttypes'):
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                "your INSTALLED_APPS setting in order to use the admin application.")
        if 'django.contrib.auth.context_processors.auth' not in Engine.get_default().context_processors:
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
def is_installed(appname):
    # for old django-fluent compatibility
    if apps.apps_ready:
        return apps.is_installed(appname)
    else:
        logger.debug('''fluent_utils.django_compat.is_installed("%s") only checks settings.INSTALLED_APPS, Apps aren't loaded yet.''', appname)  # noqa
        return appname in settings.INSTALLED_APPS
Ejemplo n.º 14
0
    def get_context_data(self, **kwargs):
        context = super(PrivateCalendarView,self).get_context_data(**kwargs)

        context.update({
            'locations': Location.objects.all().order_by('status','name'),
            'rooms': Room.objects.all().order_by('location__status','location__name', 'name'),
            'publicFeed': reverse('calendarFeed'),
            'jsonPublicFeed': reverse('jsonCalendarFeed'),
            'jsonPrivateFeeds': {
                'privateEvents': reverse('jsonPrivateCalendarFeed'),
            }
        })

        feedKey = getattr(getattr(self.request.user,'staffmember',None),'feedKey',None)
        if feedKey:
            context.update({
                'privateFeeds': {
                    'ownPublicEvents': reverse('calendarFeed', args=(feedKey,)),
                    'privateEvents': reverse('privateCalendarFeed', args=(feedKey,)),
                },
            })
            context['jsonPrivateFeeds']['ownPublicEvents'] = reverse('jsonCalendarFeed', args=(feedKey,))

        if apps.is_installed('danceschool.private_lessons'):
            context['privateLessonAdminUrl'] = reverse('admin:private_lessons_privatelessonevent_changelist')
            context['jsonPrivateFeeds'].update({
                'privateLessons': reverse('jsonPrivateLessonFeed'),
                'ownPrivateLessons': reverse('jsonOwnPrivateLessonFeed'),
            })

        return context
Ejemplo n.º 15
0
def is_installed(module):
    try:
        from django.apps import apps

        return apps.is_installed(module)
    except ImportError:
        return module in settings.INSTALLED_APPS
Ejemplo n.º 16
0
    def get_urls(self, page=1, site=None, protocol=None):
        # Determine protocol
        if self.protocol is not None:
            protocol = self.protocol
        if protocol is None:
            protocol = 'http'

        # Determine domain
        if site is None:
            if django_apps.is_installed('django.contrib.sites'):
                Site = django_apps.get_model('sites.Site')
                try:
                    site = Site.objects.get_current()
                except Site.DoesNotExist:
                    pass
            if site is None:
                raise ImproperlyConfigured(
                    "To use sitemaps, either enable the sites framework or pass "
                    "a Site/RequestSite object in your view."
                )
        domain = site.domain

        if getattr(self, 'i18n', False):
            urls = []
            current_lang_code = translation.get_language()
            for lang_code, lang_name in settings.LANGUAGES:
                translation.activate(lang_code)
                urls += self._urls(page, protocol, domain)
            translation.activate(current_lang_code)
        else:
            urls = self._urls(page, protocol, domain)

        return urls
Ejemplo n.º 17
0
def ping_google(sitemap_url=None, ping_url=PING_URL):
    """
    Alerts Google that the sitemap for the current site has been updated.
    If sitemap_url is provided, it should be an absolute path to the sitemap
    for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this
    function will attempt to deduce it by using urls.reverse().
    """
    if sitemap_url is None:
        try:
            # First, try to get the "index" sitemap URL.
            sitemap_url = reverse('django.contrib.sitemaps.views.index')
        except NoReverseMatch:
            try:
                # Next, try for the "global" sitemap URL.
                sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
            except NoReverseMatch:
                pass

    if sitemap_url is None:
        raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")

    if not django_apps.is_installed('django.contrib.sites'):
        raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")
    Site = django_apps.get_model('sites.Site')
    current_site = Site.objects.get_current()
    url = "http://%s%s" % (current_site.domain, sitemap_url)
    params = urlencode({'sitemap': url})
    urlopen("%s?%s" % (ping_url, params))
Ejemplo n.º 18
0
    def test_can_issue_badge_if_authenticated(self):
        test_user = self.setup_user(authenticate=True)
        test_issuer = self.setup_issuer(owner=test_user)
        test_badgeclass = self.setup_badgeclass(issuer=test_issuer)

        assertion = {
            "email": "*****@*****.**",
            "create_notification": False
        }
        response = self.client.post('/v1/issuer/issuers/{issuer}/badges/{badge}/assertions'.format(
            issuer=test_issuer.entity_id,
            badge=test_badgeclass.entity_id
        ), assertion)
        self.assertEqual(response.status_code, 201)
        self.assertIn('slug', response.data)
        assertion_slug = response.data.get('slug')

        # assert that the BadgeInstance was published to and fetched from cache
        query_count = 1 if apps.is_installed('badgebook') else 0
        with self.assertNumQueries(query_count):
            response = self.client.get('/v1/issuer/issuers/{issuer}/badges/{badge}/assertions/{assertion}'.format(
                issuer=test_issuer.entity_id,
                badge=test_badgeclass.entity_id,
                assertion=assertion_slug))
            self.assertEqual(response.status_code, 200)
Ejemplo n.º 19
0
    def register(self, **cleaned_data):
        """
        Given a username, email address and password, register a new
        user account, which will initially be inactive.

        Along with the new ``User`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``User``, containing the activation key which
        will be used for this account.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """
        username, email, password = (cleaned_data["username"], cleaned_data["email"], cleaned_data["password1"])
        if apps.is_installed("django.contrib.sites"):
            site = Site.objects.get_current()
        else:
            site = RequestSite(self.request)
        new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site)
        signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request)
        return new_user
Ejemplo n.º 20
0
 def session(self):
     """Session as Lazy property: check that django.contrib.sessions is installed"""
     if not apps.is_installed('django.contrib.sessions'):
         raise EnvironmentError('Add django.contrib.sessions to the INSTALLED_APPS to use session')
     if not self._session:
         self._session = session_for_reply_channel(self.reply_channel)
     return self._session
Ejemplo n.º 21
0
 def __init__(self, *args, **kwargs):
     if not apps.is_installed('django.contrib.sites'):
         raise ImproperlyConfigured(
             'You cannot use RedirectFallbackMiddleware when '
             'django.contrib.sites is not installed.'
         )
     super(RedirectMiddleware, self).__init__(*args, **kwargs)
Ejemplo n.º 22
0
def fiduswriter_config_js(context):
    """
    Add Fidus Writer config variables to the window object in JavaScript.
    Usage::
        {% fiduswriter_config_js %}
    """
    if apps.is_installed('django.contrib.staticfiles'):
        from django.contrib.staticfiles.storage import staticfiles_storage
        static_url = staticfiles_storage.base_url
    else:
        static_url = PrefixNode.handle_simple("STATIC_URL")
    if 'WS_PORT' in settings.SERVER_INFO:
        ws_port = settings.SERVER_INFO['WS_PORT']
    else:
        ws_port = ''
    if 'WS_SERVER' in settings.SERVER_INFO:
        ws_server = settings.SERVER_INFO['WS_SERVER']
    else:
        ws_server = ''
    if 'user' in context:
        username = context['user'].get_username()
    else:
        username = ''
    return {
        'static_url': static_url,
        'ws_port': ws_port,
        'ws_server': ws_server,
        'username': username
    }
Ejemplo n.º 23
0
    def delete(self, *args, **kwargs):
        if self.recipient_count > 0:
            raise ProtectedError("Issuer can not be deleted because it has previously issued badges.", self)

        # remove any unused badgeclasses owned by issuer
        for bc in self.cached_badgeclasses():
            bc.delete()

        staff = self.cached_issuerstaff()
        ret = super(Issuer, self).delete(*args, **kwargs)

        # remove membership records
        for membership in staff:
            membership.delete(publish_issuer=False)

        if apps.is_installed('badgebook'):
            # badgebook shim
            try:
                from badgebook.models import LmsCourseInfo
                # update LmsCourseInfo's that were using this issuer as the default_issuer
                for course_info in LmsCourseInfo.objects.filter(default_issuer=self):
                    course_info.default_issuer = None
                    course_info.save()
            except ImportError:
                pass

        return ret
Ejemplo n.º 24
0
def is_installed(app_name):
    if django.VERSION[:2] < (1, 7):
        from django.db.models import get_apps
        return app_name in get_apps()
    else:
        from django.apps import apps
        return apps.is_installed(app_name)
Ejemplo n.º 25
0
    def run(self):

        try:
            self.common_setup()
            channel_layers = ChannelLayerManager()
            channel_layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)
            if self.serve_static and apps.is_installed('django.contrib.staticfiles'):
                channel_layer.router.check_default(http_consumer=StaticFilesConsumer())
            else:
                channel_layer.router.check_default()
            if self.n_threads == 1:
                self.worker = Worker(
                    channel_layer=channel_layer,
                    signal_handlers=False,
                )
            else:
                self.worker = WorkerGroup(
                    channel_layer=channel_layer,
                    signal_handlers=False,
                    n_threads=self.n_threads,
                )
            self.worker.ready()
            self.is_ready.set()
            self.worker.run()
        except Exception:
            self.is_ready.set()
            raise
Ejemplo n.º 26
0
    def to_representation(self, instance):
        if self.context.get('extended_json'):
            self.fields['json'] = V1InstanceSerializer(source='extended_json')

        representation = super(BadgeInstanceSerializer, self).to_representation(instance)
        if self.context.get('include_issuer', False):
            representation['issuer'] = IssuerSerializer(instance.cached_badgeclass.cached_issuer).data
        else:
            representation['issuer'] = settings.HTTP_ORIGIN+reverse('issuer_json', kwargs={'slug': instance.cached_issuer.slug})
        if self.context.get('include_badge_class', False):
            representation['badge_class'] = BadgeClassSerializer(instance.cached_badgeclass, context=self.context).data
        else:
            representation['badge_class'] = settings.HTTP_ORIGIN+reverse('badgeclass_json', kwargs={'slug': instance.cached_badgeclass.slug})

        if apps.is_installed('badgebook'):
            try:
                from badgebook.models import BadgeObjectiveAward
                from badgebook.serializers import BadgeObjectiveAwardSerializer
                try:
                    award = BadgeObjectiveAward.cached.get(badge_instance_id=instance.id)
                except BadgeObjectiveAward.DoesNotExist:
                    representation['award'] = None
                else:
                    representation['award'] = BadgeObjectiveAwardSerializer(award).data
            except ImportError:
                pass

        return representation
Ejemplo n.º 27
0
    def get_safe_session(self):
        """
        Here, we are duplicating the original Client._session code
        in order to allow conversion of the safe_cookie_data back
        to the raw session_id, if needed.  Since test code may
        access the session_id before it's actually converted,
        we use a try-except clause here to check both cases.
        """
        from django.apps import apps
        from django.conf import settings
        from importlib import import_module
        from .middleware import SafeCookieData, SafeCookieError, SafeSessionMiddleware

        if apps.is_installed('django.contrib.sessions'):
            engine = import_module(settings.SESSION_ENGINE)
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
            if cookie:
                session_id = cookie.value
                if using_safe_cookie_data(settings):
                    try:
                        session_id = SafeCookieData.parse(session_id).session_id
                    except SafeCookieError:
                        pass  # The safe cookie hasn't yet been created.
                return engine.SessionStore(session_id)
            else:
                session = engine.SessionStore()
                session.save()
                self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
                SafeSessionMiddleware.update_with_safe_session_cookie(self.cookies, user_id=None)
                return session
        return {}
Ejemplo n.º 28
0
 def __init__(self, get_response=None):
     if not apps.is_installed('django.contrib.sites'):
         raise ImproperlyConfigured(
             "You cannot use RedirectFallbackMiddleware when "
             "django.contrib.sites is not installed."
         )
     super().__init__(get_response)
Ejemplo n.º 29
0
 def add_arguments(self, parser):
     parser.add_argument('pattern', type=str, help='Pattern to search for')
     parser.add_argument('identifiers', nargs='*', type=str, help='Identifier of a model or field')
     parser.add_argument('--show-values', '-s', nargs='?', type=show_values_style, default='l',
                         help='Turn off showing matching values (default is any line containing a match), '
                         'or provide the mode "a" to show the entire field '
                         'or an integer to show that many characters either side of a match.')
     parser.add_argument('--ignore-case', '-i', action='store_true', help='Match case-insensitively')
     parser.add_argument('--find-text-fields', '-t', dest='field_type', action='append_const', const='TextField',
                         help='Search all TextField fields (and subclasses) on a model if no field is specified')
     parser.add_argument('--find-char-fields', '-c', dest='field_type', action='append_const', const='CharField',
                         help='Search all CharField fields (and subclasses) on a model if no field is specified')
     parser.add_argument('--find-fields', '-f', dest='field_type', action='append', type=str,
                         help='Search all fields of this type (and subclasses) on a model if no field is specified')
     parser.add_argument('--preset', '-p', help='The name of a preset configuration in DJANGO_GREPDB_PRESETS. '
                         'DJANGO_GREPDB_PRESETS should be a dict of dicts, with each config dict providing '
                         'default values for any number of parser args.')
     if apps.is_installed('django.contrib.admin'):
         parser.add_argument('--admin-links', '-l', dest='admin_hostname', nargs='*', default=['default'],
                             help='Generate admin links. Defaults to true, using http://localhost:8000/ as hostname. '
                             'Can be passed one or more hostnames to use instead. If DJANGO_GREPDB_SITES is a '
                             'dict defined in settings, the value of the "default" key will be used as default, '
                             'and keys from it can also be passed to use their values as hostnames. '
                             'Links can be disabled by using this argument without any values.')
     self.parser = parser
def run_as_django_behave(formatter_name, feature_names, scenario_n_options):
    """
    :param formatter_name: for "-f" argument
    :param feature_names: feature names or folders behave arguments
    :param scenario_n_options: list of ["-n", "scenario_name"]


    :return: True if launched as django-behave. Otherwise false and need to be launched as plain behave
    """
    if "DJANGO_SETTINGS_MODULE" not in os.environ:
        return False
    try:
        import django
        from django.core.management import ManagementUtility

        from behave_django import __version__  # To make sure version exists
        django.setup()
        from django.apps import apps

        if apps.is_installed("behave_django"):
            base = sys.argv[0]
            sys.argv = [base] + ["behave", "-f{0}".format(formatter_name)] + feature_names + scenario_n_options
            print("manage.py " + " ".join(sys.argv[1:]))
            ManagementUtility().execute()
            return True
    except ImportError:
        return False
Ejemplo n.º 31
0

class RemoteHostAdmin(admin.ModelAdmin):
    """
    Hides the private key field, which is not necessary for host keys
    """
    fields = [
        'nickname', 'administrator', 'host_name', 'port', 'key_type',
        'public_key', 'logo_img'
    ]


class CredentialForm(forms.ModelForm):
    class Meta:
        fields = '__all__'
        model = Credential
        widgets = {
            'password': forms.PasswordInput(),
        }


class CredentialAdmin(admin.ModelAdmin):
    form = CredentialForm


# Register the models with the admin
if apps.is_installed(PushToConfig.name):
    admin.site.register(RemoteHost, RemoteHostAdmin)
    admin.site.register(Credential, CredentialAdmin)
    admin.site.register(OAuthSSHCertSigningService)
Ejemplo n.º 32
0
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.apps import apps
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('cvat.apps.engine.urls')),
    path('django-rq/', include('django_rq.urls')),
]

if apps.is_installed('cvat.apps.dataset_repo'):
    urlpatterns.append(
        path('git/repository/', include('cvat.apps.dataset_repo.urls')))

if apps.is_installed('cvat.apps.log_viewer'):
    urlpatterns.append(path('analytics/',
                            include('cvat.apps.log_viewer.urls')))

if apps.is_installed('cvat.apps.lambda_manager'):
    urlpatterns.append(path('', include('cvat.apps.lambda_manager.urls')))

if apps.is_installed('cvat.apps.opencv'):
    urlpatterns.append(path('opencv/', include('cvat.apps.opencv.urls')))

if apps.is_installed('silk'):
    urlpatterns.append(path('profiler/', include('silk.urls')))
    def handle(self, *args, **options):  # NOQA
        if not apps.is_installed("field_permissions"):
            raise CommandError(
                'App "field_permissions" must be installed to use this command.'
            )

        from field_permissions.registry import field_permissions

        groups = {group.id: group for group in Group.objects.all()}
        permissions = {
            perm.codename: perm
            for perm in Permission.objects.all()
        }

        group_permissions = []
        all_field_permissions = []

        for model in field_permissions.get_models():
            model_name = model._meta.model_name

            # Find all the fields that the field permissions registry knows about
            perms = field_permissions.get_field_permissions_for_model(model)

            field_perms = {}
            for (codename, name) in sorted(perms):
                try:
                    all_field_permissions.append(permissions[codename])
                except KeyError:
                    raise CommandError(
                        '"{}" field permission is missing. Please run migrate to create '
                        'the missing permissions.'.format(codename))

                if codename.startswith('change_'):
                    continue

                field_name = codename.replace('view_{}_'.format(model_name),
                                              '')

                # Set field permissions to their default value
                if model_name in DEFAULT_FIELD_PERMS:
                    field_perms[field_name] = dict(
                        DEFAULT_FIELD_PERMS[model_name])

            # Customize field permissions for this model
            if model_name in CUSTOM_FIELD_PERMS:
                update(field_perms, CUSTOM_FIELD_PERMS[model_name])

            # Generate Group permissions for all of the fields and groups
            for field_name, group_perms in field_perms.items():
                for group_id, permission_type in group_perms.items():
                    if not permission_type:
                        continue

                    permission_name = '{}_{}_{}'.format(
                        permission_type, model_name, field_name)

                    group_permissions.append(
                        Group.permissions.through(
                            group=groups[group_id],
                            permission=permissions[permission_name]))

        # Delete existing field permissions from the pre-defined groups
        mvj_groups = [grp for grp in groups.values() if grp.id in range(1, 8)]
        Group.permissions.through.objects.filter(
            group__in=mvj_groups,
            permission__in=all_field_permissions).delete()

        # Save the desired field permissions for the groups
        Group.permissions.through.objects.bulk_create(group_permissions)
        for group_permission in group_permissions:
            self.stdout.write(
                'Added field permission "{}" for group "{}"'.format(
                    group_permission.permission.codename,
                    group_permission.group.name))
Ejemplo n.º 34
0
 def liveblog_enabled(self):
     return self.object.enable_liveblog and apps.is_installed(
         "djangocms_blog.liveblog")
Ejemplo n.º 35
0
            kwargs={
                'insecure': True,
            })
    ] + urlpatterns

# Serve pattern library view only in debug mode or if explicitly declared
if getattr(settings, 'DEBUG', True) or getattr(settings,
                                               'SERVE_PATTERN_LIBRARY', False):
    urlpatterns = [
        url(r'^component-library$',
            TemplateView.as_view(template_name='component-library.html'),
            name='component-library')
    ] + urlpatterns

# serve django debug toolbar if present
if settings.DEBUG and apps.is_installed('debug_toolbar'):
    try:
        import debug_toolbar
        urlpatterns = urlpatterns + [
            url(r'^__debug__/', include(debug_toolbar.urls)),
        ]
    except ImportError:
        pass

# protected assertion media files
urlpatterns.insert(
    0,
    url(r'^media/(?P<path>.*)$',
        serve_protected_document, {'document_root': settings.MEDIA_ROOT},
        name='serve_protected_document'),
)
Ejemplo n.º 36
0
 def __init__(self, get_response=None):
     if not apps.is_installed('django.contrib.sites'):
         raise ImproperlyConfigured(
             "You cannot use RedirectFallbackMiddleware when "
             "django.contrib.sites is not installed.")
     super(RedirectFallbackMiddleware, self).__init__(get_response)
Ejemplo n.º 37
0
 def has_image(self):
     return bool(self.profile_photo
                 or (apps.is_installed("allauth.socialaccount")
                     and SocialAccount.objects.filter(user_id=self.id)))
 def test_setup(self):
     assert apps.is_installed('rest_framework')
     assert hasattr(self.APIView, '_opentelemetry_patch')
Ejemplo n.º 39
0
    ),
    path("admin/hijack/", include("hijack.urls")),
    path("admin/", admin.site.urls),
    path(
        "reset/<uidb64>/<token>/",
        auth_views.PasswordResetConfirmView.as_view(),
        name="password_reset_confirm",
    ),
    path(
        "reset/done/",
        auth_views.PasswordResetCompleteView.as_view(),
        name="password_reset_complete",
    ),
    # auth backends
    path("adfs/", include("django_auth_adfs.urls")),
    # Simply show the master template.
    path("", TemplateView.as_view(template_name="master.html"), name="index"),
]

# NOTE: The staticfiles_urlpatterns also discovers static files (ie. no need to run collectstatic). Both the static
# folder and the media folder are only served via Django if DEBUG = True.
urlpatterns += staticfiles_urlpatterns() + static(
    settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG and apps.is_installed("debug_toolbar"):
    import debug_toolbar

    urlpatterns = [
        path("__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns
Ejemplo n.º 40
0
    def static(path):
        if apps.is_installed("django.contrib.staticfiles"):
            from django.contrib.staticfiles.storage import staticfiles_storage

            return staticfiles_storage.url(path)
        return _static(path)
Ejemplo n.º 41
0
def shortcut(request, content_type_id, object_id):
    """
    Redirect to an object's page based on a content-type ID and an object ID.
    """
    # Look up the object, making sure it's got a get_absolute_url() function.
    try:
        content_type = ContentType.objects.get(pk=content_type_id)
        if not content_type.model_class():
            raise http.Http404(
                _("Content type %(ct_id)s object has no associated model") %
                {'ct_id': content_type_id})
        obj = content_type.get_object_for_this_type(pk=object_id)
    except (ObjectDoesNotExist, ValueError):
        raise http.Http404(
            _("Content type %(ct_id)s object %(obj_id)s doesn't exist") % {
                'ct_id': content_type_id,
                'obj_id': object_id
            })

    try:
        get_absolute_url = obj.get_absolute_url
    except AttributeError:
        raise http.Http404(
            _("%(ct_name)s objects don't have a get_absolute_url() method") %
            {'ct_name': content_type.name})
    absurl = get_absolute_url()

    # Try to figure out the object's domain, so we can do a cross-site redirect
    # if necessary.

    # If the object actually defines a domain, we're done.
    if absurl.startswith(('http://', 'https://', '//')):
        return http.HttpResponseRedirect(absurl)

    # Otherwise, we need to introspect the object's relationships for a
    # relation to the Site object
    object_domain = None

    if apps.is_installed('django.contrib.sites'):
        Site = apps.get_model('sites.Site')

        opts = obj._meta

        # First, look for an many-to-many relationship to Site.
        for field in opts.many_to_many:
            if field.remote_field.model is Site:
                try:
                    # Caveat: In the case of multiple related Sites, this just
                    # selects the *first* one, which is arbitrary.
                    object_domain = getattr(obj, field.name).all()[0].domain
                except IndexError:
                    pass
                if object_domain is not None:
                    break

        # Next, look for a many-to-one relationship to Site.
        if object_domain is None:
            for field in obj._meta.fields:
                if field.remote_field and field.remote_field.model is Site:
                    try:
                        site = getattr(obj, field.name)
                    except Site.DoesNotExist:
                        continue
                    if site is not None:
                        object_domain = site.domain
                    if object_domain is not None:
                        break

        # Fall back to the current site (if possible).
        if object_domain is None:
            try:
                object_domain = Site.objects.get_current(request).domain
            except Site.DoesNotExist:
                pass

    else:
        # Fall back to the current request's site.
        object_domain = RequestSite(request).domain

    # If all that malarkey found an object domain, use it. Otherwise, fall back
    # to whatever get_absolute_url() returned.
    if object_domain is not None:
        protocol = request.scheme
        return http.HttpResponseRedirect('%s://%s%s' %
                                         (protocol, object_domain, absurl))
    else:
        return http.HttpResponseRedirect(absurl)
Ejemplo n.º 42
0
    #     The brick must be visible by all users ; we check permissions in the
    #     render to disabled only forbidden things.
    # permission = None

    def detailview_display(self, context):
        user = context['user']

        return self._render(
            self.get_template_context(
                context,
                EmailSignature.objects.filter(user=user),
                has_app_perm=user.has_perm('emails'),
            ))


if apps.is_installed('creme.crudity'):
    from creme.crudity.bricks import BaseWaitingActionsBrick
    from creme.crudity.utils import is_sandbox_by_user

    class _SynchronizationMailsBrick(BaseWaitingActionsBrick):
        dependencies = (EntityEmail, )
        order_by = '-reception_date'
        configurable = False

    class WaitingSynchronizationMailsBrick(_SynchronizationMailsBrick):
        id_ = _SynchronizationMailsBrick.generate_id(
            'emails', 'waiting_synchronisation')
        verbose_name = _('Incoming emails to treat')
        template_name = 'emails/bricks/synchronization.html'

        def detailview_display(self, context):
Ejemplo n.º 43
0
def is_installed(module):
    try:
        from django.apps import apps
        return apps.is_installed(module)
    except ImportError:
        return module in settings.INSTALLED_APPS
Ejemplo n.º 44
0
 def handle_simple(cls, path):
     if apps.is_installed('django.contrib.staticfiles'):
         from django.contrib.staticfiles.storage import staticfiles_storage
         return staticfiles_storage.url(path)
     else:
         return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path))
Ejemplo n.º 45
0
            "type": "password",
            "labelWidth": 220
        })
        fs[self.add_prefix('new_password2')].update({
            "type": "password",
            "labelWidth": 220
        })

        return [{
            'cols': [fs[self.add_prefix('new_password1')]]
        }, {
            'cols': [fs[self.add_prefix('new_password2')]]
        }]


if apps.is_installed("two_factor"):
    from two_factor.forms import (AuthenticationTokenForm, BackupTokenForm,
                                  DisableForm, MethodForm, TOTPDeviceForm,
                                  PhoneNumberForm, DeviceValidationForm,
                                  YubiKeyDeviceForm)
    from django_otp.forms import OTPAuthenticationFormMixin
    # ################################ Autenticazione a 2 fattori - django-two-factor-auth ################################
    AuthenticationForm.__bases__ = (WebixForm, )
    WebixAuthenticationAuthForm = type(
        str('WebixAuthenticationAuthForm'), (AuthenticationForm, ),
        {'get_fieldsets': FieldSetMixin.authenticationForm_get_fieldsets})

    AuthenticationTokenForm.__bases__ = (OTPAuthenticationFormMixin, WebixForm)
    WebixAuthenticationTokenForm = type(str('WebixAuthenticationTokenForm'),
                                        (AuthenticationTokenForm, ), {})
Ejemplo n.º 46
0
from django.apps import apps
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import LogoutView
from django.urls import path
from django.views.static import serve
from rest_framework import routers

from NEMO.models import ReservationItemType
from NEMO.views import abuse, accounts_and_projects, alerts, api, area_access, authentication, calendar, configuration_agenda, consumables, contact_staff, customization, email, feedback, get_projects, history, jumbotron, landing, maintenance, mobile, usage, news, qualifications, remote_work, resources, safety, sidebar, staff_charges, status_dashboard, tasks, tool_control, training, tutorials, users, buddy_system

logger = logging.getLogger(__name__)

if apps.is_installed("django.contrib.admin"):
    # Use our custom login page instead of Django's built-in one.
    admin.site.login = login_required(admin.site.login)

# REST API URLs
router = routers.DefaultRouter()
router.register(r'users', api.UserViewSet)
router.register(r'projects', api.ProjectViewSet)
router.register(r'accounts', api.AccountViewSet)
router.register(r'tools', api.ToolViewSet)
router.register(r'reservations', api.ReservationViewSet)
router.register(r'usage_events', api.UsageEventViewSet)
router.register(r'area_access_records', api.AreaAccessRecordViewSet)
router.register(r'tasks', api.TaskViewSet)
router.register(r'scheduled_outages', api.ScheduledOutageViewSet)
Ejemplo n.º 47
0
    def setUpClass(cls):
        super().setUpClass()

        if apps.is_installed('creme.tickets'):
            cls.ct = ContentType.objects.get_for_model(Ticket)
Ejemplo n.º 48
0
class HTTPSitemapTests(SitemapTestsBase):
    @ignore_warnings(category=RemovedInDjango110Warning)
    def test_simple_sitemap_index(self):
        "A simple sitemap index can be rendered"
        # The URL for views.sitemap in tests/urls/http.py has been updated
        # with a name but since reversing by Python path is tried first
        # before reversing by name and works since we're giving
        # name='django.contrib.sitemaps.views.sitemap', we need to silence
        # the erroneous warning until reversing by dotted path is removed.
        # The test will work without modification when it's removed.
        response = self.client.get('/simple/index.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>
</sitemapindex>
""" % self.base_url
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)

    @ignore_warnings(category=RemovedInDjango110Warning)
    @override_settings(TEMPLATES=[{
        'BACKEND':
        'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(os.path.dirname(upath(__file__)), 'templates')],
    }])
    def test_simple_sitemap_custom_index(self):
        "A simple sitemap index can be rendered with a custom template"
        # The URL for views.sitemap in tests/urls/http.py has been updated
        # with a name but since reversing by Python path is tried first
        # before reversing by name and works since we're giving
        # name='django.contrib.sitemaps.views.sitemap', we need to silence
        # the erroneous warning until reversing by dotted path is removed.
        # The test will work without modification when it's removed.
        response = self.client.get('/simple/custom-index.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a customised template -->
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>
</sitemapindex>
""" % self.base_url
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)

    def test_simple_sitemap_section(self):
        "A simple sitemap section can be rendered"
        response = self.client.get('/simple/sitemap-simple.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset>
""" % (self.base_url, date.today())
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)

    def test_simple_sitemap(self):
        "A simple sitemap can be rendered"
        response = self.client.get('/simple/sitemap.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset>
""" % (self.base_url, date.today())
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)

    @override_settings(TEMPLATES=[{
        'BACKEND':
        'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(os.path.dirname(upath(__file__)), 'templates')],
    }])
    def test_simple_custom_sitemap(self):
        "A simple sitemap can be rendered with a custom template"
        response = self.client.get('/simple/custom-sitemap.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a customised template -->
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset>
""" % (self.base_url, date.today())
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)

    def test_sitemap_last_modified(self):
        "Tests that Last-Modified header is set correctly"
        response = self.client.get('/lastmod/sitemap.xml')
        self.assertEqual(response['Last-Modified'],
                         'Wed, 13 Mar 2013 10:00:00 GMT')

    def test_sitemap_last_modified_date(self):
        """
        The Last-Modified header should be support dates (without time).
        """
        response = self.client.get('/lastmod/date-sitemap.xml')
        self.assertEqual(response['Last-Modified'],
                         'Wed, 13 Mar 2013 00:00:00 GMT')

    def test_sitemap_last_modified_tz(self):
        """
        The Last-Modified header should be converted from timezone aware dates
        to GMT.
        """
        response = self.client.get('/lastmod/tz-sitemap.xml')
        self.assertEqual(response['Last-Modified'],
                         'Wed, 13 Mar 2013 15:00:00 GMT')

    def test_sitemap_last_modified_missing(self):
        "Tests that Last-Modified header is missing when sitemap has no lastmod"
        response = self.client.get('/generic/sitemap.xml')
        self.assertFalse(response.has_header('Last-Modified'))

    def test_sitemap_last_modified_mixed(self):
        "Tests that Last-Modified header is omitted when lastmod not on all items"
        response = self.client.get('/lastmod-mixed/sitemap.xml')
        self.assertFalse(response.has_header('Last-Modified'))

    @skipUnless(settings.USE_I18N, "Internationalization is not enabled")
    @override_settings(USE_L10N=True)
    def test_localized_priority(self):
        "The priority value should not be localized (Refs #14164)"
        activate('fr')
        self.assertEqual('0,3', localize(0.3))

        # Retrieve the sitemap. Check that priorities
        # haven't been rendered in localized format
        response = self.client.get('/simple/sitemap.xml')
        self.assertContains(response, '<priority>0.5</priority>')
        self.assertContains(response, '<lastmod>%s</lastmod>' % date.today())
        deactivate()

    @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'})
    def test_requestsite_sitemap(self):
        # Make sure hitting the flatpages sitemap without the sites framework
        # installed doesn't raise an exception.
        response = self.client.get('/simple/sitemap.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>http://testserver/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset>
""" % date.today()
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)

    @skipUnless(apps.is_installed('django.contrib.sites'),
                "django.contrib.sites app not installed.")
    def test_sitemap_get_urls_no_site_1(self):
        """
        Check we get ImproperlyConfigured if we don't pass a site object to
        Sitemap.get_urls and no Site objects exist
        """
        Site.objects.all().delete()
        self.assertRaises(ImproperlyConfigured, Sitemap().get_urls)

    @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'})
    def test_sitemap_get_urls_no_site_2(self):
        """
        Check we get ImproperlyConfigured when we don't pass a site object to
        Sitemap.get_urls if Site objects exists, but the sites framework is not
        actually installed.
        """
        self.assertRaises(ImproperlyConfigured, Sitemap().get_urls)

    def test_sitemap_item(self):
        """
        Check to make sure that the raw item is included with each
        Sitemap.get_url() url result.
        """
        test_sitemap = GenericSitemap({'queryset': TestModel.objects.all()})

        def is_testmodel(url):
            return isinstance(url['item'], TestModel)

        item_in_url_info = all(map(is_testmodel, test_sitemap.get_urls()))
        self.assertTrue(item_in_url_info)

    def test_cached_sitemap_index(self):
        """
        Check that a cached sitemap index can be rendered (#2713).
        """
        response = self.client.get('/cached/index.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/cached/sitemap-simple.xml</loc></sitemap>
</sitemapindex>
""" % self.base_url
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)

    @ignore_warnings(category=RemovedInDjango110Warning)
    def test_x_robots_sitemap(self):
        # The URL for views.sitemap in tests/urls/http.py has been updated
        # with a name but since reversing by Python path is tried first
        # before reversing by name and works since we're giving
        # name='django.contrib.sitemaps.views.sitemap', we need to silence
        # the erroneous warning until reversing by dotted path is removed.
        # The test will work without modification when it's removed.
        response = self.client.get('/simple/index.xml')
        self.assertEqual(response['X-Robots-Tag'], 'noindex, noodp, noarchive')

        response = self.client.get('/simple/sitemap.xml')
        self.assertEqual(response['X-Robots-Tag'], 'noindex, noodp, noarchive')

    def test_empty_sitemap(self):
        response = self.client.get('/empty/sitemap.xml')
        self.assertEqual(response.status_code, 200)

    @override_settings(LANGUAGES=(('en', 'English'), ('pt', 'Portuguese')))
    def test_simple_i18nsitemap_index(self):
        "A simple i18n sitemap index can be rendered"
        response = self.client.get('/simple/i18n.xml')
        expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>{0}/en/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url><url><loc>{0}/pt/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset>
""".format(self.base_url, self.i18n_model.pk)
        self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
Ejemplo n.º 49
0
    # This is a public view of the courses we have enabled
    path('api/v1/courses_enabled/',
         cache_page(settings.CLIENT_CACHE_TIME)(views.courses_enabled),
         name='courses_enabled'),

    # PUT/POST access patterns
    path('api/v1/courses/<int:course_id>/set_user_default_selection/',
         login_required(views.update_user_default_selection_for_views),
         name='update_user_default_selection_for_views'),
    path('api/v1/courses/<int:course_id>/update_info/',
         login_required(views.update_course_info),
         name='update_course_info'),
    path('su/', include('django_su.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if apps.is_installed('djangosaml2'):
    from djangosaml2.views import echo_attributes
    urlpatterns += (
        # This URL *does* need a trailing slash because of the include
        path('accounts/', include('djangosaml2.urls')),
        path('samltest/', login_required(echo_attributes)),
        # Override auth_logout from djangosaml2 and registration for consistency
        # Note the absence of a trailing slash; adding one breaks the SAML implementation.
        path('accounts/logout', views.logout, name='auth_logout'))

if settings.STUDENT_DASHBOARD_LTI:
    from . import lti_new
    urlpatterns += (
        path('lti/login/', lti_new.login, name='login'),
        path('lti/launch/', lti_new.launch, name='launch'),
        path('lti/jwks/', lti_new.get_jwks, name='get_jwks'),
Ejemplo n.º 50
0
    def authenticate(self, username=None, password=None):
        # authenticate
        if not JaneusBackend.login(username, password):
            return None

        # get LDAP attributes and groups of user
        attrs, groups = JaneusBackend.get_attrs_groups(username)
        groups = groups or []
        if len(groups) == 0:
            return None

        # find all roles of this user, if any
        roles = JaneusRole.objects.filter(role__in=groups)
        if len(roles) == 0:
            return None

        # determine the sites user has any access to
        if len(roles.filter(sites=None)) > 0:
            # user has access to all sites
            sites = Site.objects.all()
        else:
            # user has access to some sites
            sites_query = '{}__in'.format(
                JaneusRole._meta.get_field('sites').related_query_name())
            sites = Site.objects.filter(**{sites_query: roles})

        # find current site
        site = JaneusBackend.current_site_id()
        if site is not None:
            # check if user gets access
            if site not in [s.pk for s in sites]:
                return None
            # restrict roles to roles of the current site
            roles = roles.filter(Q(sites=None) | Q(sites__id__exact=site))

        # get or create JaneusUser object
        try:
            juser = JaneusUser.objects.get(uid=username)
        except JaneusUser.DoesNotExist:
            juser = JaneusUser(uid=username, user=None)
            juser.save()

        # get or create User
        if juser.user is None:
            model = get_user_model()
            username_field = getattr(model, 'USERNAME_FIELD', 'username')

            kwargs = {
                username_field + '__iexact': username,
                'defaults': {
                    username_field: username.lower()
                }
            }

            juser.user, created = model.objects.get_or_create(**kwargs)
            if created:
                # created, so set active, staff, unusable password
                juser.user.set_unusable_password()
                juser.user.is_active = True
                juser.user.is_staff = True
                juser.user.save()
            juser.save()

        # now update attributes of user
        if attrs is not None:
            setattr(juser.user, 'last_name', attrs['sn'][0])
            setattr(juser.user, 'email', attrs['mail'][0])
            juser.user.save()

        # Mezzanine support
        if apps.is_installed('mezzanine.core'):
            from mezzanine.core.models import SitePermission
            sp, created = SitePermission.objects.get_or_create(user=juser.user)
            # if set in the settings, clear sp.sites before adding site permissions
            if getattr(settings, 'JANEUS_MEZZANINE_CLEAR_SITEPERMISSION',
                       False):
                sp.sites.clear()
            sp.sites.add(*sites)
            sp.save()

        # add information to User object
        juser.user._janeus_user = juser
        juser.user._janeus_groups = groups
        juser.user._janeus_roles = roles  # all roles of current site
        juser.user._janeus_sites = sites  # all sites with access

        return juser.user
Ejemplo n.º 51
0
    def handle(self, *args, **options):
        if options["force"]:
            force = True
        else:
            force = False
        start = int(round(time.time()))
        npm_install = install_npm(force, self.stdout)
        js_paths = finders.find("js/", True)
        # Remove paths inside of collection dir
        js_paths = [
            x for x in js_paths if not x.startswith(settings.STATIC_ROOT)
        ]

        transpile_path = os.path.join(PROJECT_PATH, "static-transpile")

        if os.path.exists(transpile_path):
            files = []
            for js_path in js_paths:
                for root, dirnames, filenames in os.walk(js_path):
                    for filename in filenames:
                        files.append(os.path.join(root, filename))
            newest_file = max(files, key=os.path.getmtime)
            if (os.path.commonprefix([newest_file, transpile_path])
                    == transpile_path and not npm_install and not force):
                # Transpile not needed as nothing has changed and not forced
                return
            # Remove any previously created static output dirs
            shutil.rmtree(transpile_path, ignore_errors=True)
        self.stdout.write("Transpiling...")
        if not os.path.exists(TRANSPILE_CACHE_PATH):
            os.makedirs(TRANSPILE_CACHE_PATH)
        # We reload the file as other values may have changed in the meantime
        set_last_run("transpile", start)
        # Create a static output dir
        out_dir = os.path.join(transpile_path, "js/")
        os.makedirs(out_dir)
        with open(os.path.join(transpile_path, "README.txt"), "w") as f:
            f.write(("These files have been automatically generated. "
                     "DO NOT EDIT THEM! \n Changes will be overwritten. Edit "
                     "the original files in one of the django apps, and run "
                     "./manage.py transpile."))

        mainfiles = []
        sourcefiles = []
        lib_sourcefiles = []
        for path in js_paths:
            for mainfile in (subprocess.check_output(
                ["find", path, "-type", "f", "-name", "*.mjs",
                 "-print"]).decode("utf-8").split("\n")[:-1]):
                mainfiles.append(mainfile)
            for sourcefile in (subprocess.check_output(
                ["find", path, "-type", "f", "-wholename",
                 "*js"]).decode("utf-8").split("\n")[:-1]):
                if "static/js" in sourcefile:
                    sourcefiles.append(sourcefile)
                if "static-libs/js" in sourcefile:
                    lib_sourcefiles.append(sourcefile)
        # Collect all JavaScript in a temporary dir (similar to
        # ./manage.py collectstatic).
        # This allows for the modules to import from oneanother, across Django
        # Apps.

        cache_path = os.path.join(TRANSPILE_CACHE_PATH, "js/")
        if not os.path.exists(cache_path):
            os.makedirs(cache_path)
        # Note all cache files so that we can remove outdated files that no
        # longer are in the prject.
        cache_files = []
        # Note all plugin dirs and the modules inside of them to crate index.js
        # files inside of them.
        plugin_dirs = {}
        for sourcefile in sourcefiles:
            relative_path = sourcefile.split("static/js/")[1]
            outfile = os.path.join(cache_path, relative_path)
            cache_files.append(outfile)
            dirname = os.path.dirname(outfile)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
                shutil.copyfile(sourcefile, outfile)
            elif not os.path.isfile(outfile):
                shutil.copyfile(sourcefile, outfile)
            elif os.path.getmtime(outfile) < os.path.getmtime(sourcefile):
                shutil.copyfile(sourcefile, outfile)
            # Check for plugin connectors
            if relative_path[:8] == "plugins/":
                if dirname not in plugin_dirs:
                    plugin_dirs[dirname] = []
                module_name = os.path.splitext(
                    os.path.basename(relative_path))[0]
                if module_name != "init" and module_name not in plugin_dirs[
                        dirname]:
                    plugin_dirs[dirname].append(module_name)

        for sourcefile in lib_sourcefiles:
            relative_path = sourcefile.split("static-libs/js/")[1]
            outfile = os.path.join(cache_path, relative_path)
            cache_files.append(outfile)
            dirname = os.path.dirname(outfile)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
                shutil.copyfile(sourcefile, outfile)
            elif not os.path.isfile(outfile):
                shutil.copyfile(sourcefile, outfile)
            elif os.path.getmtime(outfile) < os.path.getmtime(sourcefile):
                shutil.copyfile(sourcefile, outfile)

        # Write an index.js file for every plugin dir
        for plugin_dir in plugin_dirs:
            index_js = ""
            for module_name in plugin_dirs[plugin_dir]:
                index_js += 'export * from "./%s"\n' % module_name
            outfile = os.path.join(plugin_dir, "index.js")
            cache_files.append(outfile)
            if not os.path.isfile(outfile):
                index_file = open(outfile, "w")
                index_file.write(index_js)
                index_file.close()
            else:
                index_file = open(outfile, "r")
                old_index_js = index_file.read()
                index_file.close()
                if old_index_js != index_js:
                    index_file = open(outfile, "w")
                    index_file.write(index_js)
                    index_file.close()

        # Check for outdated files that should be removed
        for existing_file in (subprocess.check_output(
            ["find", cache_path, "-type",
             "f"]).decode("utf-8").split("\n")[:-1]):
            if existing_file not in cache_files:
                self.stdout.write("Removing %s" % existing_file)
                os.remove(existing_file)
        if apps.is_installed("django.contrib.staticfiles"):
            from django.contrib.staticfiles.storage import staticfiles_storage

            static_base_url = staticfiles_storage.base_url
        else:
            static_base_url = PrefixNode.handle_simple("STATIC_URL")
        transpile_base_url = urljoin(static_base_url, "js/")
        if (hasattr(settings, "WEBPACK_CONFIG_TEMPLATE")
                and settings.WEBPACK_CONFIG_TEMPLATE):
            webpack_config_template_path = settings.WEBPACK_CONFIG_TEMPLATE
        else:
            webpack_config_template_path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                "webpack.config.template.js",
            )
        entries = {}
        for mainfile in mainfiles:
            basename = os.path.basename(mainfile)
            modulename = basename.split(".")[0]
            file_path = os.path.join(cache_path, basename)
            entries[modulename] = file_path
        find_static = CSCommand()
        find_static.set_options(
            **{
                "interactive": False,
                "verbosity": 0,
                "link": False,
                "clear": False,
                "dry_run": True,
                "ignore_patterns": ["js/", "admin/"],
                "use_default_ignore_patterns": True,
                "post_process": True,
            })
        found_files = find_static.collect()
        static_frontend_files = (found_files["modified"] +
                                 found_files["unmodified"] +
                                 found_files["post_processed"])
        transpile = {
            "OUT_DIR":
            out_dir,
            "VERSION":
            get_last_run("transpile"),
            "BASE_URL":
            transpile_base_url,
            "ENTRIES":
            entries,
            "STATIC_FRONTEND_FILES":
            list(
                map(
                    lambda x: urljoin(static_base_url, x),
                    static_frontend_files,
                )),
        }
        with open(webpack_config_template_path, "r") as f:
            webpack_config_template = f.read()
        settings_dict = {}
        for var in dir(settings):
            if var in ["DATABASES", "SECRET_KEY"]:
                # For extra security, we do not copy DATABASES or SECRET_KEY
                continue
            try:
                settings_dict[var] = getattr(settings, var)
            except AttributeError:
                pass
        webpack_config_js = webpack_config_template.replace(
            "window.transpile", json.dumps(transpile)).replace(
                "window.settings",
                json.dumps(settings_dict, default=lambda x: False),
            )

        if webpack_config_js is not OLD_WEBPACK_CONFIG_JS:
            with open(WEBPACK_CONFIG_JS_PATH, "w") as f:
                f.write(webpack_config_js)
        call(["./node_modules/.bin/webpack"], cwd=TRANSPILE_CACHE_PATH)
        end = int(round(time.time()))
        self.stdout.write("Time spent transpiling: " + str(end - start) +
                          " seconds")
        signals.post_transpile.send(sender=None)
Ejemplo n.º 52
0
import os.path

from django.apps import apps
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models import signals
from django.utils.translation import gettext, gettext_lazy as _
from wiki.models.pluginbase import RevisionPlugin, RevisionPluginRevision

from . import settings

if not apps.is_installed("sorl.thumbnail"):
    raise ImproperlyConfigured(
        'wiki.plugins.images: needs sorl.thumbnail in INSTALLED_APPS')


def upload_path(instance, filename):
    # Has to match original extension filename

    upload_path = settings.IMAGE_PATH
    upload_path = upload_path.replace(
        '%aid', str(instance.plugin.image.article.id))
    if settings.IMAGE_PATH_OBSCURIFY:
        import uuid
        upload_path = os.path.join(upload_path, uuid.uuid4().hex)
    return os.path.join(upload_path, filename)


class Image(RevisionPlugin):
Ejemplo n.º 53
0
def installed_apps_list():
    installed_apps = []
    for app in ('issuer', 'composition', 'badgebook'):
        if apps.is_installed(app):
            installed_apps.append(app)
    return installed_apps
Ejemplo n.º 54
0
    def has_permission(self, request):
        """
        Allow all users which are in 'users' group.
        """
        return request.user.is_active \
            and request.user.groups.filter(name='users').count()


admin = SuperAdminSite(name='adminpanel')
staff = AdminSite(name='staffpanel')
user = UserSite(name='userpanel')


# admin
if apps.is_installed('django.contrib.sites'):
    admin.register(Site, SiteAdmin)
admin.register(User, UserAdmin)
admin.register(Group, GroupAdmin)

admin.register(Author, AuthorAdmin)
admin.register(BookCategory, BookCategoryAdmin)
admin.register(Book, BookAdmin)
admin.register(CdCategory, CdCategoryAdmin)
admin.register(Cd, CdAdmin)
admin.register(DvdCategory, DvdCategoryAdmin)
admin.register(Dvd, DvdAdmin)
admin.register(TestModel, TestModelAdmin)

# staff
staff.register(Author, AuthorAdmin)
Ejemplo n.º 55
0
class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
                ModelAppHookConfig, TranslatableAdmin):
    form = PostAdminForm
    list_display = [
        "title", "author", "date_published", "app_config",
        "all_languages_column", "date_published_end"
    ]
    search_fields = ("translations__title", )
    date_hierarchy = "date_published"
    raw_id_fields = ["author"]
    frontend_editable_fields = ("title", "abstract", "post_text")
    enhance_exclude = ("main_image", "tags")
    actions = [
        "make_published",
        "make_unpublished",
        "enable_comments",
        "disable_comments",
    ]
    inlines = []
    if apps.is_installed("djangocms_blog.liveblog"):
        actions += ["enable_liveblog", "disable_liveblog"]
    _fieldsets = [
        (None, {
            "fields": [
                "title", "subtitle", "slug", "publish",
                ["categories", "app_config"]
            ]
        }),
        (None, {
            "fields": [[]]
        }),
        (
            _("Info"),
            {
                "fields": [
                    "tags",
                    ["date_published", "date_published_end", "date_featured"],
                    ["enable_comments"]
                ],
                "classes": ("collapse", ),
            },
        ),
        (
            _("Images"),
            {
                "fields":
                [["main_image", "main_image_thumbnail", "main_image_full"]],
                "classes": ("collapse", )
            },
        ),
        (_("SEO"), {
            "fields": [["meta_description", "meta_title", "meta_keywords"]],
            "classes": ("collapse", )
        }),
    ]

    app_config_values = {"default_published": "publish"}
    _sites = None

    # Bulk actions for post admin
    def make_published(self, request, queryset):
        """ Bulk action to mark selected posts as published. If
            the date_published field is empty the current time is
            saved as date_published.
            queryset must not be empty (ensured by DjangoCMS).
        """
        cnt1 = queryset.filter(
            date_published__isnull=True,
            publish=False,
        ).update(date_published=timezone.now(), publish=True)
        cnt2 = queryset.filter(
            date_published__isnull=False,
            publish=False,
        ).update(publish=True)
        messages.add_message(
            request,
            messages.INFO,
            __("%(updates)d entry published.",
               "%(updates)d entries published.", cnt1 + cnt2) %
            {"updates": cnt1 + cnt2},
        )

    def make_unpublished(self, request, queryset):
        """ Bulk action to mark selected posts as UNpublished.
            queryset must not be empty (ensured by DjangoCMS).
        """
        updates = queryset.filter(publish=True).update(publish=False)
        messages.add_message(
            request,
            messages.INFO,
            __("%(updates)d entry unpublished.",
               "%(updates)d entries unpublished.", updates) %
            {"updates": updates},
        )

    def enable_comments(self, request, queryset):
        """ Bulk action to enable comments for selected posts.
            queryset must not be empty (ensured by DjangoCMS).
        """
        updates = queryset.filter(enable_comments=False).update(
            enable_comments=True)
        messages.add_message(
            request,
            messages.INFO,
            __("Comments for %(updates)d entry enabled.",
               "Comments for %(updates)d entries enabled", updates) %
            {"updates": updates},
        )

    def disable_comments(self, request, queryset):
        """ Bulk action to disable comments for selected posts.
            queryset must not be empty (ensured by DjangoCMS).
        """
        updates = queryset.filter(enable_comments=True).update(
            enable_comments=False)
        messages.add_message(
            request,
            messages.INFO,
            __("Comments for %(updates)d entry disabled.",
               "Comments for %(updates)d entries disabled.", updates) %
            {"updates": updates},
        )

    def enable_liveblog(self, request, queryset):
        """ Bulk action to enable comments for selected posts.
            queryset must not be empty (ensured by DjangoCMS).
        """
        updates = queryset.filter(enable_liveblog=False).update(
            enable_liveblog=True)
        messages.add_message(
            request,
            messages.INFO,
            __("Liveblog for %(updates)d entry enabled.",
               "Liveblog for %(updates)d entries enabled.", updates) %
            {"updates": updates},
        )

    def disable_liveblog(self, request, queryset):
        """ Bulk action to disable comments for selected posts.
            queryset must not be empty (ensured by DjangoCMS).
        """
        updates = queryset.filter(enable_liveblog=True).update(
            enable_liveblog=False)
        messages.add_message(
            request,
            messages.INFO,
            __("Liveblog for %(updates)d entry enabled.",
               "Liveblog for %(updates)d entries enabled.") %
            {"updates": updates},
        )

    # Make bulk action menu entries localizable
    make_published.short_description = _("Publish selection")
    make_unpublished.short_description = _("Unpublish selection")
    enable_comments.short_description = _("Enable comments for selection")
    disable_comments.short_description = _("Disable comments for selection ")
    enable_liveblog.short_description = _("Enable liveblog for selection")
    disable_liveblog.short_description = _("Disable liveblog for selection ")

    def get_list_filter(self, request):
        filters = ["app_config", "publish", "date_published"]
        if get_setting("MULTISITE"):
            filters.append(SiteListFilter)
        try:
            from taggit_helpers.admin import TaggitListFilter

            filters.append(TaggitListFilter)
        except ImportError:  # pragma: no cover
            try:
                from taggit_helpers import TaggitListFilter

                filters.append(TaggitListFilter)
            except ImportError:
                pass
        return filters

    def get_urls(self):
        """
        Customize the modeladmin urls
        """
        urls = [
            url(
                r"^publish/([0-9]+)/$",
                self.admin_site.admin_view(self.publish_post),
                name="djangocms_blog_publish_article",
            ),
        ]
        urls.extend(super().get_urls())
        return urls

    def post_add_plugin(self, request, obj1, obj2=None):
        if isinstance(obj1, CMSPlugin):
            plugin = obj1
        elif isinstance(obj2, CMSPlugin):
            plugin = obj2
        if plugin.plugin_type in get_setting("LIVEBLOG_PLUGINS"):
            plugin = plugin.move(plugin.get_siblings().first(),
                                 "first-sibling")
        if isinstance(obj1, CMSPlugin):
            return super().post_add_plugin(request, plugin)
        elif isinstance(obj2, CMSPlugin):
            return super().post_add_plugin(request, obj1, plugin)

    def publish_post(self, request, pk):
        """
        Admin view to publish a single post

        :param request: request
        :param pk: primary key of the post to publish
        :return: Redirect to the post itself (if found) or fallback urls
        """
        language = get_language_from_request(request, check_path=True)
        try:
            post = Post.objects.get(pk=int(pk))
            post.publish = True
            post.save()
            return HttpResponseRedirect(post.get_absolute_url(language))
        except Exception:
            try:
                return HttpResponseRedirect(request.META["HTTP_REFERER"])
            except KeyError:
                return HttpResponseRedirect(
                    reverse("djangocms_blog:posts-latest"))

    def has_restricted_sites(self, request):
        """
        Whether the current user has permission on one site only

        :param request: current request
        :return: boolean: user has permission on only one site
        """
        sites = self.get_restricted_sites(request)
        return sites and sites.count() == 1

    def get_restricted_sites(self, request):
        """
        The sites on which the user has permission on.

        To return the permissions, the method check for the ``get_sites``
        method on the user instance (e.g.: ``return request.user.get_sites()``)
        which must return the queryset of enabled sites.
        If the attribute does not exists, the user is considered enabled
        for all the websites.

        :param request: current request
        :return: boolean or a queryset of available sites
        """
        try:
            return request.user.get_sites()
        except AttributeError:  # pragma: no cover
            return Site.objects.none()

    def _set_config_defaults(self, request, form, obj=None):
        form = super()._set_config_defaults(request, form, obj)
        sites = self.get_restricted_sites(request)
        if "sites" in form.base_fields and sites.exists():
            form.base_fields["sites"].queryset = self.get_restricted_sites(
                request).all()
        return form

    def _get_available_posts(self, config):
        if config:
            return self.model.objects.namespace(
                config.namespace).active_translations().exists()
        return []

    def get_fieldsets(self, request, obj=None):
        """
        Customize the fieldsets according to the app settings

        :param request: request
        :param obj: post
        :return: fieldsets configuration
        """
        app_config_default = self._app_config_select(request, obj)
        if app_config_default is None and request.method == "GET":
            return super().get_fieldsets(request, obj)
        if not obj:
            config = app_config_default
        else:
            config = obj.app_config

        fsets = deepcopy(self._fieldsets)
        related_posts = []
        if config:
            abstract = bool(config.use_abstract)
            placeholder = bool(config.use_placeholder)
            related = bool(config.use_related)
        else:
            abstract = get_setting("USE_ABSTRACT")
            placeholder = get_setting("USE_PLACEHOLDER")
            related = get_setting("USE_RELATED")
        if related:
            related_posts = self._get_available_posts(config)
        if abstract:
            fsets[0][1]["fields"].append("abstract")
        if not placeholder:
            fsets[0][1]["fields"].append("post_text")
        if get_setting("MULTISITE") and not self.has_restricted_sites(request):
            fsets[1][1]["fields"][0].append("sites")
        if request.user.is_superuser:
            fsets[1][1]["fields"][0].append("author")
        if apps.is_installed("djangocms_blog.liveblog"):
            fsets[2][1]["fields"][2].append("enable_liveblog")
        filter_function = get_setting("ADMIN_POST_FIELDSET_FILTER")
        if related_posts:
            fsets[1][1]["fields"][0].append("related")
        if callable(filter_function):
            fsets = filter_function(fsets, request, obj=obj)
        return fsets

    def get_prepopulated_fields(self, request, obj=None):
        return {"slug": ("title", )}

    def save_model(self, request, obj, form, change):
        obj._set_default_author(request.user)
        super().save_model(request, obj, form, change)

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        sites = self.get_restricted_sites(request)
        if sites.exists():
            pks = list(sites.all().values_list("pk", flat=True))
            qs = qs.filter(sites__in=pks)
        return qs.distinct()

    def save_related(self, request, form, formsets, change):
        if self.get_restricted_sites(request).exists():
            if "sites" in form.cleaned_data:
                form_sites = form.cleaned_data.get("sites", [])
                removed = set(self.get_restricted_sites(
                    request).all()).difference(form_sites)
                diff_original = set(form.instance.sites.all()).difference(
                    removed).union(form_sites)
                form.cleaned_data["sites"] = diff_original
            else:
                form.instance.sites.add(*self.get_restricted_sites(
                    request).all().values_list("pk", flat=True))
        super().save_related(request, form, formsets, change)

    class Media:
        css = {
            "all":
            ("{}djangocms_blog/css/{}".format(settings.STATIC_URL,
                                              "djangocms_blog_admin.css"), )
        }
 def test_setup(self):
     assert apps.is_installed('rest_framework')
     assert hasattr(self.APIView, '_datadog_patch')
Ejemplo n.º 57
0
from __future__ import absolute_import
from django.apps import apps

BAKER_GIS = apps.is_installed("django.contrib.gis")

default_gis_mapping = {}

__all__ = ['BAKER_GIS', 'default_gis_mapping']

if BAKER_GIS:
    from . import random_gen
    from django.contrib.gis.db.models import (
        GeometryField,
        PointField,
        LineStringField,
        PolygonField,
        MultiPointField,
        MultiLineStringField,
        MultiPolygonField,
        GeometryCollectionField,
    )

    default_gis_mapping[GeometryField] = random_gen.gen_geometry
    default_gis_mapping[PointField] = random_gen.gen_point
    default_gis_mapping[LineStringField] = random_gen.gen_line_string
    default_gis_mapping[PolygonField] = random_gen.gen_polygon
    default_gis_mapping[MultiPointField] = random_gen.gen_multi_point
    default_gis_mapping[
        MultiLineStringField] = random_gen.gen_multi_line_string
    default_gis_mapping[MultiPolygonField] = random_gen.gen_multi_polygon
    default_gis_mapping[
Ejemplo n.º 58
0
    urlpatterns += [
        # Add views for testing 404 and 500 templates
        path(
            "test404/",
            TemplateView.as_view(
                template_name="patterns/pages/errors/404.html"),
        ),
        path(
            "test500/",
            TemplateView.as_view(
                template_name="patterns/pages/errors/500.html"),
        ),
    ]

    # Try to install the django debug toolbar, if exists
    if apps.is_installed("debug_toolbar"):
        import debug_toolbar

        urlpatterns = [path("__debug__/", include(debug_toolbar.urls))
                       ] + urlpatterns

# Style guide
if getattr(settings, "PATTERN_LIBRARY_ENABLED",
           False) and apps.is_installed("pattern_library"):
    urlpatterns += [path("pattern-library/", include("pattern_library.urls"))]

# Error handlers
handler404 = "dft.utils.views.page_not_found"
handler500 = "dft.utils.views.server_error"
Ejemplo n.º 59
0
        name="main",
    ),
    path("zaken/api/", include("openzaak.components.zaken.api.urls")),
    path("besluiten/api/", include("openzaak.components.besluiten.api.urls")),
    path("documenten/api/",
         include("openzaak.components.documenten.api.urls")),
    path("autorisaties/api/",
         include("openzaak.components.autorisaties.api.urls")),
    path("catalogi/api/", include("openzaak.components.catalogi.api.urls")),
    # Simply show the master template.
    path("ref/", include("vng_api_common.urls")),
    path("ref/", include("vng_api_common.notifications.urls")),
    # auth backends
    path("adfs/", include("django_auth_adfs.urls")),
]

# NOTE: The staticfiles_urlpatterns also discovers static files (ie. no need to run collectstatic). Both the static
# folder and the media folder are only served via Django if DEBUG = True.
urlpatterns += staticfiles_urlpatterns() + static(
    settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.PRIVATE_MEDIA_URL,
                      document_root=settings.PRIVATE_MEDIA_ROOT)

if apps.is_installed("debug_toolbar"):
    import debug_toolbar

    urlpatterns += [path("__debug__/", include(debug_toolbar.urls))]

if apps.is_installed("silk"):
    urlpatterns += [path(r"silk/", include("silk.urls", namespace="silk"))]
Ejemplo n.º 60
0
def check_dependencies(**kwargs):
    """
    Check that the admin's dependencies are correctly installed.
    """
    if not apps.is_installed('django.contrib.admin'):
        return []
    errors = []
    app_dependencies = (
        ('django.contrib.contenttypes', 401),
        ('django.contrib.auth', 405),
        ('django.contrib.messages', 406),
        ('django.contrib.sessions', 407),
    )
    for app_name, error_code in app_dependencies:
        if not apps.is_installed(app_name):
            errors.append(
                checks.Error(
                    "'%s' must be in INSTALLED_APPS in order to use the admin "
                    "application." % app_name,
                    id='admin.E%d' % error_code,
                ))
    for engine in engines.all():
        if isinstance(engine, DjangoTemplates):
            django_templates_instance = engine.engine
            break
    else:
        django_templates_instance = None
    if not django_templates_instance:
        errors.append(
            checks.Error(
                "A 'django.template.backends.django.DjangoTemplates' instance "
                "must be configured in TEMPLATES in order to use the admin "
                "application.",
                id='admin.E403',
            ))
    else:
        if ('django.contrib.auth.context_processors.auth'
                not in django_templates_instance.context_processors
                and 'django.contrib.auth.backends.ModelBackend'
                in settings.AUTHENTICATION_BACKENDS):
            errors.append(
                checks.Error(
                    "'django.contrib.auth.context_processors.auth' must be "
                    "enabled in DjangoTemplates (TEMPLATES) if using the default "
                    "auth backend in order to use the admin application.",
                    id='admin.E402',
                ))
        if ('django.contrib.messages.context_processors.messages'
                not in django_templates_instance.context_processors):
            errors.append(
                checks.Error(
                    "'django.contrib.messages.context_processors.messages' must "
                    "be enabled in DjangoTemplates (TEMPLATES) in order to use "
                    "the admin application.",
                    id='admin.E404',
                ))
    if ('django.contrib.auth.middleware.AuthenticationMiddleware'
            not in settings.MIDDLEWARE):
        errors.append(
            checks.Error(
                "'django.contrib.auth.middleware.AuthenticationMiddleware' must "
                "be in MIDDLEWARE in order to use the admin application.",
                id='admin.E408',
            ))
    if ('django.contrib.messages.middleware.MessageMiddleware'
            not in settings.MIDDLEWARE):
        errors.append(
            checks.Error(
                "'django.contrib.messages.middleware.MessageMiddleware' must "
                "be in MIDDLEWARE in order to use the admin application.",
                id='admin.E409',
            ))
    return errors