当前位置: 首页>>代码示例>>Python>>正文


Python models.ContentType类代码示例

本文整理汇总了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')
开发者ID:egasimus,项目名称:django-multistep-select,代码行数:7,代码来源:views.py

示例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
开发者ID:Wombatpm,项目名称:djangae,代码行数:35,代码来源:contenttypes.py

示例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()
开发者ID:BGCX261,项目名称:zkwiki-hg-to-git,代码行数:30,代码来源:management.py

示例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
开发者ID:donnel6809,项目名称:devil,代码行数:9,代码来源:management.py

示例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])
开发者ID:notanumber,项目名称:xapian-haystack,代码行数:9,代码来源:test_backend.py

示例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'")
开发者ID:django-fluent,项目名称:django-fluent-contents,代码行数:9,代码来源:test_models.py

示例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'))
开发者ID:TwigWorld,项目名称:django-rottweiler,代码行数:11,代码来源:test_backends.py

示例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)
开发者ID:Yevs,项目名称:FortyTwoTestTask,代码行数:11,代码来源:test_signal.py

示例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
开发者ID:wuher,项目名称:Bulldog,代码行数:12,代码来源:bulldog.py

示例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()
开发者ID:henriksa,项目名称:pootle,代码行数:15,代码来源:0006_auto__del_suggestion.py

示例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......"
开发者ID:SongJLG,项目名称:johan-doc,代码行数:48,代码来源:syncdb_contenttype.py

示例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)
开发者ID:kunanit,项目名称:adaptive-mooclet-lti,代码行数:31,代码来源:views.py

示例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
开发者ID:rtighe,项目名称:rapidsms,代码行数:7,代码来源:models.py

示例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')
开发者ID:fynjah,项目名称:django-pimp-my-filter,代码行数:29,代码来源:views.py

示例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()
开发者ID:AltCtrlSupr,项目名称:acspypanel,代码行数:7,代码来源:models.py


注:本文中的django.contrib.contenttypes.models.ContentType类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。