本文整理汇总了Python中django.contrib.contenttypes.models.ContentType类的典型用法代码示例。如果您正苦于以下问题:Python ContentType类的具体用法?Python ContentType怎么用?Python ContentType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ContentType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: json_list
def json_list(request,app,model,lookup,value):
content = ContentType(app_label=app,model=model)
contentclass = content.model_class()
lookup_dict = { lookup:value }
queryset = contentclass.objects.filter(**lookup_dict)
return HttpResponse(serializers.serialize('json', queryset),
mimetype='application/json')
示例2: get
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
示例3: update_contenttypes
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()
示例4: _ensure_content_type
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
示例5: setUp
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])
示例6: test_stale_model_str
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'")
示例7: test_user_is_checked_for_global_db_permission
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'))
示例8: test_ignore_delete
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)
示例9: _add_content_type
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
示例10: backwards
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()
示例11: update_contenttypes
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......"
示例12: mooclet_create
def mooclet_create(request, **kwargs):
'''
create a new mooclet
required kwargs: quiz, type, parent object
'''
quiz = get_object_or_404(Quiz,pk=kwargs['quiz_id'])
mooclet_type = get_object_or_404(MoocletType,name=kwargs['type'])
# object class that the mooclet is attached to
parent_content_type = mooclet_type.content_type
parent_content = ContentType.get_object_for_this_type(parent_content_type, pk=kwargs[parent_content_type.name+'_id'])
if request.method == 'GET':
mooclet_form = MoocletForm(initial={'type':mooclet_type})
context = {
'quiz':quiz,
'mooclet_form':mooclet_form,
}
if 'question' in kwargs:
context['question'] = get_object_or_404(Question,pk=kwargs['question_id'])
if 'answer' in kwargs:
context['answer'] = get_object_or_404(Answer,pk=kwargs['answer_id'])
return render(request, 'engine/mooclet_create.html', context)
elif request.method == 'POST':
mooclet_form = MoocletForm(request.POST)
mooclet = mooclet_form.save()
prev_url = request.POST['prev']
return redirect(prev_url)
示例13: get_validation_errors
def get_validation_errors(self, token):
model_class = ContentType.model_class(self.lookup_type)
vals = model_class.objects.values_list(self.field_name, flat=True)
print "validating %s with %s" % (token, str(self))
if token not in vals:
return "%s not in list of %s %s" % (token, self.lookup_type.name, self.field_name)
return None
示例14: get_typeahead
def get_typeahead(request):
if request.is_ajax() and request.method == "POST":
if ('field' in request.POST and
'app' in request.POST and
'model' in request.POST):
ct = ContentType.objects.get_by_natural_key(request.POST['app'],
request.POST['model'])
instance = ContentType.model_class(ct)
f = dict([(x,x) for x in instance._meta.get_all_field_names() ])
try:
o = f[request.POST['field']]
o = instance._meta.get_field_by_name(o)[0]
except KeyError:
return HttpResponseForbidden('[{"error":"Forbidden"}]',
mimetype='application/json; charset=utf8')
o = o.related.parent_model
obj_list = o.objects.all()
lst = {}
for i,obj in enumerate(obj_list):
l = {}
l.update({"id":obj.id})
l.update({"unicode":obj.__unicode__()})
#not sure about __unicode__, actually
lst.update({i:l})
return HttpResponse(json.dumps(lst, indent = 4 * ' '),
mimetype='application/json; charset=utf8')
else:
return HttpResponseForbidden('[{"error":"Forbidden. Wrong headers."}]',
mimetype='application/json; charset=utf8')
示例15: save
def save(self, *args, **kwargs):
super(SettingKey, self).save(*args, **kwargs)
# Create and update default values for all objects
for obj in ContentType.get_all_objects_for_this_type(self.scope):
(sv, created) = SettingValue.objects.get_or_create(key=self, scope=ContentType.objects.get_for_model(obj), object_id=obj.pk)
if not created:
sv.save()