當前位置: 首頁>>代碼示例>>Python>>正文


Python ContentType.save方法代碼示例

本文整理匯總了Python中django.contrib.contenttypes.models.ContentType.save方法的典型用法代碼示例。如果您正苦於以下問題:Python ContentType.save方法的具體用法?Python ContentType.save怎麽用?Python ContentType.save使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.contrib.contenttypes.models.ContentType的用法示例。


在下文中一共展示了ContentType.save方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: text_description_to_model

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
def text_description_to_model(module, text, app_label, admin_register=True):
    dct = yaml.load(text)
    for model_name in dct.keys():
        fields = dct[model_name]['fields']
        attrs = {}

        for field in fields:
            attrs[field['id']] = _field_by_type(field['type'], field['title'])

        attrs['__module__'] = module.__name__

        model_name = str(model_name).capitalize()
        NewModel = type(model_name, (Model,), attrs)

        setattr(module, model_name, NewModel)

        new_ct = ContentType()
        new_ct.app_label = app_label
        new_ct.name = model_name
        new_ct.model = model_name.lower()
        new_ct.save()

        if admin_register:

            class Admin(admin.ModelAdmin):
                pass

            admin.site.register(NewModel, Admin)

    if admin_register:
        reload(import_module(settings.ROOT_URLCONF))
        clear_url_caches()
開發者ID:stushurik,項目名稱:django_dynamic_models,代碼行數:34,代碼來源:utils.py

示例2: update_contenttypes

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
def update_contenttypes(app, created_models, verbosity=2, **kwargs):
    """
    Creates content types for models in the given app, removing any model
    entries that no longer have a matching model class.
    """
    db = kwargs['db']
    ContentType.objects.clear_cache()
    content_types = list(ContentType.objects.using(db).filter(app_label=app.__name__.split('.')[-2]))
    app_models = get_models(app)
    if not app_models:
        return
    for klass in app_models:
        opts = klass._meta
        try:
            ct = ContentType.objects.using(db).get(app_label=opts.app_label,
                                                   model=opts.object_name.lower())
            content_types.remove(ct)
        except ContentType.DoesNotExist:
            ct = ContentType(name=smart_unicode(opts.verbose_name_raw),
                app_label=opts.app_label, model=opts.object_name.lower())
            ct.save(using=db)
            if verbosity >= 2:
                print "Adding content type '%s | %s'" % (ct.app_label, ct.model)
    # The presence of any remaining content types means the supplied app has an
    # undefined model and can safely be removed, which cascades to also remove
    # related permissions.
    for ct in content_types:
        if verbosity >= 2:
            print "Deleting stale content type '%s | %s'" % (ct.app_label, ct.model)
        ct.delete()
開發者ID:BGCX261,項目名稱:zkwiki-hg-to-git,代碼行數:32,代碼來源:management.py

示例3: _ensure_content_type

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
def _ensure_content_type():
    """ Add the bulldog content type to the database if it's missing. """
    from django.contrib.contenttypes.models import ContentType
    try:
        row = ContentType.objects.get(app_label=PERM_APP_NAME)
    except ContentType.DoesNotExist:
        row = ContentType(name=PERM_APP_NAME, app_label=PERM_APP_NAME, model=PERM_APP_NAME)
        row.save()
    return row.id
開發者ID:donnel6809,項目名稱:devil,代碼行數:11,代碼來源:management.py

示例4: setUp

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
    def setUp(self):
        super(IndexationDjangoContentTypeTestCase, self).setUp()

        entry1 = ContentType(model='DjangoContentType')
        entry1.save()
        entry2 = DjangoContentType(content_type=entry1)
        entry2.save()

        self.backend.update(self.index, [entry2])
開發者ID:notanumber,項目名稱:xapian-haystack,代碼行數:11,代碼來源:test_backend.py

示例5: test_stale_model_str

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
 def test_stale_model_str(self):
     """
     No matter what, the ContentItem.__str__() should work.
     This would break the admin delete screen otherwise.
     """
     c = ContentType()
     c.save()
     a = ContentItem(polymorphic_ctype=c)
     self.assertEqual(str(a), "'(type deleted) 0' in 'None None'")
開發者ID:django-fluent,項目名稱:django-fluent-contents,代碼行數:11,代碼來源:test_models.py

示例6: test_user_is_checked_for_global_db_permission

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
 def test_user_is_checked_for_global_db_permission(self):
     user = User(is_active=True)
     user.save()
     content_type = ContentType(app_label='test_app')
     content_type.save()
     permission = Permission(content_type=content_type,
                             codename='test_permission')
     permission.save()
     user.user_permissions.add(permission)
     backend = PermissionBackend()
     self.assertTrue(backend.has_perm(user, 'test_app.test_permission'))
開發者ID:TwigWorld,項目名稱:django-rottweiler,代碼行數:13,代碼來源:test_backends.py

示例7: test_ignore_delete

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
    def test_ignore_delete(self):
        """
        Tests if deleting instance of a model from ignore list
        would not create db entry"""

        c = ContentType(app_label='hello', model='abc')
        c.save()
        old_count = ModelChange.objects.count()
        c.delete()
        new_count = ModelChange.objects.count()
        self.assertEqual(old_count, new_count)
開發者ID:Yevs,項目名稱:FortyTwoTestTask,代碼行數:13,代碼來源:test_signal.py

示例8: _add_content_type

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
    def _add_content_type(self):
        """
        Add the bulldog content type to the database if it's missing.
        """

        from django.contrib.contenttypes.models import ContentType
        try:
            row = ContentType.objects.get(app_label=self.PERM_APP_NAME)
        except ContentType.DoesNotExist:
            row = ContentType(name=self.PERM_APP_NAME, app_label=self.PERM_APP_NAME, model=self.PERM_APP_NAME)
            row.save()
        self._permission_content_type = row.id
開發者ID:wuher,項目名稱:Bulldog,代碼行數:14,代碼來源:bulldog.py

示例9: backwards

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
 def backwards(self, orm):
     # Adding model 'Suggestion'
     db.create_table('pootle_app_suggestion', (
         ('translation_project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['pootle_translationproject.TranslationProject'])),
         ('state', self.gf('django.db.models.fields.CharField')(default='pending', max_length=16, db_index=True)),
         ('suggester', self.gf('django.db.models.fields.related.ForeignKey')(related_name='suggester', null=True, to=orm['pootle_profile.PootleProfile'])),
         ('review_time', self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True)),
         ('reviewer', self.gf('django.db.models.fields.related.ForeignKey')(related_name='reviewer', null=True, to=orm['pootle_profile.PootleProfile'])),
         ('creation_time', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True, db_index=True)),
         ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
         ('unit', self.gf('django.db.models.fields.IntegerField')(db_index=True)),
     ))
     db.send_create_signal('pootle_app', ['Suggestion'])
     ct = ContentType(app_label='pootle_app', model='suggestion', name='suggestion')
     ct.save()
開發者ID:henriksa,項目名稱:pootle,代碼行數:17,代碼來源:0006_auto__del_suggestion.py

示例10: update_contenttypes

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
def update_contenttypes(app, created_models, verbosity=2, **kwargs):
    """
    Creates content types for models in the given app, removing any model
    entries that no longer have a matching model class.
    """
#    print u"johan-----------------------------: 更新contenttypes 表"
    ContentType.objects.clear_cache()
    content_types = list(ContentType.objects.filter(app_label=app.__name__.split('.')[-2])) # 得到app中的所有ContentType
    app_models = get_models(app)    # api 應用例子
    if not app_models:
        return
    for klass in app_models:    #-----------------------遍曆 app 所有 model        添加新模型對應的 ContentType
        opts = klass._meta
        try:
            ct = ContentType.objects.get(app_label=opts.app_label,
                                         model=opts.object_name.lower())
            content_types.remove(ct)
        except ContentType.DoesNotExist:
            ct = ContentType(name=u"%s"%opts.verbose_name,
                app_label=opts.app_label, model=opts.object_name.lower())
            ct.save()
            if verbosity >= 2:  # ------------------------是否顯示運行信息
                print "Adding content type '%s | %s'......" % (ct.app_label, ct.model)
    # The presence of any remaining content types means the supplied app has an
    # undefined model. Confirm that the content type is stale before deletion.
    if content_types:   # ------------------------------去除已被刪除model 對應的 content_type
        if kwargs.get('interactive', False):
            content_type_display = '\n'.join(['    %s | %s' % (ct.app_label, ct.model) for ct in content_types])
            ok_to_delete = raw_input("""The following content types are stale and need to be deleted:

%s

Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.

    Type 'yes' to continue, or 'no' to cancel: """ % content_type_display)
        else:
            ok_to_delete = False

        if ok_to_delete == 'yes':
            for ct in content_types:
                if verbosity >= 2:
                    print "Deleting stale content type '%s | %s'......" % (ct.app_label, ct.model)
                ct.delete()
        else:
            if verbosity >= 2:
                print "Stale content types remain......"
開發者ID:SongJLG,項目名稱:johan-doc,代碼行數:50,代碼來源:syncdb_contenttype.py

示例11: get

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
    def get(self, **kwargs):
        self._repopulate_if_necessary()

        if "pk" in kwargs:
            kwargs["id"] = kwargs["pk"]
            del kwargs["pk"]

        if "id" in kwargs:
            dic = self._get_from_store(int(kwargs["id"]))
        else:
            for ct in self._store.content_types.values():
                for k, v in kwargs.items():
                    if k not in ct:
                        raise ContentType.DoesNotExist()

                    if ct[k] != v:
                        break
                else:
                    dic = ct
                    break
            else:
                raise ContentType.DoesNotExist()

        def disable_save(*args, **kwargs):
            raise NotImplementedError("You can't save simulated content types")

        # We do this because some tests to comparisons with 'is' so we store
        # constructed ContentTypes in the thread local and return them if possible
        if dic["id"] in self._store.constructed_instances:
            return self._store.constructed_instances[dic["id"]]
        else:
            result = ContentType(**dic)
            result.save = new.instancemethod(disable_save, ContentType, result)
            self._store.constructed_instances[dic["id"]] = result
            return result
開發者ID:Wombatpm,項目名稱:djangae,代碼行數:37,代碼來源:contenttypes.py

示例12: create_contenttypes

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
def create_contenttypes(app, created_models, verbosity=2):
    from django.contrib.contenttypes.models import ContentType
    ContentType.objects.clear_cache()
    app_models = get_models(app)
    if not app_models:
        return
    for klass in app_models:
        opts = klass._meta
        try:
            ContentType.objects.get(app_label=opts.app_label,
                model=opts.object_name.lower())
        except ContentType.DoesNotExist:
            ct = ContentType(name=str(opts.verbose_name),
                app_label=opts.app_label, model=opts.object_name.lower())
            ct.save()
            if verbosity >= 2:
                print "Adding content type '%s | %s'" % (ct.app_label, ct.model)
開發者ID:0xmilk,項目名稱:appscale,代碼行數:19,代碼來源:management.py

示例13: setUp

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
    def setUp(self):
        person = Person()
		
        User.objects.create(username="user1", password="password")		
        person.user = User.objects.get(username="user1")
	    
        person.birthDate = "1990-05-14"
        person.birthForeignCity = "Melbourne"
        person.birthForeignState = "Victoria"
        person.birthForeignCountry = '1'
        
        person.save()
        
        contentType = ContentType()
        contentType.app_label = "auth"
        contentType.model = "any"
        contentType.save()
        
        emailType = EmailType()
        emailType.description = "Email Type"
        emailType.save()
        email = Email()
        email.email = "[email protected]"
        email.email_type = EmailType.objects.all()[0]
        email.content_object = person
        email.save()

        site = Site()
        site.description = "this is a website"
        site.site = "www.google.com.br"
        site.content_object = person
        site.save()

        person.save()

        self.p = Person.objects.get(user_id=person.user.id)

	def tearDown(self):
	    for person in Person.objects.all():
	        person.delete()

	    for user in User.objects.all():
	        user.delete()
開發者ID:caep-unb,項目名稱:gestorpsi,代碼行數:45,代碼來源:tests_models.py

示例14: permission_add

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
def permission_add(module, using=None):
    '''
    添加自定義權限
    '''
    content_type = None
    try:
        if not using:
            content_type = ContentType.objects.get(app_label=settings.PERMISSION_APP, model=module)
        else:
            content_type = ContentType.objects.using(using).get(app_label=settings.PERMISSION_APP, model=module)
    except:
        content_type = ContentType(name=module, app_label=settings.PERMISSION_APP, model=module)
        content_type.save(using=using)
        
    for op in operations.values():
        try:
            perm = Permission(codename='%s_%s'%(op,module),name='can %s %s'%(op,module),content_type=content_type)
            perm.save(using=using)
        except:
            pass
開發者ID:baifendian,項目名稱:TopicTrend,代碼行數:22,代碼來源:permission.py

示例15: register_model

# 需要導入模塊: from django.contrib.contenttypes.models import ContentType [as 別名]
# 或者: from django.contrib.contenttypes.models.ContentType import save [as 別名]
def register_model(**kwargs):
    """
    Register the model to metaman when it's ready. This
    will register all related many_to_many models too
    """
    sender = kwargs['sender']
    if sender._meta.app_label == META_OBJECTS_LABEL:
        opts = sender._meta
        # register the content type if does not exist already
        try:
            ct = ContentType.objects.get(app_label=META_OBJECTS_LABEL, 
                                         model=opts.object_name.lower())
        except ContentType.DoesNotExist:
            ct = ContentType(name=smart_unicode(opts.verbose_name_raw),
                        app_label=META_OBJECTS_LABEL, model=opts.object_name.lower())
            ct.save()
        except DatabaseError:
            # should only happen on first syncdb
            pass
        metaman.add_model(sender)
開發者ID:ferama,項目名稱:fermeta,代碼行數:22,代碼來源:models.py


注:本文中的django.contrib.contenttypes.models.ContentType.save方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。