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.

155 Examples 7

Example 51

Project: hue Source File: flush.py
    def handle_noargs(self, **options):
        database = options.get('database')
        connection = connections[database]
        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_syncdb = options.get('inhibit_post_syncdb', False)

        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:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = 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: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.atomic(using=database,
                                        savepoint=connection.features.can_rollback_ddl):
                    cursor = connection.cursor()
                    for sql in sql_list:
                        cursor.execute(sql)
            except Exception as e:
                new_msg = (
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.\n"
                    "The full error: %s") % (connection.settings_dict['NAME'], e)
                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])

            if not inhibit_post_syncdb:
                self.emit_post_syncdb(verbosity, interactive, database)

            # Reinstall the initial_data fixture.
            if options.get('load_initial_data'):
                # Reinstall the initial_data fixture.
                call_command('loaddata', 'initial_data', **options)

        else:
            self.stdout.write("Flush cancelled.\n")

Example 52

Project: nexus Source File: __init__.py
Function: auto_discover
def autodiscover(site=None):
    """
    Auto-discover INSTALLED_APPS nexus.py modules and fail silently when
    not present. This forces an import on them to register any api bits they
    may want.

    Specifying ``site`` will register all auto discovered modules with the new site.
    """
    # Bail out if autodiscover didn't finish loading from a previous call so
    # that we avoid running autodiscover again when the URLconf is loaded by
    # the exception handler to resolve the handler500 view.  This prevents an
    # admin.py module with errors from re-registering models and raising a
    # spurious AlreadyRegistered exception (see #8245).
    global LOADING
    if LOADING:
        return
    LOADING = True

    if site:
        orig_site = globals()['site']
        globals()['site'] = locals()['site']

    import imp
    from django.utils.importlib import import_module
    from django.conf import settings

    for app in settings.INSTALLED_APPS:
        # For each app, we need to look for an api.py inside that app's
        # package. We can't use os.path here -- recall that modules may be
        # imported different ways (think zip files) -- so we need to get
        # the app's __path__ and look for admin.py on that path.

        # Step 1: find out the app's __path__ Import errors here will (and
        # should) bubble up, but a missing __path__ (which is legal, but weird)
        # fails silently -- apps that do weird things with __path__ might
        # need to roll their own admin registration.
        try:
            app_path = import_module(app).__path__
        except (AttributeError, ImportError):
            continue

        # Step 2: use imp.find_module to find the app's admin.py. For some
        # reason imp.find_module raises ImportError if the app can't be found
        # but doesn't actually try to import the module. So skip this app if
        # its admin.py doesn't exist
        try:
            imp.find_module('nexus_modules', app_path)
        except ImportError:
            continue

        # Step 3: import the app's admin file. If this has errors we want them
        # to bubble up.
        import_module("%s.nexus_modules" % app)
    # # load builtins
    # from gargoyle.builtins import *

    if site:
        globals()['site'] = orig_site

    # autodiscover was successful, reset loading flag.
    LOADING = False

Example 53

Project: pootle Source File: views.py
Function: get_context_data
    def get_context_data(self, *args, **kwargs):
        priority = (
            self.store.priority
            if 'virtualfolder' in settings.INSTALLED_APPS
            else None)
        return {
            'unit': self.object,
            'form': self.get_unit_edit_form(),
            'comment_form': self.get_unit_comment_form(),
            'priority': priority,
            'store': self.store,
            'directory': self.directory,
            'user': self.request.user,
            'project': self.project,
            'language': self.language,
            'source_language': self.source_language,
            'cantranslate': check_user_permission(self.request.user,
                                                  "translate",
                                                  self.directory),
            'cantranslatexlang': check_user_permission(self.request.user,
                                                       "administrate",
                                                       self.project.directory),
            'cansuggest': check_user_permission(self.request.user,
                                                "suggest",
                                                self.directory),
            'canreview': check_user_permission(self.request.user,
                                               "review",
                                               self.directory),
            'has_admin_access': check_user_permission(self.request.user,
                                                      'administrate',
                                                      self.directory),
            'altsrcs': {x.id: x.data for x in self.get_alt_srcs()},
            'unit_values': self.get_unit_values(),
            'target_nplurals': self.get_target_nplurals(),
            'has_plurals': self.object.hasplural(),
            'filetype': self.object.store.filetype.name,
        }

Example 54

Project: django-nonrel Source File: flush.py
    def handle_noargs(self, **options):
        db = options.get('database', DEFAULT_DB_ALIAS)
        connection = connections[db]
        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_module('.management', app_name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, 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: """ % connection.settings_dict['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(using=db)
                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""" % (connection.settings_dict['NAME'], e))
            transaction.commit_unless_managed(using=db)

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            all_models = []
            for app in models.get_apps():
                all_models.extend([
                    m for m in models.get_models(app, include_auto_created=True)
                    if router.allow_syncdb(db, m)
                ])
            emit_post_sync_signal(set(all_models), verbosity, interactive, db)

            # Reinstall the initial_data fixture.
            kwargs = options.copy()
            kwargs['database'] = db
            call_command('loaddata', 'initial_data', **kwargs)

        else:
            print "Flush cancelled."

Example 55

Project: foodnetwork Source File: jobs.py
Function: get_jobs
def get_jobs(when=None, only_scheduled=False):
    """
    Returns a dictionary mapping of job names together with there respective
    application class.
    """
    global _jobs
    # FIXME: HACK: make sure the project dir is on the path when executed as ./manage.py
    import sys
    try:
        cpath = os.path.dirname(os.path.realpath(sys.argv[0]))
        ppath = os.path.dirname(cpath)
        if ppath not in sys.path:
            sys.path.append(ppath)
    except:
        pass
    if _jobs is None:
        _jobs = {}
        if True:
            from django.conf import settings
            for app_name in settings.INSTALLED_APPS:
                scandirs = (None, 'hourly', 'daily', 'weekly', 'monthly', 'yearly')
                if when:
                    scandirs = None, when
                for subdir in scandirs:
                    try:
                        path = find_job_module(app_name, subdir)
                        for name in find_jobs(path):
                            if (app_name, name) in _jobs:
                                raise JobError("Duplicate job %s" % name)
                            job = import_job(app_name, name, subdir)
                            if only_scheduled and job.when == None:
                                # only include jobs which are scheduled
                                continue
                            if when and job.when != when:
                                # generic job not in same schedule
                                continue
                            _jobs[(app_name, name)] = job
                    except ImportError:
                        pass # No job module -- continue scanning
    return _jobs

Example 56

Project: tendenci Source File: load_base_defaults.py
    def call_loaddata(self, reset_nav=False):
        """
        This calls the loaddata command on all
        non profit fixtures.
        The order - It's a big deal.
        """
        from tendenci.apps.files.models import File

        if reset_nav:
            from tendenci.apps.navs.models import NavItem
            try:
                main_nav_items = NavItem.objects.filter(nav_id=1)
                main_nav_items.delete()
            except:
                pass

        staff_installed = "addons.staff" in settings.INSTALLED_APPS
        print 'npo_default_auth_user.json'
        call_command('loaddata', 'npo_default_auth_user.json')
        print 'npo_default_entities.json'
        call_command('loaddata', 'npo_default_entities.json')
        print 'npo_default_user_groups.json'
        call_command('loaddata', 'npo_default_user_groups.json')
        print 'npo_default_files.json'
        call_command('loaddata', 'npo_default_files.json')
        print 'paymentmethod.json'
        call_command('loaddata', 'paymentmethod.json')
        print 'load default_forums.json'
        call_command('loaddata', 'default_forums.json')
        print 'load npo_default_directories_pricings.json'
        call_command('loaddata', 'npo_default_directories_pricings.json')
        
        # default sqls for explorer
        call_command('load_sqlexplorer_defaults')
        

        box_ct = ContentType.objects.get(app_label='boxes', model='box')
        story_ct = ContentType.objects.get(app_label='stories', model='story')
        setting_ct = ContentType.objects.get(app_label='site_settings', model='setting')
        if staff_installed:
            staff_ct = ContentType.objects.get(app_label='staff', model='staff')

        files = File.objects.all()

        print 'updating files'
        for f in files:

            if 'box' in unicode(f.file):
                f.content_type = box_ct
            if 'story' in unicode(f.file):
                f.content_type = story_ct
            if 'setting' in unicode(f.file):
                f.content_type = setting_ct
            if 'staff' in unicode(f.file) and staff_installed:
                f.content_type = staff_ct

            f.save()

        suffix_list = [
            'profiles_profile',
            'forms',
            'boxes',
            'pages',
            'navs',
            'stories',
            'videos',
        ]

        # call loaddata on fixtures
        for suffix in suffix_list:
            filename = 'npo_default_%s.json' % suffix

            print filename
            call_command('loaddata', filename)

Example 57

Project: decode-Django Source File: options.py
Function: contribute_to_class
    def contribute_to_class(self, cls, name):
        # 参数说明
        # cls: 是一个 model 实例
        # name: model 的名字

        from django.db import connection
        from django.db.backends.util import truncate_name

        # 将自己挂钩到 cls._meta, 即挂钩到一个 model
        cls._meta = self

        # 是否已经安装
        self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS

        # First, construct the default values for these options.
        self.object_name = cls.__name__
        self.module_name = self.object_name.lower()
        self.verbose_name = get_verbose_name(self.object_name)

        # Next, apply any overridden values from 'class Meta'.
        # 将数据从 slef.meta 中拷贝出来
        if self.meta:
            meta_attrs = self.meta.__dict__.copy()
            for name in self.meta.__dict__:
                # Ignore any private attributes that Django doesn't care about.
                # NOTE: We can't modify a dictionary's contents while looping
                # over it, so we loop over the *original* dictionary instead.
                if name.startswith('_'):
                    del meta_attrs[name]

            for attr_name in DEFAULT_NAMES:
                if attr_name in meta_attrs:
                    setattr(self, attr_name, meta_attrs.pop(attr_name))

                elif hasattr(self.meta, attr_name):
                    setattr(self, attr_name, getattr(self.meta, attr_name))

            # unique_together can be either a tuple of tuples, or a single
            # tuple of two strings. Normalize it to a tuple of tuples, so that
            # calling code can uniformly expect that.
            ut = meta_attrs.pop('unique_together', self.unique_together)
            if ut and not isinstance(ut[0], (tuple, list)):
                ut = (ut,)
            self.unique_together = ut

            # verbose_name_plural is a special case because it uses a 's'
            # by default.
            # 详细名称的复数 ???
            if self.verbose_name_plural is None:
                self.verbose_name_plural = string_concat(self.verbose_name, 's')

            # Any leftover attributes must be invalid.
            # 除了以上属性, 其他都是无效的, 异常
            if meta_attrs != {}:
                raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()))
        else:
            self.verbose_name_plural = string_concat(self.verbose_name, 's')

        # 居然直接删除, 是因为所有的属性都已经拷贝出来了???
        del self.meta

        # If the db_table wasn't provided, use the app_label + module_name.
        if not self.db_table:
            self.db_table = "%s_%s" % (self.app_label, self.module_name)
            self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())

Example 58

Project: django-easymode Source File: __init__.py
Function: init_db
def initdb(cls):
    """
    This is a class decorator.

    Adds a setUp and tearDown method to a TestCase class.
    The setup will add tests to the installed apps, causing
    the models in the tests folder to be loaded.

    Then at the end they are removed again.
    """

    orig_pre_setup = getattr(cls, '_pre_setup')
    orig_post_teardown = getattr(cls, '_post_teardown')

    @wraps(orig_pre_setup)
    def _pre_setup(self):
        self.settingsManager = TestSettingsManager()
        self.settingsManager.set(INSTALLED_APPS=settings.INSTALLED_APPS + (
            'easymode',
            'easymode.tests',
            ),
        )

        for skipped_test in getattr(settings, 'SKIPPED_TESTS', []):
            if hasattr(cls, skipped_test):
                setattr(cls, skipped_test, lambda x: True)

        if orig_pre_setup:
            orig_pre_setup(self)

    @wraps(orig_post_teardown)
    def _post_teardown(self):
        if orig_post_teardown:
            orig_post_teardown(self)

        # don't try to remove the locale dir in the project dir because it has
        # all translations
        # test cases should have a separate locale dir, preferably in /tmp
        if not (os.path.normpath(settings.LOCALE_DIR) == \
            os.path.normpath(settings.PROJECT_DIR)):
            locale_dir = os.path.join(settings.LOCALE_DIR, 'locale')
            if os.path.exists(locale_dir):
                shutil.rmtree(locale_dir)
        self.settingsManager.revert()

    cls._pre_setup = _pre_setup
    cls._post_teardown = _post_teardown
    return cls

Example 59

Project: django-extensions Source File: create_app.py
Function: handle
    @signalcommand
    def handle(self, *args, **options):
        from django_extensions.utils.deprecation import MarkedForDeprecationWarning
        warnings.warn(
            "Deprecated: "
            "\"create_app\" is marked for depreciaton and will most likely "
            "be removed in future releases. Use \"startapp --template\" instead.",
            MarkedForDeprecationWarning
        )
        if django.VERSION[:2] >= (1, 10):
            raise CommandError("This command is deprecated. Please use \"startapp --template\" instead.")

        project_dir = os.getcwd()
        project_name = os.path.split(project_dir)[-1]
        app_name = options['app_name']
        app_template = options.get('app_template') or os.path.join(django_extensions.__path__[0], 'conf', 'app_template')
        app_dir = os.path.join(options.get('parent_path') or project_dir, app_name)
        dia_path = options.get('dia_path') or os.path.join(project_dir, '%s.dia' % app_name)

        if not os.path.exists(app_template):
            raise CommandError("The template path, %r, does not exist." % app_template)

        if not re.search(r'^\w+$', app_name):
            raise CommandError("%r is not a valid application name. Please use only numbers, letters and underscores." % app_name)

        dia_parse = options.get('dia_path') or options.get('dia_parse')
        if dia_parse:
            if not os.path.exists(dia_path):
                raise CommandError("The diagram path, %r, does not exist." % dia_path)
            if app_name in settings.INSTALLED_APPS:
                raise CommandError("The application %s should not be defined in the settings file. Please remove %s now, and add it after using this command." % (app_name, app_name))
            tables = [name for name in connection.introspection.table_names() if name.startswith('%s_' % app_name)]
            if tables:
                raise CommandError("%r application has tables in the database. Please delete them." % app_name)

        try:
            os.makedirs(app_dir)
        except OSError as e:
            raise CommandError(e)

        copy_template(app_template, app_dir, project_name, app_name)

        if dia_parse:
            generate_models_and_admin(dia_path, app_dir, project_name, app_name)

        self.stdout.write("Application %r created.\n" % app_name)
        self.stdout.write("Please add now %r and any other dependent application in settings.INSTALLED_APPS, and run 'manage syncdb'\n" % app_name)

Example 60

Project: xadmin Source File: __init__.py
Function: auto_discover
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLASS_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "passwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclass(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                pass

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site.restore_registry(before_import_registry)

            # 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, 'adminx'):
                raise

Example 61

Project: cgstudiomap Source File: __init__.py
Function: execute
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader.
                    pass

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)

Example 62

Project: django-url-framework Source File: site.py
Function: auto_discover
    def autodiscover(self, include_apps = [], exclude_apps = []):
        """Autodiscover all urls within all applications that regex match any entry in 'include_apps'
        and exclude any in 'exclude_apps'.
        """
        
        if type(include_apps) not in (list, tuple):
            include_apps = (include_apps,)
        if type(exclude_apps) not in (list, tuple):
            exclude_apps = (exclude_apps,)
        
        if len(include_apps) == 0:
            include_apps = settings.INSTALLED_APPS
        
        for app in settings.INSTALLED_APPS:
            must_skip = False
            if app.endswith('django_url_framework'):
                continue
            
            for inc in include_apps:
                if re.search(inc, app):
                    must_skip = False
                    break
                else:
                    must_skip = True
            for excl in exclude_apps:
                if re.search(excl, app):
                    must_skip = True
                    break
            if must_skip:
                continue
            try:
                available_controllers = []
                app_path = import_module(app).__path__
                if app_path[0][-1] != os.path.sep:
                    app_path[0] = app_path[0]+os.path.sep
                    
                for f in dircache.listdir(app_path[0]):
                    if f.endswith('_controller.py'):
                        available_controllers.append(f[:-14])
                self.load_controllers(app_path, available_controllers)
            except AttributeError, e:
                self.logger.exception(e)
                continue

Example 63

Project: jaikuenginepatch Source File: generatemedia.py
Function: update_media
def updatemedia(compressed=None):
    if 'mediautils' not in settings.INSTALLED_APPS:
        return

    # Remove unused media versions
    if os.path.exists(GENERATED_MEDIA):
        entries = os.listdir(GENERATED_MEDIA)
        if len(entries) != 1 or MEDIA_VERSION not in entries:
            shutil.rmtree(GENERATED_MEDIA)

    from ragendja.apputils import get_app_dirs

    # Remove old media if settings got modified (too much work to check
    # if COMBINE_MEDIA was changed)
    mtime = getmtime(os.path.join(PROJECT_ROOT, 'settings.py'))
    for app_path in get_app_dirs().values():
        path = os.path.join(app_path, 'settings.py')
        if os.path.exists(path) and os.path.getmtime(path) > mtime:
            mtime = os.path.getmtime(path)
    if os.path.exists(MEDIA_ROOT) and getmtime(MEDIA_ROOT) <= mtime:
        shutil.rmtree(MEDIA_ROOT)
    
    if not os.path.exists(MEDIA_ROOT):
        os.makedirs(MEDIA_ROOT)
    if not os.path.exists(DYNAMIC_MEDIA):
        os.makedirs(DYNAMIC_MEDIA)

    if compressed is None:
        compressed = not getattr(settings, 'FORCE_UNCOMPRESSED_MEDIA', False)

    media_dirs = get_media_dirs()
    data = {'media_dirs': media_dirs}
    targets = get_targets(**data)
    copy_targets = get_copy_targets(**data)
    target_names = [target[0] for target in targets]

    # Remove unneeded files
    cleanup_dir(MEDIA_ROOT, target_names + copy_targets.keys())
    dynamic_files = []
    for target, kwargs, group in targets:
        for handler in group:
            if callable(handler):
                dynamic_files.append(get_file_path(handler, **kwargs))
    cleanup_dir(DYNAMIC_MEDIA, dynamic_files)

    # Copy files
    for target in sorted(copy_targets.keys()):
        # Only overwrite files if they've been modified. Also, only
        # copy files that won't get combined.
        path = copy_targets[target]
        generated = os.path.join(MEDIA_ROOT, target.replace('/', os.sep))
        if os.path.exists(generated) and \
                getmtime(generated) >= getmtime(path):
            continue
        print 'Copying %s...' % target
        copy_file(path, generated)
    
    # Update dynamic files
    cache = {}
    for target, kwargs, group in targets:
        for handler in group:
            if callable(handler):
                update_dynamic_file(handler, cache, **kwargs)

    # Combine media files
    for target, kwargs, group in targets:
        files = [get_file_path(handler, **kwargs) for handler in group]
        path = os.path.join(MEDIA_ROOT, target.replace('/', os.sep))
        # Only overwrite files if they've been modified
        if os.path.exists(path):
            target_mtime = getmtime(path)
            if not [1 for name in files if os.path.exists(name) and
                                           getmtime(name) >= target_mtime]:
                continue
        print 'Combining %s...' % target
        dirpath = os.path.dirname(path)
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)
        file = codecs.open(path, 'w', 'utf-8')
        file.write(get_target_content(group, cache, **kwargs))
        file.close()
        if compressed:
            compress_file(path)

Example 64

Project: django-nonrel Source File: __init__.py
Function: auto_complete
    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 not os.environ.has_key('DJANGO_AUTO_COMPLETE'):
            return

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

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

        subcommands = get_commands().keys() + ['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', 'reset', 'sql', 'sqlall',
                               'sqlclear', 'sqlcustom', 'sqlindexes',
                               'sqlreset', '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 = filter(lambda (x, v): x not in prev_opts, options)

            # 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 65

Project: oioioi Source File: views.py
@enforce_condition(is_teacher)
def teacher_dashboard_view(request):
    contest_context = []
    min_date = datetime.today() - timedelta(days=7)

    contests = [contest for contest in visible_contests(request)]
    are_contests_limited = len(contests) > MAX_CONTESTS_ON_PAGE
    visible_contests_count = len(contests)

    contests = [x for x in contests if is_teachers(x)
                                    and can_admin_contest(request.user, x)]
    if len(contests) < visible_contests_count:
        are_contests_limited = True
    contests.sort(key=lambda x: x.creation_date, reverse=True)

    contests = contests[:MAX_CONTESTS_ON_PAGE]

    if 'oioioi.portals' in settings.INSTALLED_APPS:
        has_portal = global_portal_exists(request)
    else:
        has_portal = False

    for contest in contests:

        scores = [result.score.to_int() for result in
                  UserResultForContest.objects.filter(contest=contest).all()
                  if result.score is not None]

        max_score = 0
        for problem_inst in ProblemInstance.objects.filter(contest=contest):
            user_results = \
                UserResultForProblem.objects.filter(
                    problem_instance=problem_inst,
                    submission_report__isnull=False)
            if user_results.count() > 0:
                for result in user_results:
                    score_report = result.submission_report.score_report

                    if score_report_is_valid(score_report):
                        max_score += score_report.max_score.to_int()
                        break

        contest_dict = {
            'id': contest.id,
            'name': contest.name,
            'round_count': Round.objects.filter(contest=contest).count(),
            'task_count': ProblemInstance.objects.filter(
                contest=contest).count(),
            'user_count': User.objects.filter(
                participant__contest=contest).count(),
            'submission_count': Submission.objects.filter(
                problem_instance__contest=contest).count(),
            'recent_submission_count': Submission.objects.filter(
                problem_instance__contest=contest, date__gte=min_date
            ).count(),
            'recent_question_count': Message.objects.filter(
                contest=contest, kind='QUESTION', date__gte=min_date
            ).count(),
            'max_score': max_score,
            'scores': scores,
        }
        contest_context.append(contest_dict)
    context = {
        'contests': contest_context,
        'are_contests_limited': are_contests_limited,
        'has_portal': has_portal
    }
    if has_portal:
        context['portal_path'] = Portal.objects.filter(owner=None)[0] \
            .root.get_path()

    return TemplateResponse(request,
                            'simpleui/main_dashboard/dashboard.html', context)

Example 66

Project: django-wordpress Source File: import_to_blogango.py
Function: handle
    def handle(self, *args, **kwargs):
        if 'blogango' not in settings.INSTALLED_APPS:
            raise CommandError('Add blogango to installed apps to import posts from wordpress')
        
        # get the offset id from blogango
        blog_entries = BlogEntry.objects.all().order_by('-id')
        offset = blog_entries.count() and blog_entries[0].id or 0
        wp_posts = Post.objects.filter(id__gt=offset, post_status='publish', post_type='post')
        
        for wp_post in wp_posts:
            # insert into BlogEntry
            print wp_post.post_date

            blog_entry = BlogEntry.objects.create(id=wp_post.id,
                                                  title=wp_post.post_title,
                                                  slug=slugify(wp_post.post_title),
                                                  text=wp_post.post_content,
                                                  created_by=get_auth_user(wp_post.post_author))
            blog_entry.created_on = wp_post.post_date
            blog_entry.save()
            
            tables = ['wp_term_taxonomy', 'wp_term_relationships']
            where = ['wp_term_relationships.object_id = %s', 
                     'wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id', 
                     'wp_term_taxonomy.term_id = wp_terms.term_id', 
                     'wp_term_taxonomy.taxonomy = %s']
                
            # get categories
            categories = Term.objects.extra(tables=tables, where=where, params=[wp_post.id, 'category'])
            for category in categories:blog_entry.tags.add(category.name)
            
            # get tags
            # tags = Term.objects.extra(tables=tables, where=where, params=[wp_post.id, 'post_tag'])
            # for tag in tags:blog_entry.tags.add(tag.name)
            
            # add comments
            wp_comments = WpComment.objects.filter(comment_post_id=wp_post.id, comment_approved=1)
            for wp_comment in wp_comments:
                if wp_comment.comment_type == 'pingback':continue
                if wp_comment.comment_agent in COMMENT_AGENTS:
                    comment = Reaction.objects.create(text=wp_comment.comment_content,
                                                       comment_for=blog_entry,
                                                       user_name=wp_comment.comment_author,
                                                       user_url=wp_comment.comment_author_url,
                                                       source=wp_comment.comment_agent.lstrip('btc_'))
                else:
                    comment = Comment.objects.create(text=wp_comment.comment_content,
                                                     comment_for=blog_entry,
                                                     user_name=wp_comment.comment_author,
                                                     user_url=wp_comment.comment_author_url,
                                                     email_id=wp_comment.comment_author_email)
                comment.created_on = wp_comment.comment_date
                comment.is_public = True
                comment.save()

Example 67

Project: tendenci Source File: load_sqlexplorer_defaults.py
Function: handle
    def handle(self, **options):
        if 'explorer' in settings.INSTALLED_APPS:
            from explorer.models import Query
            queries = (
('All Interactive Users',
'All Interactive Users - People Who Can Login to the Site',
"""SELECT u.first_name, u.last_name, u.email, u.username, u.is_staff, u.is_superuser,  
        p.salutation, p.company, p.position_title, p.phone, p.address, p.address2, 
        p.member_number, p.city, p.state, p.zipcode, p.country, p.url, p.sex,
        p.address_type, p.phone2, p.fax, p.work_phone, p.home_phone, p.mobile_phone,
        p.notes, p.admin_notes
FROM auth_user u INNER JOIN profiles_profile p
ON u.id=p.user_id
WHERE u.is_active=True
AND p.status=True
AND p.status_detail='active'"""),
('All Memberships',
'All Memberships',
"""SELECT u.first_name, u.last_name, u.email, u.username, u.is_staff, u.is_superuser,
        p.salutation, p.company, p.position_title, p.phone, p.address, p.address2,
        p.member_number, p.city, p.state, p.zipcode, p.country, p.url, p.sex,
        p.address_type, p.phone2, p.fax, p.work_phone, p.home_phone, p.mobile_phone,
        m.membership_type_id, m.renewal, m.certifications, m.work_experience,
        m.referer_url, m.referral_source, m.join_dt, m.expire_dt, m.renew_dt,
        m.primary_practice, m.how_long_in_practice, m.application_approved,
        m.application_approved_dt, m.areas_of_expertise, m.home_state,
        m.year_left_native_country, m.network_sectors, m.networking,
        m.government_worker, m.government_agency, m.license_number,
        m.license_state, m.status_detail
FROM auth_user u
INNER JOIN profiles_profile p
ON u.id=p.user_id
INNER JOIN memberships_membershipdefault m
ON m.user_id=u.id
WHERE u.is_active=True
AND p.status=True
AND m.status_detail <> 'archive'"""),
('All Corporate Memberships',
'All corporate memberships',
 """SELECT cp.name, cp.address, cp.address2, cp.city, cp.state, cp.zip, cp.country,
     cp.phone, cp.email, cp.url, cp.number_employees, cp.chapter, cp.tax_exempt,
     cp.annual_revenue, cp.annual_ad_expenditure, cp.description, cp.expectations,
     cp.notes, cp.referral_source, cp.ud1, cp.ud2, cp.ud3, cp.ud4, cp.ud5, cp.ud6,
     cp.ud7, cp.ud8, cm.corporate_membership_type_id, cm.renewal, cm.renew_dt,
     cm.join_dt, cm.expiration_dt, cm.approved, cm.admin_notes, cm.status_detail 
FROM corporate_memberships_corpprofile cp
INNER JOIN corporate_memberships_corpmembership cm
ON cp.id=cm.corp_profile_id
WHERE cm.status_detail <> 'archive'"""),
('Users By Group ID (All Groups)',
'All groups - dump this into Excel and filter by the group_name field as needed',
"""SELECT ug.name as group_name, u.first_name, u.last_name, u.email, u.username, u.is_staff, 
      u.is_superuser, p.salutation, p.company, p.position_title, p.phone, 
      p.address, p.address2, p.member_number, p.city, p.state, p.zipcode, 
      p.country, p.url, p.sex, p.address_type, p.phone2, p.fax, p.work_phone, 
      p.home_phone, p.mobile_phone 
FROM auth_user u 
INNER JOIN profiles_profile p ON u.id=p.user_id 
INNER JOIN user_groups_groupmembership ugm on u.id=ugm.member_id 
INNER JOIN user_groups_group ug on ug.id=ugm.group_id 
WHERE ug.id>0
AND ugm.status=True 
AND ugm.status_detail='active'"""),
('Users By Group ID (Edit the Group ID)',
'Users by Group ID - this query shows group id = 1 on line number 10, so edit that for whichever group you are looking for.',
"""SELECT ug.name as group_name, u.first_name, u.last_name, u.email, u.username, u.is_staff, 
      u.is_superuser, p.salutation, p.company, p.position_title, p.phone, 
      p.address, p.address2, p.member_number, p.city, p.state, p.zipcode, 
      p.country, p.url, p.sex, p.address_type, p.phone2, p.fax, p.work_phone, 
      p.home_phone, p.mobile_phone 
FROM auth_user u 
INNER JOIN profiles_profile p ON u.id=p.user_id 
INNER JOIN user_groups_groupmembership ugm on u.id=ugm.member_id 
INNER JOIN user_groups_group ug on ug.id=ugm.group_id 
WHERE ug.id=1 
AND ugm.status=True 
AND ugm.status_detail='active'"""),
('Tables - List All Database Tables',
'A list of all tables including system tables',
"""select tablename from pg_tables"""),
('Users In the Database On The Site, Not All Can Login',
'This lists everyone in the auth_user table which is the default django table for authentication but also used for anyone who has filled out a contact form. The passwords are encrypted and cant be decrypted (no way around that) but it does have the basics of all humans (does NOT mean they can login.)',
"""select id, first_name, last_name, email, username, last_login, is_superuser, is_staff, is_active, date_joined  from auth_user;"""),
('Users in Database with Membership Details',
'Users in Database with Membership Details',
"""select u.id, u.first_name, u.last_name, u.email, u.username, u.last_login, u.is_superuser, u.is_staff, u.is_active, m.member_number, m.join_dt, m.expire_dt
from auth_user u
inner join memberships_membershipdefault m on m.user_id = u.id
where m.status=true
and m.status_detail<>'archive'"""),
)
            for title, description, sql in queries:
                query = Query(title=title,
                              description=description,
                              sql=sql)
                query.save()
                print 'Inserted: ', title
                
        else:
            print 'NO default sqls loaded for SQL Explorer because django-sqlexplorer is not installed'

Example 68

Project: django-compositepks Source File: __init__.py
Function: get_commands
def get_commands():
    """
    Returns a dictionary mapping command names to their callback applications.

    This works by looking for a management.commands package in django.core, and
    in each installed application -- if a commands package exists, all commands
    in that package are registered.

    Core commands are always included. If a settings module has been
    specified, user-defined commands will also be included, the
    startproject command will be disabled, and the startapp command
    will be modified to use the directory in which the settings module appears.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    global _commands
    if _commands is None:
        _commands = dict([(name, 'django.core') for name in find_commands(__path__[0])])

        # Find the installed apps
        try:
            from django.conf import settings
            apps = settings.INSTALLED_APPS
        except (AttributeError, EnvironmentError, ImportError):
            apps = []

        # Find the project directory
        try:
            from django.conf import settings
            project_directory = setup_environ(
                __import__(
                    settings.SETTINGS_MODULE, {}, {},
                    (settings.SETTINGS_MODULE.split(".")[-1],)
                ), settings.SETTINGS_MODULE
            )
        except (AttributeError, EnvironmentError, ImportError):
            project_directory = None

        # Find and load the management module for each installed app.
        for app_name in apps:
            try:
                path = find_management_module(app_name)
                _commands.update(dict([(name, app_name)
                                       for name in find_commands(path)]))
            except ImportError:
                pass # No management module - ignore this app

        if project_directory:
            # Remove the "startproject" command from self.commands, because
            # that's a django-admin.py command, not a manage.py command.
            del _commands['startproject']

            # Override the startapp command so that it always uses the
            # project_directory, not the current working directory
            # (which is default).
            from django.core.management.commands.startapp import ProjectCommand
            _commands['startapp'] = ProjectCommand(project_directory)

    return _commands

Example 69

Project: snowy Source File: migrate.py
Function: handle
    def handle(self, app=None, target=None, skip=False, merge=False, backwards=False, fake=False, db_dry_run=False, list=False, **options):

        # Work out what the resolve mode is
        resolve_mode = merge and "merge" or (skip and "skip" or None)
        # Turn on db debugging
        from south.db import db
        db.debug = True
        
        # NOTE: THIS IS DUPLICATED FROM django.core.management.commands.syncdb
        # This code imports any module named 'management' in INSTALLED_APPS.
        # The 'management' module is the preferred way of listening to post_syncdb
        # signals, and since we're sending those out with create_table migrations,
        # we need apps to behave correctly.
        for app_name in settings.INSTALLED_APPS:
            try:
                __import__(app_name + '.management', {}, {}, [''])
            except ImportError, exc:
                msg = exc.args[0]
                if not msg.startswith('No module named') or 'management' not in msg:
                    raise
        # END DJANGO DUPE CODE
        
        # if all_apps flag is set, shift app over to target
        if options['all_apps']:
            target = app
            app = None

        # Migrate each app
        if app:
            apps = [migration.get_app(app.split(".")[-1])]
        else:
            apps = migration.get_migrated_apps()
        silent = options.get('verbosity', 0) == 0
        
        if list and apps:
            list_migrations(apps)
        
        if not list:
            for app in apps:
                result = migration.migrate_app(
                    app,
                    resolve_mode = resolve_mode,
                    target_name = target,
                    fake = fake,
                    db_dry_run = db_dry_run,
                    silent = silent,
                    load_inital_data = not options['no_initial_data'],
                    skip = skip,
                )
                if result is False:
                    return

Example 70

Project: django-erp Source File: urls.py
Function: auto_discover
def autodiscover():
    """ Auto discover urls of installed applications.
    """
    global LOADING
    if LOADING:
        return
    
    LOADING = True

    import imp
    
    for app in settings.INSTALLED_APPS:
        if app.startswith('django.'):
            continue
            
        # Step 1: find out the app's __path__.
        try:
            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
        except AttributeError:
            continue

        # Step 2: use imp.find_module to find the app's urls.py.
        try:
            imp.find_module('urls', app_path)
        except ImportError:
            continue

        # Step 3: return the app's url patterns.
        pkg, sep, name = app.rpartition('.')
        global urlpatterns
        urlpatterns += patterns("", (r'^', include('%s.urls' % app)))
        
    LOADING = False

Example 71

Project: gunicorn Source File: django_wsgi.py
def reload_django_settings():
        mod = util.import_module(os.environ['DJANGO_SETTINGS_MODULE'])

        # Reload module.
        reload(mod)

        # Reload settings.
        # Use code from django.settings.Settings module.

        # Settings that should be converted into tuples if they're mistakenly entered
        # as strings.
        tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")

        for setting in dir(mod):
            if setting == setting.upper():
                setting_value = getattr(mod, setting)
                if setting in tuple_settings and type(setting_value) == str:
                    setting_value = (setting_value,)  # In case the user forgot the comma.
                setattr(settings, setting, setting_value)

        # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
        # of all those apps.
        new_installed_apps = []
        for app in settings.INSTALLED_APPS:
            if app.endswith('.*'):
                app_mod = util.import_module(app[:-2])
                appdir = os.path.dirname(app_mod.__file__)
                app_subdirs = os.listdir(appdir)
                name_pattern = re.compile(r'[a-zA-Z]\w*')
                for d in sorted(app_subdirs):
                    if (name_pattern.match(d) and
                            os.path.isdir(os.path.join(appdir, d))):
                        new_installed_apps.append('%s.%s' % (app[:-2], d))
            else:
                new_installed_apps.append(app)
        setattr(settings, "INSTALLED_APPS", new_installed_apps)

        if hasattr(time, 'tzset') and settings.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not
                    os.path.exists(os.path.join(zoneinfo_root,
                        *(settings.TIME_ZONE.split('/'))))):
                raise ValueError("Incorrect timezone setting: %s" %
                        settings.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = settings.TIME_ZONE
            time.tzset()

        # Settings are configured, so we can set up the logger if required
        if getattr(settings, 'LOGGING_CONFIG', False):
            # First find the logging configuration function ...
            logging_config_path, logging_config_func_name = settings.LOGGING_CONFIG.rsplit('.', 1)
            logging_config_module = util.import_module(logging_config_path)
            logging_config_func = getattr(logging_config_module, logging_config_func_name)

            # ... then invoke it with the logging settings
            logging_config_func(settings.LOGGING)

Example 72

Project: treeio Source File: runcron.py
Function: init
    def __init__(self, databases=None, noloop=False, *args, **kwargs):
        "Capture all cron jobs"
        if databases is None:
            databases = []

        signal.signal(signal.SIGTERM, self.stop)

        self.databases = databases or []
        self.jobs = []
        self.sleeptime = getattr(settings, 'HARDTREE_CRON_PERIOD', 60)
        self.priority_high = getattr(
            settings, 'HARDTREE_CRON_HIGH_PRIORITY', 10)
        self.priority_low = getattr(settings, 'HARDTREE_CRON_LOW_PRIORITY', 3)
        self.qualify_high = getattr(settings, 'HARDTREE_CRON_QUALIFY_HIGH', 10)
        self.qualify_run = getattr(
            settings, 'HARDTREE_CRON_QUALIFY_RUN', 86400)
        self.poolsize = getattr(settings, 'HARDTREE_CRON_POOL_SIZE', 10)
        self.softkill = getattr(settings, 'HARDTREE_CRON_SOFT_KILL', 0)
        self.hardkill = getattr(settings, 'HARDTREE_CRON_HARD_KILL', -1)
        self.gracewait = getattr(settings, 'HARDTREE_CRON_GRACE_WAIT', 5)
        self.noloop = noloop

        for module in settings.INSTALLED_APPS:
            import_name = str(
                module) + "." + settings.HARDTREE_MODULE_IDENTIFIER
            try:
                hmodule = __import__(import_name, fromlist=[str(module)])
                self.jobs.extend(hmodule.CRON)
            except ImportError:
                pass
            except AttributeError:
                pass

        if not self.databases:
            self.databases = [db for db in settings.DATABASES]

        cronlogger.info('Starting cron...')
        cronlogger.debug('DATABASES: ' + unicode(self.databases))
        cronlogger.debug('CRON_PERIOD: ' + unicode(self.sleeptime))
        cronlogger.debug('CRON_HIGH_PRIORITY: ' + unicode(self.priority_high))
        cronlogger.debug('CRON_LOW_PRIORITY: ' + unicode(self.priority_low))
        cronlogger.debug('CRON_QUALIFY_HIGH: ' + unicode(self.qualify_high))
        cronlogger.debug('CRON_POOL_SIZE: ' + unicode(self.poolsize))
        cronlogger.debug('CRON_SOFT_KILL: ' + unicode(self.softkill))
        cronlogger.debug('CRON_HARD_KILL: ' + unicode(self.hardkill))
        cronlogger.debug('CRON_GRACE_WAIT: ' + unicode(self.gracewait))
        cronlogger.debug('CRON_NO_LOOP: ' + unicode(self.noloop))

Example 73

Project: coursys Source File: testing.py
    def login_user(self, userid):
        """
        Login as specified user, does not depend on auth backend (hopefully)

        This is based on Client.login() with a small hack that does not
        require the call to authenticate()
        """
        if not 'django.contrib.sessions' in settings.INSTALLED_APPS:
            raise AssertionError("Unable to login without django.contrib.sessions in INSTALLED_APPS")
        try:
            user = User.objects.get(username=userid)
        except User.DoesNotExist:
            user = User(username=userid, password='')
            user.save()
        user.backend = "%s.%s" % ("django.contrib.auth.backends",
                                  "ModelBackend")
        engine = import_module(settings.SESSION_ENGINE)

        # Create a fake request to store login details.
        request = HttpRequest()
        #if self.session:
        #    request.session = self.session
        #else:
        request.session = engine.SessionStore()
        login(request, user)

        # Set the cookie to represent the session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)

        # Save the session values.
        request.session.save()

Example 74

Project: yawd-translations Source File: views.py
Function: get_context_data
    def get_context_data(self, **kwargs):
        context = super(GenerateTranslationMessagesView, self).get_context_data(**kwargs)
        
        if hasattr(self, 'error') and self.error:
            context['error'] = self.error
            return context
        
        #locate the current directory
        curr_dir = os.curdir
        domain_dict = {'django' : ['html','txt'], 'djangojs' : []}
        
        lang_files = []
        #iterate over the installed applications and copy their po files
        #for this language to the appropriate folder 
        for app_name in settings.INSTALLED_APPS:    
            
            mod = import_module(app_name)
            mod_root = os.path.dirname(mod.__file__)

            if not os.path.exists(os.path.join(mod_root, 'locale')):
                continue
            
            original_path = os.path.join(mod_root, 'locale',
                                         to_locale(self.language.name),
                                         'LC_MESSAGES')
            delete_at_the_end = False
            
            if not os.path.exists(original_path):
                if not app_name.startswith('django.contrib'):
                    try: #try to create language directory for the app
                        os.makedirs(original_path)
                        delete_at_the_end = True
                    except:
                        continue
                else:
                    continue

            if not app_name.startswith('django.contrib'):
                #move original files to a temp file
                for file_ in list(os.listdir(original_path)):
                        if file_.endswith('.po'):
                            shutil.copy(os.path.join(original_path, file_),
                                        os.path.join(original_path,
                                                     'original-%s' % file_))

                #copy the project-wise files to the appropriate directory
                if not self.request.GET.get('delete', 0):
                    #replace original file with the yawd version
                    #so that it gets updated
                    for f in list(os.listdir(self.po_path)):
                        if f.startswith('%s-' % app_name) and f.endswith('.po'):
                            shutil.copy(os.path.join(self.po_path, f),
                                        os.path.join(original_path,
                                                     f.replace('%s-' % app_name, '')))  

                #makemessages excluding the core applications
                os.chdir(mod_root)
                for key, value in domain_dict.items():
                    try:
                        management.call_command('makemessages', domain=key,
                                                extensions=value, locale=self.locale,
                                                verbosity=0)
                    except management.CommandError:
                        #Django could throw a CommandError if we process
                        #the domainjs and there are no messages to process.
                        pass
                os.chdir(curr_dir)

            #iterate over the application po files
            for file_ in list(os.listdir(original_path)):
                if not file_.startswith('original-') and file_.endswith('.po'):
                    original_file_path = os.path.join(original_path, file_)
                    file_name = '%s-%s' % (app_name, file_)
                    
                    #copy file
                    copy_path = os.path.join(self.po_path, file_name)
                    if self.request.GET.get('delete', 0) or \
                            not (app_name.startswith('django.contrib') \
                                 and os.path.exists(copy_path)):
                        shutil.copy(original_file_path, copy_path)
                        os.chmod(copy_path, 0664)

                    #unlink updated file
                    if not app_name.startswith('django.contrib'):
                        os.unlink(original_file_path)

                    lang_files.append(file_name)

            if not app_name.startswith('django.contrib'):
                if delete_at_the_end:
                    shutil.rmtree(os.path.join(mod_root, 'locale',
                                               to_locale(self.language.name)))
                else:
                    for file_ in os.listdir(original_path):
                        #put back the original application files
                        if file_.startswith('original-') and file_.endswith('.po'):
                            shutil.move(os.path.join(original_path, file_),
                                        os.path.join(original_path,
                                                     file_.replace('original-','')))

        #concat all messages in a single .po file for each domain
        for domain in domain_dict:
            file_name = '%s.po' % domain
            uni_django_path = os.path.join(self.po_path, file_name)

            if os.path.exists(uni_django_path):
                os.unlink(uni_django_path)

            source_files = [os.path.join(self.po_path, f) for f in lang_files \
                            if f.endswith(file_name)]
            if source_files:
                #merge .po files
                concat_message_files(source_files, uni_django_path)
                #compile django.po
                if not has_bom(uni_django_path):
                    compile_message_file(uni_django_path)

        #reset the cached translation messages so that
        #we do not need to restart the web server
        reset_translations(self.language.name)

        context['lang_files'] = sorted(lang_files)
        return context

Example 75

Project: mezzanine Source File: lazy_admin.py
Function: urls
    @property
    def urls(self):
        urls = [url("", super(LazyAdminSite, self).urls)]

        # Filebrowser admin media library.
        fb_name = getattr(settings, "PACKAGE_NAME_FILEBROWSER", "")
        if fb_name in settings.INSTALLED_APPS:
            try:
                fb_urls = import_dotted_path("%s.sites.site" % fb_name).urls
            except ImportError:
                fb_urls = "%s.urls" % fb_name
            urls = [
                # This gives the media library a root URL (which filebrowser
                # doesn't provide), so that we can target it in the
                # ADMIN_MENU_ORDER setting, allowing each view to correctly
                # highlight its left-hand admin nav item.
                url("^media-library/$", lambda r: redirect("fb_browse"),
                    name="media-library"),
                url("^media-library/", include(fb_urls)),
            ] + urls

        # Give the urlpattern for the user password change view an
        # actual name, so that it can be reversed with multiple
        # languages are supported in the admin.
        User = get_user_model()
        for admin in self._registry.values():
            user_change_password = getattr(admin, "user_change_password", None)
            if user_change_password:
                bits = (User._meta.app_label, User._meta.object_name.lower())
                urls = [
                    url("^%s/%s/(\d+)/password/$" % bits,
                        self.admin_view(user_change_password),
                        name="user_change_password"),
                ] + urls
                break

        # Misc Mezzanine urlpatterns that should reside under /admin/ url,
        # specifically for compatibility with SSLRedirectMiddleware.
        from mezzanine.core.views import displayable_links_js, static_proxy
        from mezzanine.generic.views import admin_keywords_submit
        urls += [
            url("^admin_keywords_submit/$", admin_keywords_submit,
                name="admin_keywords_submit"),
            url("^asset_proxy/$", static_proxy, name="static_proxy"),
            url("^displayable_links.js$", displayable_links_js,
                name="displayable_links_js"),
        ]
        if "mezzanine.pages" in settings.INSTALLED_APPS:
            from mezzanine.pages.views import admin_page_ordering
            urls.append(url("^admin_page_ordering/$", admin_page_ordering,
                            name="admin_page_ordering"))

        return urls

Example 76

Project: django-sqlalchemy Source File: flush.py
    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 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

        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.DJANGO_SQLALCHEMY_DBURI)
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                from sqlalchemy import create_engine
                # TODO: Original django code flushes by deleting rows from 
                # each table and reseting sequences back to zero.  This 
                # doesn't reset sequences.
                from django_sqlalchemy.backend import metadata, session
                for app in models.get_apps():
                    for table in sql._get_tables_for_app(app):
                        session.execute(table.delete())
                session.commit()
            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.DJANGO_SQLALCHEMY_DBURI, 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 77

Project: django-reporter Source File: registration.py
Function: auto_discover
def autodiscover():
    """
    Modified from django.contrib.admin.__init__ to look for reports.py
    files.
    
    Auto-discover INSTALLED_APPS reports.py modules and fail silently when
    not present. This forces an import on them to register any reports they
    may want.
    """
    # Bail out if autodiscover didn't finish loading from a previous call so
    # that we avoid running autodiscover again when the URLconf is loaded by
    # the exception handler to resolve the handler500 view.  This prevents a
    # reports.py module with errors from re-registering models and raising a
    # spurious AlreadyRegistered exception (see #8245).
    global LOADING
    if LOADING:
        return
    LOADING = True

    import imp
    from django.conf import settings

    for app in settings.INSTALLED_APPS:
        # For each app, we need to look for an reports.py inside that app's
        # package. We can't use os.path here -- recall that modules may be
        # imported different ways (think zip files) -- so we need to get
        # the app's __path__ and look for reports.py on that path.

        # Step 1: find out the app's __path__ Import errors here will (and
        # should) bubble up, but a missing __path__ (which is legal, but weird)
        # fails silently -- apps that do weird things with __path__ might
        # need to roll their own report registration.
        try:
            app_path = import_module(app).__path__
        except AttributeError:
            continue

        # Step 2: use imp.find_module to find the app's reports.py. For some
        # reason imp.find_module raises ImportError if the app can't be found
        # but doesn't actually try to import the module. So skip this app if
        # its reports.py doesn't exist
        try:
            imp.find_module('reports', app_path)
        except ImportError:
            continue

        # Step 3: import the app's reports file. If this has errors we want
        # them to bubble up.
        import_module("%s.reports" % app)
    # autodiscover was successful, reset loading flag.
    LOADING = False

Example 78

Project: jaikuenginepatch Source File: patch.py
def patch_app_engine():
    # This allows for using Paginator on a Query object. We limit the number
    # of results to 301, so there won't be any timeouts (301, so you can say
    # "more than 300 results").
    def __len__(self):
        return self.count(301)
    db.Query.__len__ = __len__

    # Add "model" property to Query (needed by generic views)
    class ModelProperty(object):
        def __get__(self, query, unused):
            try:
                return query._Query__model_class
            except:
                return query._model_class
    db.Query.model = ModelProperty()

    # Add a few Model methods that are needed for serialization and ModelForm
    def _get_pk_val(self):
        if self.has_key():
            return unicode(self.key())
        else:
            return None
    db.Model._get_pk_val = _get_pk_val
    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False
        return self._get_pk_val() == other._get_pk_val()
    db.Model.__eq__ = __eq__
    def __ne__(self, other):
        return not self.__eq__(other)
    db.Model.__ne__ = __ne__
    def pk(self):
        return self._get_pk_val()
    db.Model.id = db.Model.pk = property(pk)
    def serializable_value(self, field_name):
        """
        Returns the value of the field name for this instance. If the field is
        a foreign key, returns the id value, instead of the object. If there's
        no Field object with this name on the model, the model attribute's
        value is returned directly.

        Used to serialize a field's value (in the serializer, or form output,
        for example). Normally, you would just access the attribute directly
        and not use this method.
        """
        from django.db.models.fields import FieldDoesNotExist
        try:
            field = self._meta.get_field(field_name)
        except FieldDoesNotExist:
            return getattr(self, field_name)
        return getattr(self, field.attname)
    db.Model.serializable_value = serializable_value

    # Make Property more Django-like (needed for serialization and ModelForm)
    db.Property.serialize = True
    db.Property.editable = True
    db.Property.help_text = ''
    def blank(self):
        return not self.required
    db.Property.blank = property(blank)
    def _get_verbose_name(self):
        if not getattr(self, '_verbose_name', None):
            self._verbose_name = self.name.replace('_', ' ')
        return self._verbose_name
    def _set_verbose_name(self, verbose_name):
        self._verbose_name = verbose_name
    db.Property.verbose_name = property(_get_verbose_name, _set_verbose_name)

    def attname(self):
        return self.name
    db.Property.attname = property(attname)

    class Rel(object):
        def __init__(self, property):
            self.field_name = 'key'
            self.property = property
            self.to = property.reference_class
            self.multiple = True
            self.parent_link = False
            self.related_name = getattr(property, 'collection_name', None)
            self.through = None

    class RelProperty(object):
        def __get__(self, property, cls):
            if property is None:
                return self
            if not hasattr(property, 'reference_class'):
                return None
            if not hasattr(property, '_rel_cache'):
                property._rel_cache = Rel(property)
            return property._rel_cache
    db.Property.rel = RelProperty()

    def formfield(self, **kwargs):
        return self.get_form_field(**kwargs)
    db.Property.formfield = formfield

    # Add repr to make debugging a little bit easier
    from django.utils.datastructures import SortedDict
    def __repr__(self):
        d = SortedDict()
        if self.has_key() and self.key().name():
            d['key_name'] = self.key().name()
        for field in self._meta.fields:
            try:
                d[field.name] = getattr(self, field.name)
            except:
                d[field.name] = field.get_value_for_datastore(self)
        return u'%s(**%s)' % (self.__class__.__name__, repr(d))
    db.Model.__repr__ = __repr__

    # Add default __str__ and __unicode__ methods
    def __str__(self):
        return unicode(self).encode('utf-8')
    db.Model.__str__ = __str__
    def __unicode__(self):
        return unicode(repr(self))
    db.Model.__unicode__ = __unicode__

    # Replace save() method with one that calls put(), so a monkey-patched
    # put() will also work if someone uses save()
    def save(self):
        self.put()
    db.Model.save = save

    # Add _meta to Model, so porting code becomes easier (generic views,
    # xheaders, and serialization depend on it).
    from django.conf import settings
    from django.utils.encoding import force_unicode, smart_str
    from django.utils.translation import string_concat, get_language, \
        activate, deactivate_all
    class _meta(object):
        many_to_many = ()
        class pk:
            name = 'key'
            attname = 'pk'

        def __init__(self, model, bases):
            try:
                self.app_label = model.__module__.split('.')[-2]
            except IndexError:
                raise ValueError('Django expects models (here: %s.%s) to be defined in their own apps!' % (model.__module__, model.__name__))
            self.parents = [b for b in bases if issubclass(b, db.Model)]
            self.object_name = model.__name__
            self.module_name = self.object_name.lower()
            self.verbose_name = get_verbose_name(self.object_name)
            self.ordering = ()
            self.abstract = model is db.Model
            self.model = model
            self.unique_together = ()
            self.installed = model.__module__.rsplit('.', 1)[0] in \
                             settings.INSTALLED_APPS
            self.permissions = []

            meta = model.__dict__.get('Meta')
            if meta:
                meta_attrs = meta.__dict__.copy()
                for name in meta.__dict__:
                    # Ignore any private attributes that Django doesn't care about.
                    # NOTE: We can't modify a dictionary's contents while looping
                    # over it, so we loop over the *original* dictionary instead.
                    if name.startswith('_'):
                        del meta_attrs[name]
                for attr_name in DEFAULT_NAMES:
                    if attr_name in meta_attrs:
                        setattr(self, attr_name, meta_attrs.pop(attr_name))
                    elif hasattr(meta, attr_name):
                        setattr(self, attr_name, getattr(meta, attr_name))

                # verbose_name_plural is a special case because it uses a 's'
                # by default.
                setattr(self, 'verbose_name_plural', meta_attrs.pop('verbose_name_plural', string_concat(self.verbose_name, 's')))

                # Any leftover attributes must be invalid.
                if meta_attrs != {}:
                    raise TypeError, "'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())
            else:
                self.verbose_name_plural = self.verbose_name + 's'

            if not self.abstract:
                self.permissions.extend([
                    ('add_%s' % self.object_name.lower(),
                        string_concat('Can add ', self.verbose_name)),
                    ('change_%s' % self.object_name.lower(),
                        string_concat('Can change ', self.verbose_name)),
                    ('delete_%s' % self.object_name.lower(),
                        string_concat('Can delete ', self.verbose_name)),
                ])

        def __repr__(self):
            return '<Options for %s>' % self.object_name

        def __str__(self):
            return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name))

        def _set_db_table(self, db_table):
            self._db_table = db_table
        
        def _get_db_table(self):
            if getattr(settings, 'DJANGO_STYLE_MODEL_KIND', True):
                if hasattr(self, '_db_table'):
                    return self._db_table
                return '%s_%s' % (self.app_label, self.module_name)
            return self.object_name

        db_table = property(_get_db_table, _set_db_table)

        def _set_db_tablespace(self, db_tablespace):
            self._db_tablespace = db_tablespace
        
        def _get_db_tablespace(self):
            if hasattr(self, '_db_tablespace'):
                return self._db_tablespace
            return settings.DEFAULT_TABLESPACE

        db_tablespace = property(_get_db_tablespace, _set_db_tablespace)

        @property
        def verbose_name_raw(self):
            """
            There are a few places where the untranslated verbose name is needed
            (so that we get the same value regardless of currently active
            locale).
            """
            lang = get_language()
            deactivate_all()
            raw = force_unicode(self.verbose_name)
            activate(lang)
            return raw

        @property
        def local_fields(self):
            return tuple(sorted([p for p in self.model.properties().values()
                                 if not isinstance(p, db.ListProperty)],
                                key=lambda prop: prop.creation_counter))

        @property
        def local_many_to_many(self):
            return tuple(sorted([p for p in self.model.properties().values()
                                 if isinstance(p, db.ListProperty) and
                                     not p.name == '_class'],
                                key=lambda prop: prop.creation_counter))

        @property
        def fields(self):
            return self.local_fields + self.local_many_to_many

        def get_field(self, name, many_to_many=True):
            """
            Returns the requested field by name. Raises FieldDoesNotExist on error.
            """
            for f in self.fields:
                if f.name == name:
                    return f
            from django.db.models.fields import FieldDoesNotExist
            raise FieldDoesNotExist, '%s has no field named %r' % (self.object_name, name)

        def get_all_related_objects(self, local_only=False):
            try:
                self._related_objects_cache
            except AttributeError:
                self._fill_related_objects_cache()
            if local_only:
                return [k for k, v in self._related_objects_cache.items() if not v]
            return self._related_objects_cache.keys()

        def get_all_related_objects_with_model(self):
            """
            Returns a list of (related-object, model) pairs. Similar to
            get_fields_with_model().
            """
            try:
                self._related_objects_cache
            except AttributeError:
                self._fill_related_objects_cache()
            return self._related_objects_cache.items()

        def _fill_related_objects_cache(self):
            from django.db.models.loading import get_models
            from django.db.models.related import RelatedObject
            cache = SortedDict()
            parent_list = self.get_parent_list()
            for parent in self.parents:
                for obj, model in parent._meta.get_all_related_objects_with_model():
                    if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list:
                        continue
                    if not model:
                        cache[obj] = parent
                    else:
                        cache[obj] = model
            for klass in get_models():
                for f in klass._meta.local_fields:
                    if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta:
                        cache[RelatedObject(f.rel.to, klass, f)] = None
            self._related_objects_cache = cache

        def get_all_related_many_to_many_objects(self, local_only=False):
            try:
                cache = self._related_many_to_many_cache
            except AttributeError:
                cache = self._fill_related_many_to_many_cache()
            if local_only:
                return [k for k, v in cache.items() if not v]
            return cache.keys()

        def get_all_related_m2m_objects_with_model(self):
            """
            Returns a list of (related-m2m-object, model) pairs. Similar to
            get_fields_with_model().
            """
            try:
                cache = self._related_many_to_many_cache
            except AttributeError:
                cache = self._fill_related_many_to_many_cache()
            return cache.items()

        def _fill_related_many_to_many_cache(self):
            from django.db.models.loading import get_models, app_cache_ready
            from django.db.models.related import RelatedObject
            cache = SortedDict()
            parent_list = self.get_parent_list()
            for parent in self.parents:
                for obj, model in parent._meta.get_all_related_m2m_objects_with_model():
                    if obj.field.creation_counter < 0 and obj.model not in parent_list:
                        continue
                    if not model:
                        cache[obj] = parent
                    else:
                        cache[obj] = model
            for klass in get_models():
                for f in klass._meta.local_many_to_many:
                    if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta:
                        cache[RelatedObject(f.rel.to, klass, f)] = None
            if app_cache_ready():
                self._related_many_to_many_cache = cache
            return cache

        def get_add_permission(self):
            return 'add_%s' % self.object_name.lower()

        def get_change_permission(self):
            return 'change_%s' % self.object_name.lower()

        def get_delete_permission(self):
            return 'delete_%s' % self.object_name.lower()

        def get_ordered_objects(self):
            return []

        def get_parent_list(self):
            """
            Returns a list of all the ancestor of this model as a list. Useful for
            determining if something is an ancestor, regardless of lineage.
            """
            result = set()
            for parent in self.parents:
                result.add(parent)
                result.update(parent._meta.get_parent_list())
            return result

    # Required to support reference properties to db.Model
    db.Model._meta = _meta(db.Model, ())
    
    def _initialize_model(cls, bases):
        cls._meta = _meta(cls, bases)
        cls._default_manager = cls
        if not cls._meta.abstract:
            from django.db.models.loading import register_models
            register_models(cls._meta.app_label, cls)

    # Register models with Django
    from django.db.models import signals
    old_propertied_class_init = db.PropertiedClass.__init__
    def __init__(cls, name, bases, attrs, map_kind=True):
        """Creates a combined appengine and Django model.

        The resulting model will be known to both the appengine libraries and
        Django.
        """
        _initialize_model(cls, bases)
        old_propertied_class_init(cls, name, bases, attrs,
            not cls._meta.abstract)
        signals.class_prepared.send(sender=cls)
    db.PropertiedClass.__init__ = __init__

    old_poly_init = polymodel.PolymorphicClass.__init__
    def __init__(cls, name, bases, attrs):
        if polymodel.PolyModel not in bases:
            _initialize_model(cls, bases)
        old_poly_init(cls, name, bases, attrs)
        if polymodel.PolyModel not in bases:
            signals.class_prepared.send(sender=cls)
    polymodel.PolymorphicClass.__init__ = __init__

    @classmethod
    def kind(cls):
        return cls._meta.db_table
    db.Model.kind = kind

    # Add model signals
    old_model_init = db.Model.__init__
    def __init__(self, *args, **kwargs):
        signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
        old_model_init(self, *args, **kwargs)
        signals.post_init.send(sender=self.__class__, instance=self)
    db.Model.__init__ = __init__

    old_put = db.Model.put
    def put(self, *args, **kwargs):
        raw = False
        signals.pre_save.send(sender=self.__class__, instance=self, raw=raw)
        created = not self.is_saved()
        result = old_put(self, *args, **kwargs)
        signals.post_save.send(sender=self.__class__, instance=self,
            created=created, raw=raw)
        return result
    db.Model.put = put

    old_delete = db.Model.delete
    def delete(self, *args, **kwargs):
        signals.pre_delete.send(sender=self.__class__, instance=self)
        result = old_delete(self, *args, **kwargs)
        signals.post_delete.send(sender=self.__class__, instance=self)
        return result
    db.Model.delete = delete

    # This has to come last because we load Django here
    from django.db.models.fields import BLANK_CHOICE_DASH
    def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
        first_choice = include_blank and blank_choice or []
        if self.choices:
            return first_choice + list(self.choices)
        if self.rel:
            return first_choice + [(obj.pk, unicode(obj))
                                   for obj in self.rel.to.all().fetch(301)]
        return first_choice
    db.Property.get_choices = get_choices

    fix_app_engine_bugs()

Example 79

Project: cgstudiomap Source File: models.py
Function: register_handlers
def register_handlers():
    from django.core.signals import got_request_exception

    # HACK: support Sentry's internal communication
    if 'sentry' in settings.INSTALLED_APPS:
        from django.db import transaction
        # Django 1.6
        if hasattr(transaction, 'atomic'):
            commit_on_success = transaction.atomic
        else:
            commit_on_success = transaction.commit_on_success

        @commit_on_success
        def wrap_sentry(request, **kwargs):
            if transaction.is_dirty():
                transaction.rollback()
            return sentry_exception_handler(request, **kwargs)

        exception_handler = wrap_sentry
    else:
        exception_handler = sentry_exception_handler

    # Connect to Django's internal signal handler
    got_request_exception.connect(exception_handler, weak=False)

    # If Celery is installed, register a signal handler
    if 'djcelery' in settings.INSTALLED_APPS:
        try:
            # Celery < 2.5? is not supported
            from raven.contrib.celery import (
                register_signal, register_logger_signal)
        except ImportError:
            logger.exception('Failed to install Celery error handler')
        else:
            try:
                register_signal(client)
            except Exception:
                logger.exception('Failed to install Celery error handler')

            try:
                ga = lambda x, d=None: getattr(settings, 'SENTRY_%s' % x, d)
                options = getattr(settings, 'RAVEN_CONFIG', {})
                loglevel = options.get('celery_loglevel',
                                       ga('CELERY_LOGLEVEL', logging.ERROR))

                register_logger_signal(client, loglevel=loglevel)
            except Exception:
                logger.exception('Failed to install Celery error handler')

Example 80

Project: shuup Source File: test_basket.py
@pytest.mark.django_db
def test_basket_package_product_orderability_change(rf):
    if "shuup.simple_supplier" not in settings.INSTALLED_APPS:
        pytest.skip("Need shuup.simple_supplier in INSTALLED_APPS")
    from shuup_tests.simple_supplier.utils import get_simple_supplier

    StoredBasket.objects.all().delete()
    shop = get_default_shop()
    supplier = get_simple_supplier()
    product, child = get_unstocked_package_product_and_stocked_child(shop, supplier, child_logical_quantity=2)
    request = rf.get("/")
    request.session = {}
    request.shop = shop
    apply_request_middleware(request)
    basket = get_basket(request)

    # Add the package parent
    basket.add_product(
        supplier=supplier,
        shop=shop,
        product=product,
        quantity=1,
        force_new_line=True,
        extra={"foo": "foo"}
    )

    # Also add the child product separately
    basket.add_product(
        supplier=supplier,
        shop=shop,
        product=child,
        quantity=1,
        force_new_line=True,
        extra={"foo": "foo"}
    )

    # Should be stock for both
    assert len(basket.get_lines()) == 2
    assert len(basket.get_unorderable_lines()) == 0

    supplier.adjust_stock(child.id, -1)
    assert basket.dirty

    # After reducing stock to 1, should only be stock for one
    assert len(basket.get_lines()) == 1
    assert len(basket.get_unorderable_lines()) == 1

    supplier.adjust_stock(child.id, -1)
    assert basket.dirty

    # After reducing stock to 0, should be stock for neither
    assert len(basket.get_lines()) == 0
    assert len(basket.get_unorderable_lines()) == 2

Example 81

Project: django-nonrel Source File: syncdb.py
    def handle_noargs(self, **options):

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

        # Stealth option -- 'load_initial_data' is used by the testing setup
        # process to disable initial fixture loading.
        load_initial_data = options.get('load_initial_data', True)

        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, 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', DEFAULT_DB_ALIAS)
        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, filter(model_installed, model_list))
            for app_name, model_list in all_models
        )

        # Create the tables for each model
        if verbosity >= 1:
            print "Creating tables ..."
        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:
                    print "Processing %s.%s model" % (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:
                    print "Creating table %s" % 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:
            print "Installing custom SQL ..."
        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:
                            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\n" % \
                                                (app_name, model._meta.object_name, e))
                            if show_traceback:
                                import traceback
                                traceback.print_exc()
                            transaction.rollback_unless_managed(using=db)
                        else:
                            transaction.commit_unless_managed(using=db)
                    else:
                        if verbosity >= 3:
                            print "No custom SQL for %s.%s model" % (app_name, model._meta.object_name)

        if verbosity >= 1:
            print "Installing indexes ..."
        # Install SQL indicies 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:
                            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\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:
            from django.core.management import call_command
            call_command('loaddata', 'initial_data', verbosity=verbosity, database=db)

Example 82

Project: tendenci Source File: list_tables.py
Function: handle
    def handle(self, *args, **options):
        apps = []
        models_d = {}
        tables_list = []
        for app in settings.INSTALLED_APPS:
            try:
                app_label = app.split('.')[-1]
                apps.append(app_label)
            except:
                # No models, no problem.
                pass

        for app_label in apps:
            # skip the legacy
            if app_label in ['legacy']:
                continue
            # skip the social_auth if not set
            if not getattr(settings, 'SOCIAL_AUTH_USER_MODEL', None):
                if app_label in  ['social_auth']:
                    continue
            try:
                app = get_app(app_label)
            except:
                app = None
            if app:
                for model in get_models(app, include_auto_created=True):
                    models_d[model._meta.db_table] = model
                    tables_list.append(model._meta.db_table)

        tables_list.remove('mig_help_files_helpfile_t4_to_t5')
        # django 1.4 doesn't have auth_message table
        if 'auth_message' in tables_list:
            tables_list.remove('auth_message')

        related_tables = {}
        # get a list of related tables for each table
        for table in tables_list:
            related_tables[table] = [field.rel.to._meta.db_table \
                        for field in models_d[table]._meta.fields \
                        if isinstance(field, (ForeignKey, OneToOneField))
                        and field.rel.to._meta.db_table != table
                        ]

        sorted_list = []
        for table in tables_list:
            if not related_tables[table]:
                sorted_list.append(table)

        n = 100
        # avoid getting into the infinite loop - just in case
        #while related_tables:
        while n > 1:
            # remove tables from related_tables if already in the sorted_list
            for key in related_tables.keys():
                for rel_table in related_tables[key]:
                    if rel_table in sorted_list:
                        related_tables[key].remove(rel_table)
                if not related_tables[key]:
                    del related_tables[key]

            # add to the sorted_list if there is no
            # related_tables  for this table
            for table in tables_list:
                # if the related_tables is gone
                if table not in sorted_list and (
                       table not in related_tables.keys()):
                    sorted_list.append(table)

            # continue until all the related tables are gone
            if not related_tables:
                break

            n = n - 1

        if related_tables:
            print "ERROR: Sorting not completed."

        # copy the list to your conf.yml file
        print '-', '\n- '.join(sorted_list)

Example 83

Project: django-nonrel Source File: i18n.py
Function: javascript_catalog
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, basestring):
        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(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, basestring):
            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')

Example 84

Project: Django--an-app-at-a-time Source File: __init__.py
Function: execute
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)

Example 85

Project: hue Source File: syncdb.py
    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_models = set([x for x in itertools.chain(*manifest.values())])
        emit_pre_sync_signal(create_models, verbosity, interactive, db)

        # Create the tables for each model
        if verbosity >= 1:
            self.stdout.write("Creating tables ...\n")
        with transaction.commit_on_success_unless_managed(using=db):
            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))

        # 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:
                            with transaction.commit_on_success_unless_managed(using=db):
                                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()
                    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:
                            with transaction.commit_on_success_unless_managed(using=db):
                                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))

        # 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 86

Project: tendenci Source File: load_npo_defaults.py
    def call_loaddata(self, reset_nav=False):
        """
        This calls the loaddata command on all
        non profit fixtures.
        The order - It's a big deal.
        """
        from tendenci.apps.files.models import File

        if reset_nav:
            from tendenci.apps.navs.models import NavItem
            try:
                main_nav_items = NavItem.objects.filter(nav_id=1)
                main_nav_items.delete()
            except:
                pass

        staff_installed = "addons.staff" in settings.INSTALLED_APPS
        print 'npo_default_auth_user.json'
        call_command('loaddata', 'npo_default_auth_user.json')
        print 'npo_default_entities.json'
        call_command('loaddata', 'npo_default_entities.json')
        print 'npo_default_user_groups.json'
        call_command('loaddata', 'npo_default_user_groups.json')
        print 'npo_default_files.json'
        call_command('loaddata', 'npo_default_files.json')
        print 'load paymentmethod.json'
        call_command('loaddata', 'paymentmethod.json')
        print 'load default_forums.json'
        call_command('loaddata', 'default_forums.json')
        print 'load regions_region.json'
        call_command('loaddata', 'regions_region.json')
        print 'load npo_default_directories_pricings.json'
        call_command('loaddata', 'npo_default_directories_pricings.json')
        
        
        # default sqls for explorer
        call_command('load_sqlexplorer_defaults')
        

        box_ct = ContentType.objects.get(app_label='boxes', model='box')
        story_ct = ContentType.objects.get(app_label='stories', model='story')
        setting_ct = ContentType.objects.get(app_label='site_settings', model='setting')
        if staff_installed:
            staff_ct = ContentType.objects.get(app_label='staff', model='staff')

        files = File.objects.all()

        print 'updating files'
        for f in files:

            if 'box' in unicode(f.file):
                f.content_type = box_ct
            if 'story' in unicode(f.file):
                f.content_type = story_ct
            if 'setting' in unicode(f.file):
                f.content_type = setting_ct
            if 'staff' in unicode(f.file) and staff_installed:
                f.content_type = staff_ct

            f.save()

        suffix_list = [
            'profiles_profile',
            'events',
            'jobs',
            'memberships',
            'memberships_membershipdefault',
            'directories',
            'articles',
            'forms',
            'news',
            'photos',
            'boxes',
            'pages',
            'navs',
            'stories',
            'videos',
        ]

        # call loaddata on fixtures
        for suffix in suffix_list:
            filename = 'npo_default_%s.json' % suffix

            print filename
            call_command('loaddata', filename)

Example 87

Project: decode-Django Source File: __init__.py
Function: auto_complete
    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 特殊处理, 这些命令需要返回已经安装的 app
            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

            # option_list
            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 88

Project: django-primate Source File: admin.py
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    import copy
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        if app == 'django.contrib.auth':
            admin.site.register(Group, GroupAdmin)
            continue
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(site._registry)
            import_module('%s.admin' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site._registry = before_import_registry

            # 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, 'admin'):
                raise

Example 89

Project: django-compositepks Source File: syncdb.py
    def handle_noargs(self, **options):
        from django.db import connection, transaction, models
        from django.conf import settings
        from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal

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

        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:
                # 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

        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 = {}

        # 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 connection.introspection.table_name_converter(model._meta.db_table) in tables:
                    continue
                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:
                    print "Creating table %s" % model._meta.db_table
                for statement in sql:
                    cursor.execute(statement)
                tables.append(connection.introspection.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 = connection.creation.sql_for_many_to_many(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)

        # 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)
        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, self.style)
                    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\n" % \
                                                (app_name, model._meta.object_name, e))
                            if show_traceback:
                                import traceback
                                traceback.print_exc()
                            transaction.rollback_unless_managed()
                        else:
                            transaction.commit_unless_managed()
                    else:
                        if verbosity >= 2:
                            print "No custom SQL for %s.%s model" % (app_name, model._meta.object_name)
        # 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 = connection.creation.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\n" % \
                                                (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 90

Project: django-rest-auth Source File: serializers.py
    def validate(self, attrs):
        username = attrs.get('username')
        email = attrs.get('email')
        password = attrs.get('password')

        user = None

        if 'allauth' in settings.INSTALLED_APPS:
            from allauth.account import app_settings

            # Authentication through email
            if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL:
                user = self._validate_email(email, password)

            # Authentication through username
            if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME:
                user = self._validate_username(username, password)

            # Authentication through either username or email
            else:
                user = self._validate_username_email(username, email, password)

        else:
            # Authentication without using allauth
            if email:
                try:
                    username = UserModel.objects.get(email__iexact=email).get_username()
                except UserModel.DoesNotExist:
                    pass

            if username:
                user = self._validate_username_email(username, '', password)

        # Did we get back an active user?
        if user:
            if not user.is_active:
                msg = _('User account is disabled.')
                raise exceptions.ValidationError(msg)
        else:
            msg = _('Unable to log in with provided credentials.')
            raise exceptions.ValidationError(msg)

        # If required, is the email verified?
        if 'rest_auth.registration' in settings.INSTALLED_APPS:
            from allauth.account import app_settings
            if app_settings.EMAIL_VERIFICATION == app_settings.EmailVerificationMethod.MANDATORY:
                email_address = user.emailaddress_set.get(email=user.email)
                if not email_address.verified:
                    raise serializers.ValidationError(_('E-mail is not verified.'))

        attrs['user'] = user
        return attrs

Example 91

Project: django-compositepks Source File: runtests.py
Function: django_tests
def django_tests(verbosity, interactive, test_labels):
    from django.conf import settings

    old_installed_apps = settings.INSTALLED_APPS
    old_test_database_name = settings.TEST_DATABASE_NAME
    old_root_urlconf = getattr(settings, "ROOT_URLCONF", "")
    old_template_dirs = settings.TEMPLATE_DIRS
    old_use_i18n = settings.USE_I18N
    old_login_url = settings.LOGIN_URL
    old_language_code = settings.LANGUAGE_CODE
    old_middleware_classes = settings.MIDDLEWARE_CLASSES

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),)
    settings.USE_I18N = True
    settings.LANGUAGE_CODE = 'en'
    settings.LOGIN_URL = '/accounts/login/'
    settings.MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.middleware.common.CommonMiddleware',
    )
    settings.SITE_ID = 1

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app
    get_apps()

    # Load all the test model apps.
    for model_dir, model_name in get_test_models():
        model_label = '.'.join([model_dir, model_name])
        try:
            # if the model was named on the command line, or
            # no models were named (i.e., run all), import
            # this model and add it to the list to test.
            if not test_labels or model_name in set([label.split('.')[0] for label in test_labels]):
                if verbosity >= 1:
                    print "Importing model %s" % model_name
                mod = load_app(model_label)
                if mod:
                    if model_label not in settings.INSTALLED_APPS:
                        settings.INSTALLED_APPS.append(model_label)
        except Exception, e:
            sys.stderr.write("Error while importing %s:" % model_name + ''.join(traceback.format_exception(*sys.exc_info())[1:]))
            continue

    # Add tests for invalid models.
    extra_tests = []
    for model_dir, model_name in get_invalid_models():
        model_label = '.'.join([model_dir, model_name])
        if not test_labels or model_name in test_labels:
            extra_tests.append(InvalidModelTestCase(model_label))
            try:
                # Invalid models are not working apps, so we cannot pass them into
                # the test runner with the other test_labels
                test_labels.remove(model_name)
            except ValueError:
                pass

    # Run the test suite, including the extra validation tests.
    from django.test.simple import run_tests
    failures = run_tests(test_labels, verbosity=verbosity, interactive=interactive, extra_tests=extra_tests)
    if failures:
        sys.exit(failures)

    # Restore the old settings.
    settings.INSTALLED_APPS = old_installed_apps
    settings.ROOT_URLCONF = old_root_urlconf
    settings.TEMPLATE_DIRS = old_template_dirs
    settings.USE_I18N = old_use_i18n
    settings.LANGUAGE_CODE = old_language_code
    settings.LOGIN_URL = old_login_url
    settings.MIDDLEWARE_CLASSES = old_middleware_classes

Example 92

Project: pytest-django Source File: live_server_helper.py
    def __init__(self, addr):
        import django
        from django.db import connections
        from django.test.testcases import LiveServerThread
        from django.test.utils import modify_settings

        connections_override = {}
        for conn in connections.all():
            # If using in-memory sqlite databases, pass the connections to
            # the server thread.
            if (conn.settings_dict['ENGINE'] == 'django.db.backends.sqlite3' and
                    conn.settings_dict['NAME'] == ':memory:'):
                # Explicitly enable thread-shareability for this connection
                conn.allow_thread_sharing = True
                connections_override[conn.alias] = conn

        liveserver_kwargs = {'connections_override': connections_override}
        from django.conf import settings
        if 'django.contrib.staticfiles' in settings.INSTALLED_APPS:
            from django.contrib.staticfiles.handlers import StaticFilesHandler
            liveserver_kwargs['static_handler'] = StaticFilesHandler
        else:
            from django.test.testcases import _StaticFilesHandler
            liveserver_kwargs['static_handler'] = _StaticFilesHandler

        if django.VERSION < (1, 11):
            host, possible_ports = parse_addr(addr)
            self.thread = LiveServerThread(host, possible_ports,
                                           **liveserver_kwargs)
        else:
            host = addr
            self.thread = LiveServerThread(host, **liveserver_kwargs)

        self._live_server_modified_settings = modify_settings(
            ALLOWED_HOSTS={'append': host},
        )
        self._live_server_modified_settings.enable()

        self.thread.daemon = True
        self.thread.start()
        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error

Example 93

Project: django Source File: __init__.py
Function: execute
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)

Example 94

Project: couchdbkit Source File: schema.py
    def contribute_to_class(self, cls, name):
        cls._meta = self
        self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
        # First, construct the default values for these options.
        self.object_name = cls.__name__
        self.module_name = self.object_name.lower()
        self.verbose_name = get_verbose_name(self.object_name)

        # Next, apply any overridden values from 'class Meta'.
        if self.meta:
            meta_attrs = self.meta.__dict__.copy()
            for name in self.meta.__dict__:
                # Ignore any private attributes that Django doesn't care about.
                # NOTE: We can't modify a dictionary's contents while looping
                # over it, so we loop over the *original* dictionary instead.
                if name.startswith('_'):
                    del meta_attrs[name]
            for attr_name in DEFAULT_NAMES:
                if attr_name in meta_attrs:
                    setattr(self, attr_name, meta_attrs.pop(attr_name))
                elif hasattr(self.meta, attr_name):
                    setattr(self, attr_name, getattr(self.meta, attr_name))

            # verbose_name_plural is a special case because it uses a 's'
            # by default.
            setattr(self, 'verbose_name_plural', meta_attrs.pop('verbose_name_plural', string_concat(self.verbose_name, 's')))

            # Any leftover attributes must be invalid.
            if meta_attrs != {}:
                raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()))
        else:
            self.verbose_name_plural = string_concat(self.verbose_name, 's')
        del self.meta

Example 95

Project: xadmin Source File: runtests.py
Function: set_up
def setup(verbosity, test_labels):
    from django.conf import settings
    state = {
        'INSTALLED_APPS': settings.INSTALLED_APPS,
        'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
        'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
        'USE_I18N': settings.USE_I18N,
        'LOGIN_URL': settings.LOGIN_URL,
        'LANGUAGE_CODE': settings.LANGUAGE_CODE,
        'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
        'STATIC_URL': settings.STATIC_URL,
        'STATIC_ROOT': settings.STATIC_ROOT,
    }

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.STATIC_URL = '/static/'
    settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
    settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
    settings.USE_I18N = True
    settings.LANGUAGE_CODE = 'en'
    settings.MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.common.CommonMiddleware',
    )
    settings.SITE_ID = 1
    # For testing comment-utils, we require the MANAGERS attribute
    # to be set, so that a test email is sent out which we catch
    # in our tests.
    settings.MANAGERS = ("[email protected]",)

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)


    # Load all the test model apps.
    test_labels_set = set([label.split('.')[0] for label in test_labels])
    test_modules = get_test_modules()

    for module_name in test_modules:
        module_label = module_name
        # if the module was named on the command line, or
        # no modules were named (i.e., run all), import
        # this module and add it to the list to test.
        if not test_labels or module_name in test_labels_set:
            if verbosity >= 2:
                print("Importing application %s" % module_name)
            if module_label not in settings.INSTALLED_APPS:
                settings.INSTALLED_APPS.append(module_label)

    django.setup()
    [a.models_module for a in apps.get_app_configs()]
    return state

Example 96

Project: pycon Source File: views.py
@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, "proposals/proposal_detail.html", {
        "proposal": proposal,
        "message_form": message_form
    })

Example 97

Project: django-discoverage Source File: utils.py
def find_coverage_apps(suite):
    coverage_apps = set()
    inspected = set()
    app_pkgs = dict((app.split('.')[-1], app)
                    for app in settings.INSTALLED_APPS)

    for test in suite:
        class_name = repr(test.__class__)

        if class_name in inspected:
            continue

        test_apps = get_apps(test)

        if test.__module__ not in inspected:
            test_module = import_module(test.__module__)
            test_apps.extend(get_apps(test_module))
            inspected.add(test.__module__)
            pkg, module_name = test.__module__.rsplit('.', 1)

            if MODULE_NAME_APP_DISCOVERY:
                try:
                    guessed_app_name = re.match(MODULE_NAME_DISCOVERY_PATTERN,
                                                module_name).group(1)
                    test_apps.append(app_pkgs[guessed_app_name])
                except (KeyError, AttributeError, IndexError):
                    pass

            if pkg not in inspected:
                test_pkg = import_module(pkg)
                test_apps.extend(get_apps(test_pkg))
                inspected.add(pkg)

                if PKG_NAME_APP_DISCOVERY:
                    subpkg = pkg.rsplit('.', 1)[-1]
                    try:
                        test_apps.append(app_pkgs[subpkg])
                    except KeyError:
                        pass

        inspected.add(class_name)
        coverage_apps.update(test_apps)

    return list(coverage_apps)

Example 98

Project: shuup Source File: test_order_creator.py
@pytest.mark.django_db
def test_order_creator_with_package_product(rf, admin_user):
    if "shuup.simple_supplier" not in settings.INSTALLED_APPS:
        pytest.skip("Need shuup.simple_supplier in INSTALLED_APPS")
    from shuup_tests.simple_supplier.utils import get_simple_supplier

    shop = get_default_shop()
    supplier = get_simple_supplier()
    package_product = create_package_product("Package-Product-Test", shop=shop, supplier=supplier,
                                             children=2)
    shop_product =  package_product.get_shop_instance(shop)
    quantity_map = package_product.get_package_child_to_quantity_map()
    product_1, product_2 = quantity_map.keys()
    product_1.stock_behavior = StockBehavior.STOCKED
    product_1.save()
    product_2.stock_behavior = StockBehavior.STOCKED
    product_2.save()

    assert quantity_map[product_1] == 1
    assert quantity_map[product_2] == 2

    supplier.adjust_stock(product_1.pk, 1)
    supplier.adjust_stock(product_2.pk, 2)

    assert supplier.get_stock_status(product_1.pk).logical_count == 1
    assert supplier.get_stock_status(product_2.pk).logical_count == 2

    creator = OrderCreator()

    # There should be no exception when creating order with only package product
    source = seed_source(admin_user)
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=package_product,
        supplier=supplier,
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    order = creator.create_order(source)

    # However, there should not be enough stock for both package and child products
    source = seed_source(admin_user)
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=package_product,
        supplier=supplier,
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=product_1,
        supplier=supplier,
        quantity=1,
        base_unit_price=source.create_price(10),
    )

    # And a validation error should be raised
    with pytest.raises(ValidationError):
        order = creator.create_order(source)

Example 99

Project: mezzanine Source File: tests.py
    @skipUnless("mezzanine.pages" in settings.INSTALLED_APPS,
                "pages app required")
    def test_multisite(self):
        from django.conf import settings

        # setup
        try:
            old_site_id = settings.SITE_ID
        except:
            old_site_id = None

        site1 = Site.objects.create(domain="site1.com")
        site2 = Site.objects.create(domain="site2.com")

        # create pages under site1, which should be only accessible
        # when SITE_ID is site1
        settings.SITE_ID = site1.pk
        site1_page = self._create_page("Site1", CONTENT_STATUS_PUBLISHED)
        self._test_site_pages("Site1", CONTENT_STATUS_PUBLISHED, count=1)

        # create pages under site2, which should only be accessible
        # when SITE_ID is site2
        settings.SITE_ID = site2.pk
        self._create_page("Site2", CONTENT_STATUS_PUBLISHED)
        self._test_site_pages("Site2", CONTENT_STATUS_PUBLISHED, count=1)

        # original page should 404
        response = self.client.get(site1_page.get_absolute_url(), follow=True)
        self.assertEqual(response.status_code, 404)

        # change back to site1, and only the site1 pages should be retrieved
        settings.SITE_ID = site1.pk
        self._test_site_pages("Site1", CONTENT_STATUS_PUBLISHED, count=1)

        # insert a new record, see the count change
        self._create_page("Site1 Draft", CONTENT_STATUS_DRAFT)
        self._test_site_pages("Site1 Draft", CONTENT_STATUS_DRAFT, count=2)
        self._test_site_pages("Site1 Draft", CONTENT_STATUS_PUBLISHED, count=2)

        # change back to site2, and only the site2 pages should be retrieved
        settings.SITE_ID = site2.pk
        self._test_site_pages("Site2", CONTENT_STATUS_PUBLISHED, count=1)

        # insert a new record, see the count change
        self._create_page("Site2 Draft", CONTENT_STATUS_DRAFT)
        self._test_site_pages("Site2 Draft", CONTENT_STATUS_DRAFT, count=2)
        self._test_site_pages("Site2 Draft", CONTENT_STATUS_PUBLISHED, count=2)

        # tear down
        if old_site_id:
            settings.SITE_ID = old_site_id
        else:
            del settings.SITE_ID

        site1.delete()
        site2.delete()

Example 100

Project: django-modeltranslation Source File: models.py
Function: auto_discover
def autodiscover():
    """
    Auto-discover INSTALLED_APPS translation.py modules and fail silently when
    not present. This forces an import on them to register.
    Also import explicit modules.
    """
    import os
    import sys
    import copy
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule
    from modeltranslation.translator import translator
    from modeltranslation.settings import TRANSLATION_FILES, DEBUG

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's translation module.
        module = '%s.translation' % app
        before_import_registry = copy.copy(translator._registry)
        try:
            import_module(module)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            translator._registry = before_import_registry

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

    for module in TRANSLATION_FILES:
        import_module(module)

    # In debug mode, print a list of registered models and pid to stdout.
    # Note: Differing model order is fine, we don't rely on a particular
    # order, as far as base classes are registered before subclasses.
    if DEBUG:
        try:
            if sys.argv[1] in ('runserver', 'runserver_plus'):
                models = translator.get_registered_models()
                names = ', '.join(m.__name__ for m in models)
                print('modeltranslation: Registered %d models for translation'
                      ' (%s) [pid: %d].' % (len(models), names, os.getpid()))
        except IndexError:
            pass
See More Examples - Go to Next Page
Page 1 Page 2 Selected Page 3 Page 4