python类ContentType()的实例源码

managers.py 文件源码 项目:minimum-entropy 作者: DistrictDataLabs 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def punch_ballot(self, content=None, user=None, vote=0):
        """
        Essentially `update_or_create` with ContentType lookup
        """
        if content is None or user is None:
            raise TypeError("content and user are required for punch ballot")

        kwargs = {
            'content_type': ContentType.objects.get_for_model(content),
            'object_id': content.id,
            'user': user,
            'defaults': {
                'vote': vote,
            }
        }

        return self.update_or_create(**kwargs)
fields.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        try:
            return getattr(instance, self.cache_attr)
        except AttributeError:
            rel_obj = None

            # Make sure to use ContentType.objects.get_for_id() to ensure that
            # lookups are cached (see ticket #5570). This takes more code than
            # the naive ``getattr(instance, self.ct_field)``, but has better
            # performance when dealing with GFKs in loops and such.
            f = self.model._meta.get_field(self.ct_field)
            ct_id = getattr(instance, f.get_attname(), None)
            if ct_id is not None:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                try:
                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
                except ObjectDoesNotExist:
                    pass
            setattr(instance, self.cache_attr, rel_obj)
            return rel_obj
forms.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )
forms.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )
sites.py 文件源码 项目:blog_django 作者: chnpmy 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")
        if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
                'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
models.py 文件源码 项目:blog_django 作者: chnpmy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_view_permissions(sender, **kwargs):
    """
    This syncdb hooks takes care of adding a view permission too all our
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.all():
        # build our permission slug
        codename = "view_%s" % content_type.model

        # if it doesn't exist..
        if not Permission.objects.filter(content_type=content_type, codename=codename):
            # add it
            Permission.objects.create(content_type=content_type,
                                      codename=codename,
                                      name="Can view %s" % content_type.name)
            #print "Added view permission for %s" % content_type.name

# check for all our view permissions after a syncdb
forms.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )
sites.py 文件源码 项目:dream_blog 作者: fanlion 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")

        default_template_engine = Engine.get_default()
        if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or
                        'django.core.context_processors.auth' in default_template_engine.context_processors):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
models.py 文件源码 项目:dream_blog 作者: fanlion 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def add_view_permissions(sender, **kwargs):
    """
    This syncdb hooks takes care of adding a view permission too all our
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.all():
        # build our permission slug
        codename = "view_%s" % content_type.model

        # if it doesn't exist..
        if not Permission.objects.filter(content_type=content_type, codename=codename):
            # add it
            Permission.objects.create(content_type=content_type,
                                      codename=codename,
                                      name="Can view %s" % content_type.name)
            # print "Added view permission for %s" % content_type.name


# check for all our view permissions after a syncdb
sites.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")


        default_template_engine = Engine.get_default()
        if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or
                'django.core.context_processors.auth' in default_template_engine.context_processors):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
models.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def add_view_permissions(sender, **kwargs):
    """
    This syncdb hooks takes care of adding a view permission too all our
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.all():
        # build our permission slug
        codename = "view_%s" % content_type.model

        # if it doesn't exist..
        if not Permission.objects.filter(content_type=content_type, codename=codename):
            # add it
            Permission.objects.create(content_type=content_type,
                                      codename=codename,
                                      name="Can view %s" % content_type.name)
            #print "Added view permission for %s" % content_type.name

# check for all our view permissions after a syncdb
sites.py 文件源码 项目:djangoblog 作者: liuhuipy 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")


        default_template_engine = Engine.get_default()
        if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or
                'django.core.context_processors.auth' in default_template_engine.context_processors):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
models.py 文件源码 项目:djangoblog 作者: liuhuipy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_view_permissions(sender, **kwargs):
    """
    This syncdb hooks takes care of adding a view permission too all our
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.all():
        # build our permission slug
        codename = "view_%s" % content_type.model

        # if it doesn't exist..
        if not Permission.objects.filter(content_type=content_type, codename=codename):
            # add it
            Permission.objects.create(content_type=content_type,
                                      codename=codename,
                                      name="Can view %s" % content_type.name)
            #print "Added view permission for %s" % content_type.name

# check for all our view permissions after a syncdb
forms.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )
models.py 文件源码 项目:django-jsonattrs 作者: Cadasta 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def lookup(self, instance=None, content_type=None, selectors=None):
        if instance is not None and content_type is None:
            content_type = ContentType.objects.get_for_model(instance)
        if selectors is None and instance is not None:
            selectors = self._get_selectors(instance, content_type)
        selectors = tuple(selectors)
        if any(s is None for s in selectors):
            return None

        # Look for schema list in cache, keyed by content type and
        # selector list.
        key = schema_cache_key(content_type, selectors)
        cached = caches['jsonattrs'].get(key)
        if cached is not None:
            return cached

        # Not in cache: build schema list using increasing selector
        # sequences.
        base_schemas = self.filter(content_type=content_type)
        schemas = []
        for i in range(len(selectors) + 1):
            schemas += list(base_schemas.filter(selectors=selectors[:i]))
        caches['jsonattrs'].set(key, schemas)
        return schemas
models.py 文件源码 项目:django-jsonattrs 作者: Cadasta 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _get_selectors(self, instance, content_type=None):
        if content_type is None:
            content_type = ContentType.objects.get_for_model(instance)

        # Lazily pre-process per-content type selector definitions.
        if len(self.content_type_to_selectors) == 0:
            for k, v in settings.JSONATTRS_SCHEMA_SELECTORS.items():
                a, m = k.split('.')
                self.content_type_to_selectors[
                    ContentType.objects.get(app_label=a, model=m)
                ] = v

        # Build full list of selectors from instance.
        selectors = []
        for s in self.content_type_to_selectors[content_type]:
            selector = instance
            s = s.replace('.pk', '_id')
            for step in s.split('.'):
                selector = getattr(selector, step, None)
            selectors.append(str(selector))
        return tuple(selectors)
sites.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")


        default_template_engine = Engine.get_default()
        if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or
                'django.core.context_processors.auth' in default_template_engine.context_processors):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
models.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_view_permissions(sender, **kwargs):
    """
    This syncdb hooks takes care of adding a view permission too all our
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.all():
        # build our permission slug
        codename = "view_%s" % content_type.model

        # if it doesn't exist..
        if not Permission.objects.filter(content_type=content_type, codename=codename):
            # add it
            Permission.objects.create(content_type=content_type,
                                      codename=codename,
                                      name="Can view %s" % content_type.name)
            #print "Added view permission for %s" % content_type.name

# check for all our view permissions after a syncdb
widgets.py 文件源码 项目:django-content-gallery 作者: Kemaweyan 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _filter_choices(self):
        """
        Removes the ContentType objects that have not
        the 'gallery_visible' attribute set to True.
        """
        filtered_choices = []
        # initially self.choices contains all content types
        for choice in self.choices:
            try:
                if choice[0] == "":
                    # add the empty choice
                    filtered_choices.append(choice)
                    continue
                # get the content type and determine the model
                ctype = ContentType.objects.get(pk=int(choice[0]))
                model_class = ctype.model_class()
                if model_class.gallery_visible:
                    # add the choice if the model has the 'gallery_visible'
                    # attribute and it's set to True
                    filtered_choices.append(choice)
            except:
                # the model has not the 'gallery_visible' attribute
                pass
        # replace original choices
        self.choices = filtered_choices
0002_drop_djcelery.py 文件源码 项目:paas-tools 作者: imperodesign 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def forwards(self, orm):
        "Drop django-celery tables."
        tables_to_drop = [
            'djcelery_taskstate',
            'djcelery_workerstate',
            'djcelery_periodictask',
            'djcelery_periodictasks',
            'djcelery_crontabschedule',
            'djcelery_intervalschedule',
            'celery_tasksetmeta',
            'celery_taskmeta',
        ]
        for table in tables_to_drop:
            if table in orm:
                db.delete_table(table)
        ContentType.objects.filter(app_label='djcelery').delete()
0002_drop_djcelery.py 文件源码 项目:paas-tools 作者: imperodesign 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def forwards(self, orm):
        "Drop django-celery tables."
        tables_to_drop = [
            'djcelery_taskstate',
            'djcelery_workerstate',
            'djcelery_periodictask',
            'djcelery_periodictasks',
            'djcelery_crontabschedule',
            'djcelery_intervalschedule',
            'celery_tasksetmeta',
            'celery_taskmeta',
        ]
        for table in tables_to_drop:
            if table in orm:
                db.delete_table(table)
        ContentType.objects.filter(app_label='djcelery').delete()
forms.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )
fields.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        try:
            return getattr(instance, self.cache_attr)
        except AttributeError:
            rel_obj = None

            # Make sure to use ContentType.objects.get_for_id() to ensure that
            # lookups are cached (see ticket #5570). This takes more code than
            # the naive ``getattr(instance, self.ct_field)``, but has better
            # performance when dealing with GFKs in loops and such.
            f = self.model._meta.get_field(self.ct_field)
            ct_id = getattr(instance, f.get_attname(), None)
            if ct_id is not None:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                try:
                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
                except ObjectDoesNotExist:
                    pass
            setattr(instance, self.cache_attr, rel_obj)
            return rel_obj
forms.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )
sites.py 文件源码 项目:xadmin-markdown-editor 作者: bluenknight 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")


        default_template_engine = Engine.get_default()
        if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or
                'django.core.context_processors.auth' in default_template_engine.context_processors):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
models.py 文件源码 项目:xadmin-markdown-editor 作者: bluenknight 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def add_view_permissions(sender, **kwargs):
    """
    This syncdb hooks takes care of adding a view permission too all our
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.all():
        # build our permission slug
        codename = "view_%s" % content_type.model

        # if it doesn't exist..
        if not Permission.objects.filter(content_type=content_type, codename=codename):
            # add it
            Permission.objects.create(content_type=content_type,
                                      codename=codename,
                                      name="Can view %s" % content_type.name)
            #print "Added view permission for %s" % content_type.name

# check for all our view permissions after a syncdb
fields.py 文件源码 项目:wanblog 作者: wanzifa 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        try:
            return getattr(instance, self.cache_attr)
        except AttributeError:
            rel_obj = None

            # Make sure to use ContentType.objects.get_for_id() to ensure that
            # lookups are cached (see ticket #5570). This takes more code than
            # the naive ``getattr(instance, self.ct_field)``, but has better
            # performance when dealing with GFKs in loops and such.
            f = self.model._meta.get_field(self.ct_field)
            ct_id = getattr(instance, f.get_attname(), None)
            if ct_id is not None:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                try:
                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
                except ObjectDoesNotExist:
                    pass
            setattr(instance, self.cache_attr, rel_obj)
            return rel_obj
forms.py 文件源码 项目:wanblog 作者: wanzifa 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )
fields.py 文件源码 项目:tabmaster 作者: NicolasMinghetti 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        try:
            return getattr(instance, self.cache_attr)
        except AttributeError:
            rel_obj = None

            # Make sure to use ContentType.objects.get_for_id() to ensure that
            # lookups are cached (see ticket #5570). This takes more code than
            # the naive ``getattr(instance, self.ct_field)``, but has better
            # performance when dealing with GFKs in loops and such.
            f = self.model._meta.get_field(self.ct_field)
            ct_id = getattr(instance, f.get_attname(), None)
            if ct_id is not None:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                try:
                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
                except ObjectDoesNotExist:
                    pass
            setattr(instance, self.cache_attr, rel_obj)
            return rel_obj
forms.py 文件源码 项目:tabmaster 作者: NicolasMinghetti 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, data=None, files=None, instance=None, save_as_new=None,
                 prefix=None, queryset=None, **kwargs):
        opts = self.model._meta
        self.instance = instance
        self.rel_name = '-'.join((
            opts.app_label, opts.model_name,
            self.ct_field.name, self.ct_fk_field.name,
        ))
        if self.instance is None or self.instance.pk is None:
            qs = self.model._default_manager.none()
        else:
            if queryset is None:
                queryset = self.model._default_manager
            qs = queryset.filter(**{
                self.ct_field.name: ContentType.objects.get_for_model(
                    self.instance, for_concrete_model=self.for_concrete_model),
                self.ct_fk_field.name: self.instance.pk,
            })
        super(BaseGenericInlineFormSet, self).__init__(
            queryset=qs, data=data, files=files,
            prefix=prefix,
            **kwargs
        )


问题


面经


文章

微信
公众号

扫码关注公众号