django.conf.settings.INSTALLED_APPS

Here are the examples of the python api django.conf.settings.INSTALLED_APPS taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: django-allauth
Source File: adapter.py
View license
    def add_message(self, request, level, message_template,
                    message_context=None, extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request, level, message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass

Example 2

Project: django-mediagenerator
Source File: utils.py
View license
@memoize
def get_media_dirs():
    media_dirs = GLOBAL_MEDIA_DIRS[:]
    for app in settings.INSTALLED_APPS:
        if app in IGNORE_APP_MEDIA_DIRS:
            continue
        for name in (u'static', u'media'):
            app_root = os.path.dirname(import_module(app).__file__)
            media_dirs.append(os.path.join(app_root, name))
    return media_dirs

Example 3

Project: django_xworkflows
Source File: models.py
View license
def get_default_log_model():
    """The default log model depends on whether the xworkflow_log app is there."""
    if 'django_xworkflows.xworkflow_log' in settings.INSTALLED_APPS:
        return 'xworkflow_log.TransitionLog'
    else:
        return ''

Example 4

Project: django-scaffolding
Source File: __init__.py
View license
def generic_autodiscover(module_name):

    for app in settings.INSTALLED_APPS:
        try:
            import_module(app)
            app_path = sys.modules[app].__path__
        except (AttributeError, ImportError):
            continue
        try:
            imp.find_module(module_name, app_path)
        except ImportError:
            continue
        import_module('%s.%s' % (app, module_name))
        app_path = sys.modules['%s.%s' % (app, module_name)]

Example 5

Project: django-future
Source File: __init__.py
View license
def import_app_jobs():
    """Import the 'jobs' module from all applications.

    This is needed so that the `sticky` decorator has a chance to work.
    """
    for app_name in settings.INSTALLED_APPS:
        try:
            __import__(app_name + '.jobs')
        except ImportError:
            pass # No jobs module.

Example 6

Project: django-invitations
Source File: adapters.py
View license
    def add_message(self, request, level, message_template,
                    message_context=None, extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request, level, message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass

Example 7

Project: ProjectNarwhal
Source File: __init__.py
View license
    def can_send_invites(self, *args, **kwargs):
        if not (datetime.now() - self.user.date_joined >= conf.MIN_MEMBER_AGE):
            return False
        if 'narwhal.plugins.user.reputation' in settings.INSTALLED_APPS \
          and (self.user.profile.data.get('reputation', 0) < conf.MIN_REPUTAION):
            return False
        if self.ratio < conf.MIN_RATIO:
            return False
        if not self.data.get('invites_left', 0) > 0:
            return False
        return True

Example 8

View license
def get_application(app_label):
    """ Get an application. """
    try:
        # django >= 1.7
        from django.apps import apps as django_apps
        return django_apps.get_app_package(app_label)
    except ImportError:
        # django < 1.7
        from django.conf import settings
        global APP_NAMES
        if APP_NAMES is None:
            APP_NAMES = {
                app.rsplit('.', 1)[-1]: app for app in settings.INSTALLED_APPS
            }
        return APP_NAMES[app_label]

Example 9

Project: django-eadred
Source File: test_generate.py
View license
    def reset_app_data(self):
        from django.conf import settings
        for app in settings.INSTALLED_APPS:
            try:
                app_path = import_module(app).__path__
            except AttributeError:
                continue

            try:
                imp.find_module('sampledata', app_path)
            except ImportError:
                continue

            module = import_module('%s.sampledata' % app)
            module.reset_app()

Example 10

Project: djangoembed
Source File: __init__.py
View license
def autodiscover():
    """
    Automatically build the provider index.
    """
    import imp
    from django.conf import settings
    
    for app in settings.INSTALLED_APPS:
        try:
            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
        except AttributeError:
            continue
        
        try:
            imp.find_module('oembed_providers', app_path)
        except ImportError:
            continue
        
        __import__("%s.oembed_providers" % app)

Example 11

View license
    def test_django_multiple_reports(self):
        self._override_settings(
            TEST_OUTPUT_DIR=self.tmpdir,
            TEST_OUTPUT_VERBOSE=0,
            TEST_RUNNER='xmlrunner.extra.djangotestrunner.XMLTestRunner')
        apps.populate(settings.INSTALLED_APPS)
        runner_class = get_runner(settings)
        runner = runner_class()
        suite = runner.build_suite(test_labels=None)
        runner.run_suite(suite)
        test_files = glob.glob(path.join(self.tmpdir, 'TEST*.xml'))
        self.assertTrue(test_files,
                        'did not generate xml reports where expected.')
        self.assertEqual(2, len(test_files))

Example 12

Project: django-staticflatpages
Source File: sitemaps.py
View license
    @skipUnless("staticflatpages" in settings.INSTALLED_APPS,
                "staticflatpages app not installed.")
    def test_sitemap(self):
        """Basic StaticFlatPage sitemap test"""
        url = reverse('sitemap')  # default sitemap
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        loc = '<loc>{0}{1}</loc>'.format(
            self.base_url,
            reverse('sitemap_section', args=['staticflatpages'])
        )
        self.assertContains(response, loc)

Example 13

Project: django-report-builder
Source File: utils.py
View license
def get_custom_fields_from_model(model_class):
    """ django-custom-fields support """
    if 'custom_field' in settings.INSTALLED_APPS:
        from custom_field.models import CustomField
        try:
            content_type = ContentType.objects.get(
                model=model_class._meta.model_name,
                app_label=model_class._meta.app_label)
        except ContentType.DoesNotExist:
            content_type = None
        custom_fields = CustomField.objects.filter(content_type=content_type)
        return custom_fields

Example 14

View license
    def _check_apps(self):
        """ Check if this dashlet has the required apps installed for usage """
        for app in self.require_apps:
            if not app in settings.INSTALLED_APPS:
                return False
        return True

Example 15

Project: blue-channel
Source File: utils.py
View license
def get_send_mail():
    """
    A function to return a send_mail function suitable for use in the app. It
    deals with incompatibilities between signatures.
    """
    # favour django-mailer but fall back to django.core.mail
    if "mailer" in settings.INSTALLED_APPS:
        from mailer import send_mail
    else:
        from django.core.mail import send_mail as _send_mail
        def send_mail(*args, **kwargs):
            del kwargs["priority"]
            return _send_mail(*args, **kwargs)
    return send_mail

Example 16

Project: gargoyle
Source File: runtests.py
View license
def runtests(*test_args, **kwargs):
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    if not test_args:
        test_args = ['tests']

    test_runner = NoseTestSuiteRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures)

Example 17

Project: djangoappengine
Source File: views.py
View license
def warmup(request):
    """
    Provides default procedure for handling warmup requests on App
    Engine. Just add this view to your main urls.py.
    """
    for app in settings.INSTALLED_APPS:
        for name in ('urls', 'views', 'models'):
            try:
                import_module('%s.%s' % (app, name))
            except ImportError:
                pass
    content_type = 'text/plain; charset=%s' % settings.DEFAULT_CHARSET
    return HttpResponse("Warmup done.", content_type=content_type)

Example 18

Project: django-oscar
Source File: loading.py
View license
def _get_installed_apps_entry(app_name):
    """
    Given an app name (e.g. 'catalogue'), walk through INSTALLED_APPS
    and return the first match, or None.
    This does depend on the order of INSTALLED_APPS and will break if
    e.g. 'dashboard.catalogue' comes before 'catalogue' in INSTALLED_APPS.
    """
    for installed_app in settings.INSTALLED_APPS:
        # match root-level apps ('catalogue') or apps with same name at end
        # ('shop.catalogue'), but don't match 'fancy_catalogue'
        if installed_app == app_name or installed_app.endswith('.' + app_name):
            return installed_app
    return None

Example 19

Project: django-newsletter
Source File: test_settings.py
View license
    @unittest.skipUnless(
        # Only run tests when TinyMCE is available
        'tinymce' in settings.INSTALLED_APPS,
        'django-tinymce not available for testing.'
    )
    @override_settings(
        # Filter imperavi from editors so just tinymce is left
        INSTALLED_APPS=filter(
            lambda app: app != 'imperavi', settings.INSTALLED_APPS
        ),
        NEWSLETTER_RICHTEXT_WIDGET='tinymce.widgets.TinyMCE'
    )
    def test_editor_tinymce(self):
        """
        Test explicit setting TinyMCE as editor.
        """

        from tinymce.widgets import TinyMCE
        self.assertEqual(newsletter_settings.RICHTEXT_WIDGET, TinyMCE)

Example 20

Project: django-moderation
Source File: runtests.py
View license
def runtests(*test_args, **kwargs):
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    if not test_args:
        test_args = ['tests']

    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    test_runner = prepare_test_runner(**kwargs)
    failures = test_runner.run_tests(test_args)
    sys.exit(failures)

Example 21

Project: django-dynamic-preferences
Source File: apps.py
View license
    def ready(self):
        UserPreferenceModel = self.get_model('UserPreferenceModel')
        GlobalPreferenceModel = self.get_model('GlobalPreferenceModel')

        preference_models.register(UserPreferenceModel, user_preferences_registry)
        preference_models.register(GlobalPreferenceModel, global_preferences_registry)

        # This will load all dynamic_preferences_registry.py files under isntalled apps
        global_preferences_registry.autodiscover(settings.INSTALLED_APPS)

Example 22

Project: django-precise-bbcode
Source File: loading.py
View license
def load(modname):
    """
    Loads all modules with name 'modname' from all installed apps.
    """
    for app in settings.INSTALLED_APPS:
        get_module(app, modname)

Example 23

Project: Arkestra
Source File: schema_registry.py
View license
    def discover_links_schemas(self, *args, **kwargs):
        '''
        run through all installed apps to find link schema definitions.
        This needs to get called rather late, because it needs access to
        models and admin
        '''
        if self.discovered:
            return
        for app in settings.INSTALLED_APPS:
            __import__(app, {}, {}, ['link_schemas'])
        self.discovered = True

Example 24

Project: django-nap
Source File: api.py
View license
def autodiscover():
    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's api module.
        try:
            import_module('%s.publishers' % app)
        except:

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'publishers'):
                raise

Example 25

Project: django-gears
Source File: finders.py
View license
    def get_app_assets_dirs(self):
        if not six.PY3:
            fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
        app_assets_dirs = []
        for app in settings.INSTALLED_APPS:
            try:
                mod = import_module(app)
            except ImportError as e:
                raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
            assets_dir = os.path.join(os.path.dirname(mod.__file__), 'assets')
            if os.path.isdir(assets_dir):
                if not six.PY3:
                    assets_dir = assets_dir.decode(fs_encoding)
                app_assets_dirs.append(assets_dir)
        app_assets_dirs = tuple(app_assets_dirs)
        return app_assets_dirs

Example 26

Project: simple-db-migrate
Source File: dbmigrate.py
View license
    @staticmethod
    def _locate_resource_dirs(complement, pattern):
        _dirs = []
        for app in settings.INSTALLED_APPS:
            fromlist = ""

            app_parts = app.split(".")
            if len(app_parts) > 1:
                fromlist = ".".join(app_parts[1:])

            module = __import__(app, fromlist=fromlist)
            app_dir = os.path.abspath("/" + "/".join(module.__file__.split("/")[1:-1]))

            resource_dir = os.path.join(app_dir, complement)

            if os.path.exists(resource_dir) and Command._locate_files(resource_dir, pattern):
                _dirs.append(resource_dir)

        return _dirs

Example 27

Project: gunnery
Source File: modal.py
View license
def _get_app_modal(app, form_name):
    if not app:
        app = 'core'
    if app in settings.INSTALLED_APPS:
        obj = __import__(app, fromlist=['modal']).modal
        try:
            obj = getattr(obj, '%sModal' % form_name.title())
        except AttributeError:
            raise Http404()
    else:
        raise Http404()
    return obj

Example 28

Project: django-admin2
Source File: core.py
View license
    def autodiscover(self):
        """
        Autodiscovers all admin2.py modules for apps in INSTALLED_APPS by
        trying to import them.
        """
        for app_name in [x for x in settings.INSTALLED_APPS]:
            try:
                import_module("%s.admin2" % app_name)
            except ImportError as e:
                if str(e).startswith("No module named") and 'admin2' in str(e):
                    continue
                raise e

Example 29

Project: ANALYSE
Source File: django_startup.py
View license
def autostartup():
    """
    Execute app.startup:run() for all installed django apps
    """
    for app in settings.INSTALLED_APPS:
        # See if there's a startup module in each app.
        try:
            mod = import_module(app + '.startup')
        except ImportError:
            continue

        # If the module has a run method, run it.
        if hasattr(mod, 'run'):
            mod.run()

Example 30

Project: django-counter-field
Source File: runtests.py
View license
def runtests(*test_args, **kwargs):
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    if not test_args:
        test_args = ['tests']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    test_runner = DjangoTestSuiteRunner(verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast'))
    failures = test_runner.run_tests(test_args)
    sys.exit(failures)

Example 31

Project: karaage
Source File: __init__.py
View license
def get_app_modules(name):
    if django.VERSION < (1, 7):
        for app in settings.INSTALLED_APPS:
            try:
                module_name = app + "." + name
                module = importlib.import_module(module_name)
                yield module
            except ImportError:
                pass
    else:
        from django.apps import apps
        for config in apps.get_app_configs():
            if isinstance(config, BasePlugin):
                module_name = config.name + "." + name
                module = importlib.import_module(module_name)
                yield module

Example 32

Project: jack-bower
Source File: base.py
View license
    def handle(self, *app_labels, **options):
        if not app_labels:
            if self.default_apps:
                app_labels = self.default_apps
            else:
                raise CommandError('Enter at least one appname.')

        for app_label in set(app_labels) - set(settings.INSTALLED_APPS):
            raise CommandError("%s not found in INSTALLED_APPS" % app_label)

        for app in app_labels:
            path = pkgutil.get_loader(app).filename
            self.handle_app(path, **options)

Example 33

Project: django-plugins
Source File: utils.py
View license
def load_plugins():
    for app in settings.INSTALLED_APPS:
        try:
            import_module('%s.plugins' % app)
        except ImportError:
            import_app(app)

Example 34

Project: python-webpack
Source File: apps.py
View license
    def ready(self):
        if (
            ('staticfiles' in settings.INSTALLED_APPS or 'django.contrib.staticfiles' in settings.INSTALLED_APPS) and
            FINDER_PATH not in settings.STATICFILES_FINDERS
        ):
            raise ImproperlyConfigured(
                (
                    'When using webpack together with staticfiles, please add \'{}\' to the '
                    'STATICFILES_FINDERS setting.'
                ).format(FINDER_PATH)
            )

        webpack.conf.settings.configure(
            **getattr(settings, 'WEBPACK', {})
        )

Example 35

Project: django-fabric
Source File: base.py
View license
    def syncdb(self, instance):
        from django.conf import settings
        if django.VERSION >= (1, 7):
            self.run_management_command(instance, 'migrate --noinput')
        elif 'south' in settings.INSTALLED_APPS:
            self.run_management_command(instance, 'syncdb --noinput --migrate')
        else:
            self.run_management_command(instance, 'syncdb --noinput')

        self.notify(colors.green('Synced/Migrated the database'))

Example 36

Project: django-badger
Source File: __init__.py
View license
def update_badges(overwrite=False):
    from django.utils.importlib import import_module

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        try:
            badges_mod = import_module('%s.badges' % app)
            fixture_label = '%s_badges' % app.replace('.','_')
            call_command('loaddata', fixture_label, verbosity=1)
            if hasattr(badges_mod, 'badges'):
                badger.utils.update_badges(badges_mod.badges, overwrite)
            if hasattr(badges_mod, 'update_badges'):
                badges_mod.update_badges(overwrite)
        except ImportError:
            if module_has_submodule(mod, 'badges'):
                raise

Example 37

Project: mozillians
Source File: monkeypatches.py
View license
def patch():
    global _has_patched
    if _has_patched:
        return

    # Import for side-effect: configures logging handlers.
    # pylint: disable-msg=W0611
    import log_settings  # noqa

    # Monkey-patch Django's csrf_protect decorator to use session-based CSRF
    # tokens:
    if 'session_csrf' in settings.INSTALLED_APPS:
        import session_csrf
        session_csrf.monkeypatch()

    logging.debug("Note: funfactory monkey patches executed in %s" % __file__)

    # prevent it from being run again later
    _has_patched = True

Example 38

Project: armstrong.esi
Source File: http_client.py
View license
    def _session(self):
        """
        Obtains the current session variables.
        """
        if 'django.contrib.sessions' in settings.INSTALLED_APPS:
            engine = import_module(settings.SESSION_ENGINE)
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
            if cookie:
                return engine.SessionStore(cookie.value)
        return {}

Example 39

Project: django-refinery
Source File: runtests.py
View license
def runtests(*test_args, **kwargs):
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()
    
    if not test_args:
        test_args = ['tests']
    
    kwargs.setdefault('interactive', False)
    
    test_runner = NoseTestSuiteRunner(**kwargs)
    
    failures = test_runner.run_tests(test_args)
    sys.exit(failures)

Example 40

Project: django-load
Source File: core.py
View license
def load(modname, verbose=False, failfast=False):
    """
    Loads all modules with name 'modname' from all installed apps.
    
    If verbose is True, debug information will be printed to stdout.
    
    If failfast is True, import errors will not be surpressed.
    """
    for app in settings.INSTALLED_APPS:
        get_module(app, modname, verbose, failfast)

Example 41

Project: opbeat_python
Source File: django_tests.py
View license
    def test_user_info_with_non_django_auth(self):
        with self.settings(INSTALLED_APPS=[
            app for app in settings.INSTALLED_APPS
            if app != 'django.contrib.auth'
        ]):
            self.assertRaises(Exception,
                              self.client.get,
                              reverse('opbeat-raise-exc'))

            self.assertEquals(len(self.opbeat.events), 1)
            event = self.opbeat.events.pop(0)
            self.assertFalse('user' in event)

Example 42

Project: django-crudbuilder
Source File: helpers.py
View license
def auto_discover():
    '''
    Auto register all apps that have module moderator with moderation
    '''
    from django.conf import settings

    for app in settings.INSTALLED_APPS:
        import_crud(app)

Example 43

Project: unisubs
Source File: utils.py
View license
def app_static_media_dirs():
    static_media_dirs = []
    for app in settings.INSTALLED_APPS:
        module = importlib.import_module(app)
        static_dir = os.path.join(os.path.dirname(module.__file__), 'static')
        if os.path.exists(static_dir):
            static_media_dirs.append(static_dir)
    return static_media_dirs

Example 44

Project: talk.org
Source File: flush.py
View license
    def handle_noargs(self, **options):
        from django.conf import settings
        from django.db import connection, transaction, models
        from django.dispatch import dispatcher
        from django.core.management.sql import sql_flush, emit_post_sync_signal

        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                __import__(app_name + '.management', {}, {}, [''])
            except ImportError:
                pass

        sql_list = sql_flush(self.style, only_django=True)

        if interactive:
            confirm = raw_input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % settings.DATABASE_NAME)
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                cursor = connection.cursor()
                for sql in sql_list:
                    cursor.execute(sql)
            except Exception, e:
                transaction.rollback_unless_managed()
                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
      * The database isn't running or isn't configured correctly.
      * At least one of the expected database tables doesn't exist.
      * The SQL was invalid.
    Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
    The full error: %s""" % (settings.DATABASE_NAME, e))
            transaction.commit_unless_managed()

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            emit_post_sync_signal(models.get_models(), verbosity, interactive)

            # Reinstall the initial_data fixture.
            from django.core.management import call_command
            call_command('loaddata', 'initial_data', **options)

        else:
            print "Flush cancelled."

Example 45

Project: talk.org
Source File: syncdb.py
View license
    def handle_noargs(self, **options):
        from django.db import connection, transaction, models
        from django.conf import settings
        from django.core.management.sql import table_list, installed_models, sql_model_create, sql_for_pending_references, many_to_many_sql_for_model, custom_sql_for_model, sql_indexes_for_model, emit_post_sync_signal

        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                __import__(app_name + '.management', {}, {}, [''])
            except ImportError, exc:
                if not exc.args[0].startswith('No module named management'):
                    raise

        cursor = connection.cursor()

        if connection.features.uses_case_insensitive_names:
            table_name_converter = lambda x: x.upper()
        else:
            table_name_converter = lambda x: x
        # Get a list of all existing database tables, so we know what needs to
        # be added.
        tables = [table_name_converter(name) for name in table_list()]

        # Get a list of already installed *models* so that references work right.
        seen_models = installed_models(tables)
        created_models = set()
        pending_references = {}

        # Create the tables for each model
        for app in models.get_apps():
            app_name = app.__name__.split('.')[-2]
            model_list = models.get_models(app)
            for model in model_list:
                # Create the model's database table, if it doesn't already exist.
                if verbosity >= 2:
                    print "Processing %s.%s model" % (app_name, model._meta.object_name)
                if table_name_converter(model._meta.db_table) in tables:
                    continue
                sql, references = sql_model_create(model, self.style, seen_models)
                seen_models.add(model)
                created_models.add(model)
                for refto, refs in references.items():
                    pending_references.setdefault(refto, []).extend(refs)
                    if refto in seen_models:
                        sql.extend(sql_for_pending_references(refto, self.style, pending_references))
                sql.extend(sql_for_pending_references(model, self.style, pending_references))
                if verbosity >= 1:
                    print "Creating table %s" % model._meta.db_table
                for statement in sql:
                    cursor.execute(statement)
                tables.append(table_name_converter(model._meta.db_table))

        # Create the m2m tables. This must be done after all tables have been created
        # to ensure that all referred tables will exist.
        for app in models.get_apps():
            app_name = app.__name__.split('.')[-2]
            model_list = models.get_models(app)
            for model in model_list:
                if model in created_models:
                    sql = many_to_many_sql_for_model(model, self.style)
                    if sql:
                        if verbosity >= 2:
                            print "Creating many-to-many tables for %s.%s model" % (app_name, model._meta.object_name)
                        for statement in sql:
                            cursor.execute(statement)

        transaction.commit_unless_managed()

        # Send the post_syncdb signal, so individual apps can do whatever they need
        # to do at this point.
        emit_post_sync_signal(created_models, verbosity, interactive)

        # Install custom SQL for the app (but only if this
        # is a model we've just created)
        for app in models.get_apps():
            app_name = app.__name__.split('.')[-2]
            for model in models.get_models(app):
                if model in created_models:
                    custom_sql = custom_sql_for_model(model)
                    if custom_sql:
                        if verbosity >= 1:
                            print "Installing custom SQL for %s.%s model" % (app_name, model._meta.object_name)
                        try:
                            for sql in custom_sql:
                                cursor.execute(sql)
                        except Exception, e:
                            sys.stderr.write("Failed to install custom SQL for %s.%s model: %s" % \
                                                (app_name, model._meta.object_name, e))
                            transaction.rollback_unless_managed()
                        else:
                            transaction.commit_unless_managed()

        # Install SQL indicies for all newly created models
        for app in models.get_apps():
            app_name = app.__name__.split('.')[-2]
            for model in models.get_models(app):
                if model in created_models:
                    index_sql = sql_indexes_for_model(model, self.style)
                    if index_sql:
                        if verbosity >= 1:
                            print "Installing index for %s.%s model" % (app_name, model._meta.object_name)
                        try:
                            for sql in index_sql:
                                cursor.execute(sql)
                        except Exception, e:
                            sys.stderr.write("Failed to install index for %s.%s model: %s" % \
                                                (app_name, model._meta.object_name, e))
                            transaction.rollback_unless_managed()
                        else:
                            transaction.commit_unless_managed()

        # Install the 'initial_data' fixture, using format discovery
        from django.core.management import call_command
        call_command('loaddata', 'initial_data', verbosity=verbosity)

Example 46

Project: talk.org
Source File: i18n.py
View license
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if 'language' in request.GET:
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if type(packages) in (str, unicode):
        packages = packages.split('+')
    packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    # first load all english languages files for defaults
    for package in packages:
        p = __import__(package, {}, {}, [''])
        path = os.path.join(os.path.dirname(p.__file__), 'locale')
        paths.append(path)
        try:
            catalog = gettext_module.translation(domain, path, ['en'])
            t.update(catalog._catalog)
        except IOError:
            # 'en' catalog was missing. This is harmless.
            pass
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    src = [LibHead]
    plural = None
    if '' in t:
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':',1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if type(k) in (str, unicode):
            csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
        elif type(k) == tuple:
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError, k
    csrc.sort()
    for k,v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')

Example 47

Project: symposion
Source File: views.py
View license
@login_required
def proposal_detail(request, pk):
    queryset = ProposalBase.objects.select_related("speaker", "speaker__user")
    proposal = get_object_or_404(queryset, pk=pk)
    proposal = ProposalBase.objects.get_subclass(pk=proposal.pk)

    if request.user not in [p.user for p in proposal.speakers()]:
        raise Http404()

    if "symposion.reviews" in settings.INSTALLED_APPS:
        from symposion.reviews.forms import SpeakerCommentForm
        message_form = SpeakerCommentForm()
        if request.method == "POST":
            message_form = SpeakerCommentForm(request.POST)
            if message_form.is_valid():

                message = message_form.save(commit=False)
                message.user = request.user
                message.proposal = proposal
                message.save()

                ProposalMessage = SpeakerCommentForm.Meta.model
                reviewers = User.objects.filter(
                    id__in=ProposalMessage.objects.filter(
                        proposal=proposal
                    ).exclude(
                        user=request.user
                    ).distinct().values_list("user", flat=True)
                )

                for reviewer in reviewers:
                    ctx = {
                        "proposal": proposal,
                        "message": message,
                        "reviewer": True,
                    }
                    send_email(
                        [reviewer.email], "proposal_new_message",
                        context=ctx
                    )

                return redirect(request.path)
        else:
            message_form = SpeakerCommentForm()
    else:
        message_form = None

    return render(request, "symposion/proposals/proposal_detail.html", {
        "proposal": proposal,
        "message_form": message_form
    })

Example 48

Project: GAE-Bulk-Mailer
Source File: syncdb.py
View license
    def handle_noargs(self, **options):

        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        show_traceback = options.get('traceback')
        load_initial_data = options.get('load_initial_data')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError as exc:
                # This is slightly hackish. We want to ignore ImportErrors
                # if the "management" module itself is missing -- but we don't
                # want to ignore the exception if the management module exists
                # but raises an ImportError for some reason. The only way we
                # can do this is to check the text of the exception. Note that
                # we're a bit broad in how we check the text, because different
                # Python implementations may not use the same text.
                # CPython uses the text "No module named management"
                # PyPy uses "No module named myproject.myapp.management"
                msg = exc.args[0]
                if not msg.startswith('No module named') or 'management' not in msg:
                    raise

        db = options.get('database')
        connection = connections[db]
        cursor = connection.cursor()

        # Get a list of already installed *models* so that references work right.
        tables = connection.introspection.table_names()
        seen_models = connection.introspection.installed_models(tables)
        created_models = set()
        pending_references = {}

        # Build the manifest of apps and models that are to be synchronized
        all_models = [
            (app.__name__.split('.')[-2],
                [m for m in models.get_models(app, include_auto_created=True)
                if router.allow_syncdb(db, m)])
            for app in models.get_apps()
        ]

        def model_installed(model):
            opts = model._meta
            converter = connection.introspection.table_name_converter
            return not ((converter(opts.db_table) in tables) or
                (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables))

        manifest = SortedDict(
            (app_name, list(filter(model_installed, model_list)))
            for app_name, model_list in all_models
        )

        # Create the tables for each model
        if verbosity >= 1:
            self.stdout.write("Creating tables ...\n")
        for app_name, model_list in manifest.items():
            for model in model_list:
                # Create the model's database table, if it doesn't already exist.
                if verbosity >= 3:
                    self.stdout.write("Processing %s.%s model\n" % (app_name, model._meta.object_name))
                sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
                seen_models.add(model)
                created_models.add(model)
                for refto, refs in references.items():
                    pending_references.setdefault(refto, []).extend(refs)
                    if refto in seen_models:
                        sql.extend(connection.creation.sql_for_pending_references(refto, self.style, pending_references))
                sql.extend(connection.creation.sql_for_pending_references(model, self.style, pending_references))
                if verbosity >= 1 and sql:
                    self.stdout.write("Creating table %s\n" % model._meta.db_table)
                for statement in sql:
                    cursor.execute(statement)
                tables.append(connection.introspection.table_name_converter(model._meta.db_table))

        transaction.commit_unless_managed(using=db)

        # Send the post_syncdb signal, so individual apps can do whatever they need
        # to do at this point.
        emit_post_sync_signal(created_models, verbosity, interactive, db)

        # The connection may have been closed by a syncdb handler.
        cursor = connection.cursor()

        # Install custom SQL for the app (but only if this
        # is a model we've just created)
        if verbosity >= 1:
            self.stdout.write("Installing custom SQL ...\n")
        for app_name, model_list in manifest.items():
            for model in model_list:
                if model in created_models:
                    custom_sql = custom_sql_for_model(model, self.style, connection)
                    if custom_sql:
                        if verbosity >= 2:
                            self.stdout.write("Installing custom SQL for %s.%s model\n" % (app_name, model._meta.object_name))
                        try:
                            for sql in custom_sql:
                                cursor.execute(sql)
                        except Exception as e:
                            self.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \
                                                (app_name, model._meta.object_name, e))
                            if show_traceback:
                                traceback.print_exc()
                            transaction.rollback_unless_managed(using=db)
                        else:
                            transaction.commit_unless_managed(using=db)
                    else:
                        if verbosity >= 3:
                            self.stdout.write("No custom SQL for %s.%s model\n" % (app_name, model._meta.object_name))

        if verbosity >= 1:
            self.stdout.write("Installing indexes ...\n")
        # Install SQL indices for all newly created models
        for app_name, model_list in manifest.items():
            for model in model_list:
                if model in created_models:
                    index_sql = connection.creation.sql_indexes_for_model(model, self.style)
                    if index_sql:
                        if verbosity >= 2:
                            self.stdout.write("Installing index for %s.%s model\n" % (app_name, model._meta.object_name))
                        try:
                            for sql in index_sql:
                                cursor.execute(sql)
                        except Exception as e:
                            self.stderr.write("Failed to install index for %s.%s model: %s\n" % \
                                                (app_name, model._meta.object_name, e))
                            transaction.rollback_unless_managed(using=db)
                        else:
                            transaction.commit_unless_managed(using=db)

        # Load initial_data fixtures (unless that has been disabled)
        if load_initial_data:
            call_command('loaddata', 'initial_data', verbosity=verbosity,
                         database=db, skip_validation=True)

Example 49

Project: GAE-Bulk-Mailer
Source File: __init__.py
View license
    def autocomplete(self):
        """
        Output completion suggestions for BASH.

        The output of this function is passed to BASH's `COMREPLY` variable and
        treated as completion suggestions. `COMREPLY` expects a space
        separated string as the result.

        The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
        to get information about the cli input. Please refer to the BASH
        man-page for more information about this variables.

        Subcommand options are saved as pairs. A pair consists of
        the long option string (e.g. '--exclude') and a boolean
        value indicating if the option requires arguments. When printing to
        stdout, a equal sign is appended to options which require arguments.

        Note: If debugging this function, it is recommended to write the debug
        output in a separate file. Otherwise the debug output will be treated
        and formatted as potential completion suggestions.
        """
        # Don't complete if user hasn't sourced bash_completion file.
        if 'DJANGO_AUTO_COMPLETE' not in os.environ:
            return

        cwords = os.environ['COMP_WORDS'].split()[1:]
        cword = int(os.environ['COMP_CWORD'])

        try:
            curr = cwords[cword-1]
        except IndexError:
            curr = ''

        subcommands = list(get_commands()) + ['help']
        options = [('--help', None)]

        # subcommand
        if cword == 1:
            print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))))
        # subcommand options
        # special case: the 'help' subcommand has no options
        elif cwords[0] in subcommands and cwords[0] != 'help':
            subcommand_cls = self.fetch_command(cwords[0])
            # special case: 'runfcgi' stores additional options as
            # 'key=value' pairs
            if cwords[0] == 'runfcgi':
                from django.core.servers.fastcgi import FASTCGI_OPTIONS
                options += [(k, 1) for k in FASTCGI_OPTIONS]
            # special case: add the names of installed apps to options
            elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear',
                    'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'):
                try:
                    from django.conf import settings
                    # Get the last part of the dotted path as the app name.
                    options += [(a.split('.')[-1], 0) for a in settings.INSTALLED_APPS]
                except ImportError:
                    # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The
                    # user will find out once they execute the command.
                    pass
            options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in
                        subcommand_cls.option_list]
            # filter out previously specified options from available options
            prev_opts = [x.split('=')[0] for x in cwords[1:cword-1]]
            options = [opt for opt in options if opt[0] not in prev_opts]

            # filter options by current input
            options = sorted([(k, v) for k, v in options if k.startswith(curr)])
            for option in options:
                opt_label = option[0]
                # append '=' to options which require args
                if option[1]:
                    opt_label += '='
                print(opt_label)
        sys.exit(1)

Example 50

Project: GAE-Bulk-Mailer
Source File: i18n.py
View license
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if 'language' in request.GET:
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')
    packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    en_selected = locale.startswith('en')
    en_catalog_missing = True
    # paths of requested packages
    for package in packages:
        p = importlib.import_module(package)
        path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale')
        paths.append(path)
    # add the filesystem paths listed in the LOCALE_PATHS setting
    paths.extend(list(reversed(settings.LOCALE_PATHS)))
    # first load all english languages files for defaults
    for path in paths:
        try:
            catalog = gettext_module.translation(domain, path, ['en'])
            t.update(catalog._catalog)
        except IOError:
            pass
        else:
            # 'en' is the selected language and at least one of the packages
            # listed in `packages` has an 'en' catalog
            if en_selected:
                en_catalog_missing = False
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        # If the currently selected language is English but it doesn't have a
        # translation catalog (presumably due to being the language translated
        # from) then a wrong language catalog might have been loaded in the
        # previous step. It needs to be discarded.
        if en_selected and en_catalog_missing:
            t = {}
        else:
            locale_t = {}
            for path in paths:
                try:
                    catalog = gettext_module.translation(domain, path, [locale])
                except IOError:
                    catalog = None
                if catalog is not None:
                    locale_t.update(catalog._catalog)
            if locale_t:
                t = locale_t
    src = [LibHead]
    plural = None
    if '' in t:
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':',1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if isinstance(k, six.string_types):
            csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
        elif isinstance(k, tuple):
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError(k)
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src.append(LibFormatHead)
    src.append(get_formats())
    src.append(LibFormatFoot)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')