本文整理汇总了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()
示例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()
示例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
示例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])
示例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'")
示例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'))
示例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)
示例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
示例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()
示例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......"
示例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
示例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)
示例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()
示例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
示例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)