Python django.contrib.contenttypes.models.ContentType() Examples

The following are 30 code examples of django.contrib.contenttypes.models.ContentType(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.contenttypes.models , or try the search function .
Example #1
Source File: sites.py    From CTF_AWD_Platform with MIT License 6 votes vote down vote up
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.") 
Example #2
Source File: models.py    From django-protector with MIT License 6 votes vote down vote up
def restrict(self):
        # method restricts all objects down by restriction hierarchy
        if self.restriction != self:
            current_restriction_id = self.restriction_id
            current_restriction_ctype_id = self.restriction_content_type_id
            self.restriction = self
            if self.pk is not None:
                ctype_dict = self.get_restriction_descendants()
                for ctype_id, object_ids in ctype_dict.items():
                    ctype = ContentType.objects.get_for_id(ctype_id)
                    objs = ctype.model_class().objects.filter(
                        pk__in=object_ids, restriction_id=current_restriction_id,
                        restriction_content_type_id=current_restriction_ctype_id
                    )
                    objs.update(
                        restriction_id=self.id,
                        restriction_content_type=ContentType.objects.get_for_model(self)
                    )
            self.save() 
Example #3
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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
        ) 
Example #4
Source File: models.py    From django-protector with MIT License 6 votes vote down vote up
def unrestrict(self):
        if self.restriction is None:
            return
        ctype_dict = self.get_restriction_descendants()
        current_restriction_id = self.restriction_id
        current_restriction_ctype_id = self.restriction_content_type_id
        for ctype_id, object_ids in ctype_dict.items():
            ctype = ContentType.objects.get_for_id(ctype_id)
            objs = ctype.model_class().objects.filter(
                pk__in=object_ids, restriction_id=current_restriction_id,
                restriction_content_type_id=current_restriction_ctype_id
            )
            # take only objects that restricted by same object as self
            objs.update(
                restriction_id=None,
                restriction_content_type=None
            )
        self.restriction = None
        self.save() 
Example #5
Source File: models.py    From srvup-rest-framework with Apache License 2.0 6 votes vote down vote up
def page_view_received(sender, **kwargs):
	kwargs.pop('signal', None)
	page_path = kwargs.pop('page_path')
	primary_obj = kwargs.pop('primary_obj', None)
	secondary_obj = kwargs.pop('secondary_obj', None)
	print secondary_obj
	user = sender
	if not user.is_authenticated():
		new_page_view = PageView.objects.create(path=page_path, timestamp=timezone.now())
	else:
		new_page_view = PageView.objects.create(path=page_path, user=user, timestamp=timezone.now())
	if primary_obj:
		new_page_view.primary_object_id = primary_obj.id
		new_page_view.primary_content_type = ContentType.objects.get_for_model(primary_obj)
		new_page_view.save()
	if secondary_obj:
		new_page_view.secondary_object_id = secondary_obj.id
		new_page_view.secondary_content_type = ContentType.objects.get_for_model(secondary_obj)
		new_page_view.save() 
Example #6
Source File: sites.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
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.") 
Example #7
Source File: models.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: test_page_queryset.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_specific_gracefully_handles_missing_rows(self):
        # 5928 - PageQuerySet.specific should gracefully handle pages whose ContentType
        # row in the specific table no longer exists

        # Trick specific_iterator into always looking for EventPages
        with mock.patch(
            'wagtail.core.query.ContentType.objects.get_for_id',
            return_value=ContentType.objects.get_for_model(EventPage),
        ):
            with self.assertWarnsRegex(RuntimeWarning, "Specific versions of the following pages could not be found"):
                pages = list(Page.objects.get(url_path='/home/').get_children().specific())

            # All missing pages should be supplemented with generic pages
            self.assertEqual(pages, [
                Page.objects.get(url_path='/home/events/'),
                Page.objects.get(url_path='/home/about-us/'),
                Page.objects.get(url_path='/home/other/'),
            ]) 
Example #9
Source File: models.py    From django-connections with MIT License 6 votes vote down vote up
def define_relationship(name, from_model, to_model):
    if name in _relationship_registry:
        raise KeyError(name)
    
    _from_ctype = from_model
    _to_ctype = to_model
    
    if isinstance(_from_ctype, str):
        _from_ctype = get_model(_from_ctype)
    if isinstance(_to_ctype, str):
        _to_ctype = get_model(_to_ctype)
    
    if not isinstance(_from_ctype, ContentType):
        _from_ctype = ContentType.objects.get_for_model(_from_ctype)
    if not isinstance(_to_ctype, ContentType):
        _to_ctype = ContentType.objects.get_for_model(_to_ctype)
    
    relationship = Relationship(name=name,
                                from_content_type=_from_ctype,
                                to_content_type=_to_ctype)
    
    _relationship_registry[name] = relationship
    return relationship 
Example #10
Source File: generic_relation.py    From django-GDPR with MIT License 6 votes vote down vote up
def __init__(self, app_name: str, model_name: Optional[str] = None, content_object_field: str = 'content_object'):
        """

        :param app_name: The name of the app or `<app_name>.<model_name>`
        :param model_name: The name of the model with GenericRelation
        :param content_type_field: The name of the FK to ContentType Model
        :param id_field: The id of the related model
        """
        if model_name is None:
            self.app_name, self.model_name = app_name.split('.')
        else:
            self.app_name = app_name
            self.model_name = model_name
        self.content_object_field = content_object_field

        super().__init__() 
Example #11
Source File: models.py    From django-klingon with GNU Lesser General Public License v3.0 6 votes vote down vote up
def translations_objects(self, lang):
        """
        Return the complete list of translation objects of a Translatable
        instance

        @type lang: string
        @param lang: a string with the name of the language

        @rtype: list of Translation
        @return: Returns a list of translations objects
        """
        return Translation.objects.filter(
            object_id=self.id,
            content_type=ContentType.objects.get_for_model(self),
            lang=lang
        ) 
Example #12
Source File: models.py    From django-klingon with GNU Lesser General Public License v3.0 6 votes vote down vote up
def translations_link(self):
        """
        Print on admin change list the link to see all translations for this object

        @type text: string
        @param text: a string with the html to link to the translations admin interface
        """
        translation_type = ContentType.objects.get_for_model(Translation)
        link = urlresolvers.reverse('admin:%s_%s_changelist' % (
            translation_type.app_label,
            translation_type.model),
        )

        object_type = ContentType.objects.get_for_model(self)
        link += '?content_type__id__exact=%s&object_id=%s' % (object_type.id, self.id)
        return '<a href="%s">translate</a>' % link 
Example #13
Source File: models.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
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 
Example #14
Source File: config.py    From django-river with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def settings(self):
        if self.cached_settings:
            return self.cached_settings
        else:
            from django.conf import settings
            allowed_configurations = {
                'CONTENT_TYPE_CLASS': ContentType,
                'USER_CLASS': settings.AUTH_USER_MODEL,
                'PERMISSION_CLASS': Permission,
                'GROUP_CLASS': Group,
                'INJECT_MODEL_ADMIN': False
            }
            river_settings = {}
            for key, default in allowed_configurations.items():
                river_settings[key] = getattr(settings, self.get_with_prefix(key), default)

            river_settings['IS_MSSQL'] = connection.vendor == 'microsoft'
            self.cached_settings = river_settings

            return self.cached_settings 
Example #15
Source File: models.py    From CTF_AWD_Platform with MIT License 6 votes vote down vote up
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 
Example #16
Source File: sites.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
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.") 
Example #17
Source File: models.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #18
Source File: models.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def toggle_collection_nav(cls, issue_type):
        """Toggles a nav item for the given issue_type
        :param `journal.models.IssueType` issue_type: The issue type to toggle
        """

        defaults = {
            "link_name": issue_type.plural_name,
            "link": "/collections/%s" % (issue_type.code),
        }
        content_type = ContentType.objects.get_for_model(issue_type.journal)

        nav, created = cls.objects.get_or_create(
            content_type=content_type,
            object_id=issue_type.pk,
            defaults=defaults,
        )

        if not created:
            nav.delete() 
Example #19
Source File: log.py    From byro with Apache License 2.0 6 votes vote down vote up
def flatten_objects(inobj, key_was=None):
    if isinstance(inobj, dict):
        return {k: flatten_objects(v, key_was=k) for k, v in inobj.items()}
    elif isinstance(inobj, (tuple, list)):
        return [flatten_objects(v) for v in inobj]
    elif isinstance(inobj, datetime.datetime):
        return inobj.strftime("%Y-%m-%d %H:%M:%S %Z")
    elif isinstance(inobj, datetime.date):
        return inobj.strftime("%Y-%m-%d")
    elif isinstance(inobj, uuid.UUID):
        return str(inobj)
    elif isinstance(inobj, decimal.Decimal) or (
        key_was == "amount" and isinstance(inobj, (int, float))
    ):
        return "{:.2f}".format(inobj)
    else:
        try:
            content_type = ContentType.objects.get_for_model(type(inobj))
            return {
                "object": content_type.name,
                "ref": (content_type.app_label, content_type.model, inobj.pk),
                "value": str(inobj),
            }
        except Exception:
            return str(inobj) 
Example #20
Source File: models.py    From django_OA with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #21
Source File: sites.py    From django_OA with GNU General Public License v3.0 6 votes vote down vote up
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.") 
Example #22
Source File: sites.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
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.") 
Example #23
Source File: generic_relation.py    From django-GDPR with MIT License 6 votes vote down vote up
def __init__(self, app_name: str, model_name: Optional[str] = None, content_type_field: str = 'content_type',
                 id_field: str = 'object_id'):
        """

        :param app_name: The name of the app or `<app_name>.<model_name>`
        :param model_name: The name of the model with GenericRelation
        :param content_type_field: The name of the FK to ContentType Model
        :param id_field: The id of the related model
        """
        if model_name is None:
            self.app_name, self.model_name = app_name.split('.')
        else:
            self.app_name = app_name
            self.model_name = model_name
        self.content_type_field = content_type_field
        self.id_field = id_field

        super().__init__() 
Example #24
Source File: options.py    From python with Apache License 2.0 5 votes vote down vote up
def get_content_type_for_model(obj):
    # Since this module gets imported in the application's root package,
    # it cannot import models from other applications at the module level.
    from django.contrib.contenttypes.models import ContentType
    return ContentType.objects.get_for_model(obj, for_concrete_model=False) 
Example #25
Source File: options.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def get_content_type_for_model(obj):
    # Since this module gets imported in the application's root package,
    # it cannot import models from other applications at the module level.
    from django.contrib.contenttypes.models import ContentType
    return ContentType.objects.get_for_model(obj, for_concrete_model=False) 
Example #26
Source File: dynamic_resource.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def get_or_create_permissions_for_class(self, DynamicResourceClass, additional_classes_used, config_entity):
        model_class = DynamicResourceClass.Meta.object_class
        for clazz in [model_class] + additional_classes_used:
            return map(lambda action: Permission.objects.get_or_create(
                codename='{0}_{1}'.format(action, clazz.__name__.lower()),
                # Since our dynamic model doesn't have a ContentType, borrow that of the ConfigEntity
                content_type_id=ContentType.objects.get(app_label="main", model=config_entity.__class__.__name__.lower()).id,
                # 50 is the name limit
                name='Can {0} {1}'.format(action, clazz.__name__)[-50:])[0],
                       ['add', 'change', 'delete']) 
Example #27
Source File: initdb.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def create_pootle_permissions(self):
        """Create Pootle's directory level permissions."""

        args = {
            "app_label": "pootle_app",
            "model": "directory",
        }

        pootle_content_type = self._create_object(ContentType, **args)[0]
        pootle_content_type.save()

        # Create the permissions.
        permissions = [
            {"name": _("Can access a project"), "codename": "view"},
            {"name": _("Cannot access a project"), "codename": "hide"},
            {
                "name": _("Can make a suggestion for a translation"),
                "codename": "suggest",
            },
            {"name": _("Can submit a translation"), "codename": "translate"},
            {"name": _("Can review suggestions"), "codename": "review"},
            {
                "name": _("Can perform administrative tasks"),
                "codename": "administrate",
            },
        ]

        criteria = {
            "content_type": pootle_content_type,
        }

        for permission in permissions:
            criteria.update(permission)
            self._create_object(Permission, **criteria) 
Example #28
Source File: __init__.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def fix_permission_content_type_post(**kwargs_):
    global permission_queryset
    if permission_queryset is not None:
        dir_content_type = ContentType.objects.get(
            app_label="pootle_app", model="directory"
        )
        dir_content_type.name = "pootle"
        dir_content_type.save()
        for permission in permission_queryset:
            permission.content_type = dir_content_type
            permission.save()
        permission_queryset = None 
Example #29
Source File: models.py    From django-protector with MIT License 5 votes vote down vote up
def generate_restriction(self):
        parent_object = self.get_parent_object()
        if parent_object is not None and isinstance(parent_object, Restricted):
            parent_restriction = Restriction.objects.get(
                object_id=parent_object.id,
                content_type=ContentType.objects.get_for_model(parent_object)
            )
        else:
            parent_restriction = None
        Restriction.objects.get_or_create(
            object_id=self.pk,
            content_type=ContentType.objects.get_for_model(self),
            defaults={'parent': parent_restriction}
        ) 
Example #30
Source File: common.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_content_type(cls, model):
        return ContentType.objects.get(app_label='servo', model=model)