django.apps.apps.get_model

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

200 Examples 7

Example 1

Project: pinax-documents
Source File: managers.py
View license
    def members(self, folder, **kwargs):
        direct = kwargs.get("direct", True)
        user = kwargs.get("user")
        Document = apps.get_model("documents", "Document")
        folders = self.filter(parent=folder)
        documents = Document.objects.filter(folder=folder)
        if user:
            folders = folders.for_user(user)
            documents = documents.for_user(user)
        M = sorted(itertools.chain(folders, documents), key=operator.attrgetter("name"))
        if direct:
            return M
        for child in folders:
            M.extend(self.members(child, **kwargs))
        return M

Example 2

Project: djangae
Source File: readers.py
View license
    def __init__(self, start_id, end_id, model, *args, **kwargs):
        self.shard_id = 1
        self.start_id = start_id
        self.end_id = end_id
        self.raw_model = model
        self.db = kwargs.pop('db', 'default')
        app, model = self.raw_model.split('.')
        self.model = apps.get_model(app, model)
        super(DjangoInputReader, self).__init__(*args, **kwargs)

Example 3

Project: pycontw2016
Source File: import_events.py
View license
    def handle(self, *args, filename, truncate=False, **options):
        if truncate:
            for Cls in EVENT_CLASSES:
                Cls.objects.all().delete()
        with open(filename) as f:
            data = json.load(f)
        for model_name, datasets in data.items():
            model = apps.get_model(*model_name.split('.'))
            for dataset in datasets:
                dataset['location'] = _pop_location(dataset)
                dataset.update(_pop_time_kwargs(dataset))
                model.objects.create(**dataset)

Example 4

Project: pycontw2016
Source File: loadproposals.py
View license
    def handle(self, *args, filename, **options):
        with open(filename) as f:
            data = json.load(f)
        for dataset in data:
            model = apps.get_model(*dataset['model'].split('.'))
            fields = dataset.pop('fields', {})
            submitter = fields.pop('submitter', None)
            if submitter is not None:
                try:
                    submitter = User.objects.get(pk=submitter)
                except User.DoesNotExist:
                    submitter = User.objects.first()
            fields['submitter'] = submitter
            model.objects.update_or_create(fields, pk=dataset['pk'])

Example 5

Project: dj-spam
Source File: utils.py
View license
def get_spammable_or_404(app, model, pk):
    # Does this view have the is_spammable mixin?
    if is_spammable(app, model):
        # convert app/model into the actual model class
        model_class = apps.get_model(app, model)
        # So we can call meta for details in the template
        model_class.meta = model_class._meta
        instance = get_object_or_404(model_class, pk=pk)
        return model_class, instance
    raise Http404

Example 6

Project: Misago
Source File: test_migrationutils.py
View license
    def test_get_custom_group_and_settings(self):
        """tests setup created settings group"""
        custom_group = migrationutils.get_group(
            apps.get_model('misago_conf', 'SettingsGroup'),
            self.test_group['key'])

        self.assertEqual(custom_group.key, self.test_group['key'])
        self.assertEqual(custom_group.name, self.test_group['name'])
        self.assertEqual(custom_group.description,
                         self.test_group['description'])

        custom_settings = migrationutils.get_custom_settings_values(
            custom_group)

        self.assertEqual(custom_settings['fish_name'], 'Eric')
        self.assertTrue('fish_license_no' not in custom_settings)

Example 7

Project: django-shop
Source File: plugin_base.py
View license
    @classmethod
    def get_link(cls, obj):
        link = obj.glossary.get('link', {})
        if link.get('type') == 'cmspage':
            if 'model' in link and 'pk' in link:
                if not hasattr(obj, '_link_model'):
                    Model = apps.get_model(*link['model'].split('.'))
                    try:
                        obj._link_model = Model.objects.get(pk=link['pk'])
                    except Model.DoesNotExist:
                        obj._link_model = None
                if obj._link_model:
                    return obj._link_model.get_absolute_url()
        else:
            # use the link type as special action keyword
            return link.get('type')

Example 8

Project: django-shop
Source File: plugin_base.py
View license
    def set_initial_product(self, initial):
        try:
            # check if that product still exists, otherwise return nothing
            Model = apps.get_model(*initial['link']['model'].split('.'))
            initial['product'] = Model.objects.get(pk=initial['link']['pk']).pk
        except (KeyError, ValueError, ObjectDoesNotExist):
            pass

Example 9

Project: wagtailplus
Source File: apps.py
View license
    @cached_property
    def applicable_models(self):
        """
        Returns a list of model classes that subclass Page
        and include a "tags" field.

        :rtype: list.
        """
        Page        = apps.get_model('wagtailcore', 'Page')
        applicable  = []

        for model in apps.get_models():
            meta    = getattr(model, '_meta')
            fields  = meta.get_all_field_names()

            if issubclass(model, Page) and 'tags' in fields:
                applicable.append(model)

        return applicable

Example 10

Project: django-seo2
Source File: options.py
View license
    def _set_seo_models(self, value):
        """Gets the actual models to be used."""
        seo_models = []
        for model_name in value:
            if "." in model_name:
                app_label, model_name = model_name.split(".", 1)
                model = apps.get_model(app_label, model_name)
                if model:
                    seo_models.append(model)
            else:
                app = apps.get_app_config(model_name)
                if app:
                    seo_models.extend(app.get_models())

        self.seo_models = seo_models

Example 11

Project: ava
Source File: utils.py
View license
def store_credential_in_database(model_name, integration_id, credential):
    adapter = apps.get_model(model_name)
    oauth_adapter, created = adapter.objects.get_or_create(pk=integration_id)
    log.debug("Preparing to store credential " + str(credential))
    try:
        oauth_adapter.credential = credential.to_json()
    except Exception as e:
        oauth_adapter.credential = str(credential)

    oauth_adapter.save()

Example 12

Project: ava
Source File: utils.py
View license
def retrieve_credential_from_database(model_name, integration_id):
    adapter = apps.get_model(model_name)
    oauth_adapter = adapter.objects.get(pk=integration_id)
    credential_json = oauth_adapter.credential
    if credential_json is None:
        return None
    credential = oauth2client.client.OAuth2Credentials.from_json(credential_json)
    return credential

Example 13

Project: ava
Source File: utils.py
View license
def add_identifier(model_name, model_owner, identifier_type, identifier, is_primary=False):
    identifier_model = apps.get_model(model_name)
    model, created = identifier_model.objects.get_or_create(identifier=identifier,
                                                            identifier_type=identifier_type,
                                                            belongs_to=model_owner)
    model.primary_identifier = is_primary
    model.save()

Example 14

Project: shuup
Source File: __init__.py
View license
    def __init__(self, model, default_columns, *args, **kwargs):
        if isinstance(model, six.string_types) and model == settings.AUTH_USER_MODEL:
            model = apps.get_model(settings.AUTH_USER_MODEL)

        self.model = model
        self.default_columns = default_columns
        self.ensure_initial_columns(default_columns)
        self.column_spec = self._build_settings_columns()
        self.columns = [column for column in self.column_spec if self.get_config(column.id)]

Example 15

Project: mezzanine
Source File: __init__.py
View license
def get_profile_model():
    """
    Returns the Mezzanine profile model, defined in
    ``settings.ACCOUNTS_PROFILE_MODEL``, or ``None`` if no profile
    model is configured.
    """

    if not getattr(settings, "ACCOUNTS_PROFILE_MODEL", None):
        raise ProfileNotConfigured

    try:
        return apps.get_model(settings.ACCOUNTS_PROFILE_MODEL)
    except ValueError:
        raise ImproperlyConfigured("ACCOUNTS_PROFILE_MODEL must be of "
                                   "the form 'app_label.model_name'")
    except LookupError:
        raise ImproperlyConfigured("ACCOUNTS_PROFILE_MODEL refers to "
                                   "model '%s' that has not been installed"
                                   % settings.ACCOUNTS_PROFILE_MODEL)

Example 16

Project: django-bulbs
Source File: views.py
View license
    def get_videos_for_redirect(self, videohub_ref_id):
        video_model_name = getattr(settings, "VIDEO_MODEL", "")
        video_model = apps.get_model(video_model_name)
        videos = video_model.objects.filter(
            videohub_ref__id=int(videohub_ref_id),
            published__lte=timezone.now(),
        ).order_by(
            '-published'
        ).all()

        return videos

Example 17

Project: wagtail
Source File: registry.py
View license
    def get_by_natural_key(self, app_label, model_name):
        """
        Get a setting model using its app_label and model_name.

        If the app_label.model_name combination is not a valid model, or the
        model is not registered as a setting, returns None.
        """
        try:
            Model = apps.get_model(app_label, model_name)
        except LookupError:
            return None
        if Model not in registry:
            return None
        return Model

Example 18

Project: wagtail
Source File: signal_handlers.py
View license
def register_signal_handlers():
    # Get list of models that are page types
    Page = apps.get_model('wagtailcore', 'Page')
    indexed_models = [model for model in apps.get_models() if issubclass(model, Page)]

    # Loop through list and register signal handlers for each one
    for model in indexed_models:
        page_published.connect(page_published_signal_handler, sender=model)
        page_unpublished.connect(page_unpublished_signal_handler, sender=model)

Example 19

Project: wagtail
Source File: snippets.py
View license
def get_snippet_model_from_url_params(app_name, model_name):
    """
    Retrieve a model from an app_label / model_name combo.
    Raise Http404 if the model is not a valid snippet type.
    """
    try:
        model = apps.get_model(app_name, model_name)
    except LookupError:
        raise Http404
    if model not in get_snippet_models():
        # don't allow people to hack the URL to edit content types that aren't registered as snippets
        raise Http404

    return model

Example 20

Project: Django-facebook
Source File: utils.py
View license
def get_profile_model():
    '''
    Get the profile model if present otherwise return None
    '''
    model = None
    profile_string = getattr(settings, 'AUTH_PROFILE_MODULE', None)
    if profile_string:
        app_label, model_label = profile_string.split('.')
        model = apps.get_model(app_label, model_label)
    return model

Example 21

Project: django-janyson
Source File: descriptors.py
View license
    def _get_model(self):
        model = self.options.model
        if isinstance(model, six.string_types):
            model = apps.get_model(model)
            self.options.model = model
        return model

Example 22

Project: django-cachalot
Source File: cachalot.py
View license
@register.assignment_tag
def get_last_invalidation(*tables_or_model_lookups, **kwargs):
    tables_or_models = []
    for table_or_model_lookup in tables_or_model_lookups:
        if '.' in table_or_model_lookup:
            tables_or_models.append(apps.get_model(table_or_model_lookup))
        else:
            tables_or_models.append(table_or_model_lookup)
    return get_last_invalidation_function(*tables_or_models, **kwargs)

Example 23

Project: Wooey
Source File: 0019_userfile_data.py
View license
def cleanup_tests(apps, schema_editor):
    WooeyFile = apps.get_model('wooey', 'WooeyFile')
    Favorite = apps.get_model('wooey', 'Favorite')
    WooeyJob = apps.get_model('wooey', 'WooeyJob')
    ScriptParameter = apps.get_model('wooey', 'ScriptParameter')
    ScriptParameters = apps.get_model('wooey', 'ScriptParameters')
    ScriptParameterGroup = apps.get_model('wooey', 'ScriptParameterGroup')
    ScriptVersion = apps.get_model('wooey', 'ScriptVersion')
    Script = apps.get_model('wooey', 'Script')
    WooeyFile.objects.all().delete()
    Favorite.objects.all().delete()
    WooeyJob.objects.all().delete()
    ScriptParameter.objects.all().delete()
    ScriptParameters.objects.all().delete()
    ScriptParameterGroup.objects.all().delete()
    ScriptVersion.objects.all().delete()
    Script.objects.all().delete()

Example 24

Project: django-autocomplete-light
Source File: utils.py
View license
    def get_model(self, sender):
        """Return either the preset model, either the sender's TestModel."""
        if self.model_name is None:
            return sender.get_model('TestModel')
        else:
            return apps.get_model(self.model_name)

Example 25

View license
    def setUp(self):
        super(LinkedDataFormTest, self).setUp()
        User = apps.get_model('auth.user')  # noqa
        self.owner, c = User.objects.get_or_create(
            username='owner'
        )
        self.other_user, c = User.objects.get_or_create(
            username='other'
        )

Example 26

View license
    def setUp(self):
        super(LinkedDataFormTest, self).setUp()
        User = apps.get_model('auth.user')  # noqa
        self.owner, c = User.objects.get_or_create(
            username='owner'
        )
        self.other_user, c = User.objects.get_or_create(
            username='other'
        )

Example 27

Project: django-municipios
Source File: views.py
View license
def municipios_ajax(request, uf, app_label, object_name):
    model_cls = apps.get_model(app_label, object_name)

    municipio_list = model_cls.objects.filter(Q(uf=uf)).order_by('nome')
    return render_to_response("municipios/municipios_options.html",
                              {"municipio_list": municipio_list},
                              context_instance=RequestContext(request))

Example 28

Project: cloudless
Source File: clear.py
View license
def run():
    Image = apps.get_model('train', 'Image')
    Image.objects.all().delete()
    files = glob.glob(os.path.join(
        settings.BASE_DIR, 'train', 'static', 'training_images', '*.png'
    ))
    for f in files:
        os.remove(f)

Example 29

Project: cadasta-platform
Source File: managers.py
View license
def create_options(options, question, errors=[]):
    if options:
        for o, idx in zip(options, itertools.count()):
            QuestionOption = apps.get_model('questionnaires', 'QuestionOption')

            QuestionOption.objects.create(
                question=question, index=idx+1, name=o['name'],
                label_xlat=o.get('label_xlat', o.get('label', {}))
            )
    else:
        errors.append(_("Please provide at least one option for field"
                        " '{field_name}'".format(field_name=question.name)))

Example 30

Project: cadasta-platform
Source File: managers.py
View license
    def create(self, content_object=None, *args, **kwargs):
        with transaction.atomic():
            resource = self.model(**kwargs)
            resource.save()

            if content_object:
                ContentObject = apps.get_model('resources', 'ContentObject')
                ContentObject.objects.create(
                    resource=resource,
                    content_object=content_object
                )

            return resource

Example 31

Project: cadasta-platform
Source File: mixins.py
View license
    @property
    def resources(self):
        if not hasattr(self, '_resources'):
            ContentObject = apps.get_model('resources', 'ContentObject')
            Resource = apps.get_model('resources', 'Resource')

            model_type = ContentType.objects.get_for_model(self)

            cnt_objs = ContentObject.objects.filter(
                content_type__pk=model_type.id,
                object_id=self.id
            )
            self._resources = Resource.objects.filter(
                content_objects__in=cnt_objs)
        return self._resources

Example 32

Project: django-categories
Source File: migration.py
View license
def field_exists(app_name, model_name, field_name):
    """
    Does the FK or M2M table exist in the database already?
    """
    model = apps.get_model(app_name, model_name)
    table_name = model._meta.db_table
    cursor = connection.cursor()
    field_info = connection.introspection.get_table_description(cursor, table_name)
    field_names = [f.name for f in field_info]
    return field_name in field_names

Example 33

Project: django-categories
Source File: category_tags.py
View license
def get_cat_model(model):
    """
    Return a class from a string or class
    """
    try:
        if isinstance(model, string_types):
            model_class = apps.get_model(*model.split("."))
        elif issubclass(model, CategoryBase):
            model_class = model
        if model_class is None:
            raise TypeError
    except TypeError:
        raise TemplateSyntaxError("Unknown model submitted: %s" % model)
    return model_class

Example 34

Project: django-categories
Source File: category_tags.py
View license
def get_latest_objects_by_category(category, app_label, model_name, set_name, date_field='pub_date', num=15):
    m = apps.get_model(app_label, model_name)
    if not isinstance(category, CategoryBase):
        category = Category.objects.get(slug=str(category))
    children = category.children.all()
    ids = []
    for cat in list(children) + [category]:
        if hasattr(cat, '%s_set' % set_name):
            ids.extend([x.pk for x in getattr(cat, '%s_set' % set_name).all()[:num]])

    return m.objects.filter(pk__in=ids).order_by('-%s' % date_field)[:num]

Example 35

Project: SHARE
Source File: bot.py
View license
    def run(self, chunk_size=500):
        self.setup()

        logger.info('Loading up indexed models')
        for model_name in self.config.INDEX_MODELS:
            model = apps.get_model('share', model_name)
            qs = model.objects.filter(date_modified__gt=self.last_run).values_list('id', flat=True)
            logger.info('Looking for %ss that have been modified after %s', model, self.last_run)

            logger.info('Found %s %s that must be updated in ES', qs.count(), model)
            for i, batch in enumerate(chunk(qs.all(), chunk_size)):
                IndexModelTask().apply_async((self.config.label, self.started_by.id, model.__name__, batch,))

        logger.info('Starting task to index sources')
        IndexSourceTask().apply_async((self.config.label, self.started_by.id))

Example 36

Project: SHARE
Source File: robot.py
View license
    def __call__(self, apps, schema_editor):
        ShareUser = apps.get_model('share', 'ShareUser')
        Application = apps.get_model('oauth2_provider', 'Application')
        AccessToken = apps.get_model('oauth2_provider', 'AccessToken')
        migration_user = ShareUser.objects.get(username=self.config.name, robot=self.config.name)
        application_user = ShareUser.objects.get(username=settings.APPLICATION_USERNAME)
        application = Application.objects.get(user=application_user)
        client_secret = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(64))
        AccessToken.objects.create(
            user=migration_user,
            application=application,
            expires=(timezone.now() + datetime.timedelta(weeks=20 * 52)),  # 20 yrs
            scope=settings.HARVESTER_SCOPES,
            token=client_secret
        )

Example 37

Project: SHARE
Source File: robot.py
View license
    def reverse(self, apps, schema_editor):
        PeriodicTask = apps.get_model('djcelery', 'PeriodicTask')
        try:
            PeriodicTask.get(
                task=self.config.task,
                args=json.dumps([self.config.label, 1]),  # Note 1 should always be the system user
            ).delete()
        except PeriodicTask.DoesNotExist:
            pass

Example 38

Project: django-fcm
Source File: utils.py
View license
def get_device_model():
    model = getattr(settings, "FCM_DEVICE_MODEL", DEFAULT_FCM_DEVICE_MODEL)
    try:
        return apps.get_model(model)
    except ValueError:
        raise ImproperlyConfigured("FCM_DEVICE_MODEL must be of the form 'app_label.model_name'")
    except LookupError:
        raise ImproperlyConfigured(
            "FCM_DEVICE_MODEL refers to model '%s' that has not been installed" % settings.FCM_DEVICE_MODEL
        )

Example 39

Project: django-getpaid
Source File: tasks.py
View license
@task
def get_payment_status_task(payment_id, p24_session_id, p24_order_id, p24_kwota):
    Payment = apps.get_model('getpaid', 'Payment')
    try:
        payment = Payment.objects.get(pk=int(payment_id))
    except Payment.DoesNotExist:
        logger.error('Payment does not exist pk=%d' % payment_id)
        return

    from getpaid.backends.przelewy24 import PaymentProcessor  # Avoiding circular import
    processor = PaymentProcessor(payment)
    processor.get_payment_status(p24_session_id, p24_order_id, p24_kwota)

Example 40

Project: django-getpaid
Source File: test_epaydk.py
View license
    def setUp(self):
        self.client = Client()
        Payment = apps.get_model('getpaid', 'Payment')
        order = Order(name='Test DKK order', total='123.45', currency='DKK')
        order.save()

        payment = Payment(order=order,
                          amount=order.total,
                          currency=order.currency,
                          backend='getpaid.backends.epaydk')
        payment.save()
        self.test_payment = Payment.objects.get(pk=payment.id)

Example 41

Project: djangosnippets.org
Source File: core_tags.py
View license
@register.filter
def call_manager(model_or_obj, method):
    # load up the model if we were given a string
    if isinstance(model_or_obj, str):
        model_or_obj = apps.get_model(*model_or_obj.split('.'))

    # figure out the manager to query
    if isinstance(model_or_obj, QuerySet):
        manager = model_or_obj
        model_or_obj = model_or_obj.model
    else:
        manager = model_or_obj._default_manager

    return getattr(manager, method)()

Example 42

Project: django-bmf
Source File: mixins.py
View license
    def get_bmfmodel(self):
        """
        return the model property or loads the model dynamically
        via the url kwargs (app, model) or throws a LookupError
        """
        if getattr(self, 'model', None):
            return self.model

        if 'app' not in self.kwargs or 'model' not in self.kwargs:
            raise LookupError('Can not find a model instance')

        # Raises also a LookupError, when it does not find a model
        self.model = apps.get_model(self.kwargs.get('app'), self.kwargs.get('model'))

        return self.model

Example 43

Project: 2buntu-blog
Source File: reference.py
View license
    def handleMatch(self, m):
        Model = apps.get_model(*self.MODEL)
        instance = None
        try:
            instance = Model.objects.get(pk=m.group(2))
        except Model.DoesNotExist:
            pass
        e = instance and self.create_element(instance)
        if e is None:
            e = markdown.util.etree.Element('p')
            e.set('class', 'text-muted')
            e.text = '[Invalid %s reference.]' % self.MODEL_NAME
        return e

Example 44

Project: django-precise-bbcode
Source File: __init__.py
View license
    def init_custom_bbcode_tags(self):
        """
        Find the user-defined BBCode tags and initializes their associated renderers.
        """
        BBCodeTag = apps.get_model('precise_bbcode', 'BBCodeTag')  # noqa
        if BBCodeTag:
            custom_tags = BBCodeTag.objects.all()
            for tag in custom_tags:
                self.parser.add_bbcode_tag(tag.parser_tag_klass)

Example 45

Project: django-precise-bbcode
Source File: __init__.py
View license
    def init_bbcode_smilies(self):
        """
        Find the user-defined smilies tags and register them to the BBCode parser.
        """
        SmileyTag = apps.get_model('precise_bbcode', 'SmileyTag')  # noqa
        if SmileyTag:
            custom_smilies = SmileyTag.objects.all()
            for smiley in custom_smilies:
                self.parser.add_smiley(smiley.code, smiley.html_code)

Example 46

Project: django-oauth-toolkit
Source File: models.py
View license
def get_application_model():
    """ Return the Application model that is active in this project. """
    try:
        app_label, model_name = oauth2_settings.APPLICATION_MODEL.split('.')
    except ValueError:
        e = "APPLICATION_MODEL must be of the form 'app_label.model_name'"
        raise ImproperlyConfigured(e)
    app_model = apps.get_model(app_label, model_name)
    if app_model is None:
        e = "APPLICATION_MODEL refers to model {0} that has not been installed"
        raise ImproperlyConfigured(e.format(oauth2_settings.APPLICATION_MODEL))
    return app_model

Example 47

Project: django-recommends
Source File: converters.py
View license
    def resolve_identifier(self, identifier):
        """
        The opposite of ``get_identifier()``
        """
        app_module, site_id, object_id = identifier.split(':')
        app_label, model = app_module.split('.')
        site = self.sites[int(site_id)]
        ModelClass = apps.get_model(app_label, model)
        model = ModelClass.objects.get(pk=object_id)
        return model, site

Example 48

Project: django-recommends
Source File: tasks.py
View license
@task(name='remove_suggestions')
def remove_suggestions(rated_model, object_id):
    from django.apps import apps
    from recommends.providers import recommendation_registry

    ObjectClass = apps.get_model(*rated_model.split('.'))
    provider_instance = recommendation_registry.get_provider_for_content(
        ObjectClass)
    obj = ObjectClass.objects.get(pk=object_id)

    provider_instance.storage.remove_recommendations(obj)

Example 49

Project: django-recommends
Source File: tasks.py
View license
@task(name='remove_similarities')
def remove_similarities(rated_model, object_id):
    from django.apps import apps
    from recommends.providers import recommendation_registry

    ObjectClass = apps.get_model(*rated_model.split('.'))
    provider_instance = recommendation_registry.get_provider_for_content(
        ObjectClass)
    obj = ObjectClass.objects.get(pk=object_id)

    provider_instance.storage.remove_similarities(obj)

Example 50

Project: feincms
Source File: forms.py
View license
    def label_for_value(self, value):
        match = re.match(
            # XXX this regex would be available as .models.REDIRECT_TO_RE
            r'^(?P<app_label>\w+).(?P<model_name>\w+):(?P<pk>\d+)$',
            value)

        if match:
            matches = match.groupdict()
            model = apps.get_model(matches['app_label'], matches['model_name'])
            try:
                instance = model._default_manager.get(pk=int(matches['pk']))
                return '&nbsp;<strong>%s (%s)</strong>' % (
                    instance, instance.get_absolute_url())

            except model.DoesNotExist:
                pass

        return ''