def test_get_searched_permissions(mocker): ct1 = ContentType(app_label='myapp', model='mymodel1') ct2 = ContentType(app_label='myapp', model='mymodel2') model1 = mocker.Mock(_meta=mocker.Mock(model_name='mymodel1')) model2 = mocker.Mock(_meta=mocker.Mock(model_name='mymodel2')) perms = [[('add_mymodel1', 'Can add Mymodel1'), ('change_mymodel1', 'Can change Mymodel1'), ('delete_mymodel1', 'Can delete Mymodel1')], [('add_mymodel2', 'Can add Mymodel2'), ('change_mymodel2', 'Can change Mymodel2'), ('delete_mymodel2', 'Can delete Mymodel2'), ('custom', 'Custom')]] mocker.patch('django_north.management.permissions._get_all_permissions', side_effect=perms) result = permissions.get_searched_permissions([(ct1, model1), (ct2, model2)]) assert result == [ (ct1, perms[0][0]), (ct1, perms[0][1]), (ct1, perms[0][2]), (ct2, perms[1][0]), (ct2, perms[1][1]), (ct2, perms[1][2]), (ct2, perms[1][3]), ]
def test_unknown_contenttypes(mocker): ct1 = ContentType(app_label='myapp1', model='mymodel1', id=1) ct2 = ContentType(app_label='myapp1', model='mymodel2', id=2) ct3 = ContentType(app_label='myapp2', model='mymodel3', id=3) app_config1 = CustomAppConfig('myapp1', mocker.Mock()) app_config2 = CustomAppConfig('myapp2', mocker.Mock()) app_config3 = CustomAppConfig('myapp3', mocker.Mock()) mocker.patch( 'django_north.management.commands.showfixtures.apps' '.get_app_configs', return_value=[app_config1, app_config2, app_config3]) mock_get_contenttypes = mocker.patch( 'django_north.management.contenttypes' '.get_unknown_contenttypes_for_app_config') command = showfixtures.Command() # unknown contenttypes mock_get_contenttypes.side_effect = [[ct1, ct2], [ct3], []] assert command.unknown_contenttypes() == [ "DELETE FROM django_content_type " "WHERE app_label = 'myapp1' AND model = 'mymodel1';", "DELETE FROM django_content_type " "WHERE app_label = 'myapp1' AND model = 'mymodel2';", "DELETE FROM django_content_type " "WHERE app_label = 'myapp2' AND model = 'mymodel3';", ] # no unknown contenttypes mock_get_contenttypes.side_effect = [[], [], []] assert command.unknown_contenttypes() == []
def mutate_and_get_payload(self, info, name, object_id, comment, targets): if not '.' in name: raise SngyException('Неправильное имя') app_label, model = name.lower().split('.') content_type = ContentType(app_label=app_label, model=model) content_object = content_type.get_object_for_this_type(id=object_id) Comment.objects.create(content_object=content_object, user=info.context.user, comment=comment) users_id = [u.id for u in User.objects.all()] if not targets: targets = list( set([ c.user_id for c in Comment.objects.filter( content_type__app_label=app_label, content_type__model=model, object_id=object_id) ])) if info.context.user.id in targets: targets.remove(info.context.user.id) for t in targets: if t in users_id: text = 'Комментарий: ' + comment Notification.objects.create(purpose_id=t, created=info.context.user, text=text) return CreateComments(result=True)
def register_content_type(apps, schema_editor): """Registers AlertSettings if not yet registered""" try: ContentType.objects.get(app_label='monitoring', model='alertsettings') except ObjectDoesNotExist: ct = ContentType(app_label='monitoring', model='alertsettings') ct.save()
def test_missing_contenttypes(mocker): ct1 = ContentType(app_label='myapp1', model='mymodel1') ct2 = ContentType(app_label='myapp1', model='mymodel2') ct3 = ContentType(app_label='myapp2', model='mymodel3') app_config1 = CustomAppConfig('myapp1', mocker.Mock()) app_config2 = CustomAppConfig('myapp2', mocker.Mock()) app_config3 = CustomAppConfig('myapp3', mocker.Mock()) mocker.patch( 'django_north.management.commands.showfixtures.apps' '.get_app_configs', return_value=[app_config1, app_config2, app_config3]) mock_get_contenttypes = mocker.patch( 'django_north.management.contenttypes' '.get_missing_contenttypes_for_app_config') command = showfixtures.Command() # missing contenttypes mock_get_contenttypes.side_effect = [[ct1, ct2], [ct3], []] assert command.missing_contenttypes() == [ "INSERT INTO django_content_type(app_label, model) " "VALUES('myapp1', 'mymodel1');", "INSERT INTO django_content_type(app_label, model) " "VALUES('myapp1', 'mymodel2');", "INSERT INTO django_content_type(app_label, model) " "VALUES('myapp2', 'mymodel3');" ] # no missing contenttypes mock_get_contenttypes.side_effect = [[], [], []] assert command.missing_contenttypes() == []
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')
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
def create_vote(self, vote): content_type = ContentType(app_label=self.app, model=self.model) content_object = content_type.get_object_for_this_type( id=self.instance.id) return Vote.objects.create(vote=vote, content_object=content_object, user_id=self.user_id)
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
def create_table(*models): """ Create all tables for the given models """ cursor = connection.cursor() def execute(statements): for statement in statements: cursor.execute(statement) STYLE = no_style() table_names = connection.introspection.get_table_list(cursor) for model in models: if not model._meta.db_table in table_names: execute(connection.creation.sql_create_model(model, STYLE)[0]) execute(connection.creation.sql_indexes_for_model(model, STYLE)) execute(sql.custom_sql_for_model(model, STYLE, connection)) for model in models: opts = model._meta try: ct = ContentType.objects.get(app_label=opts.app_label, model=opts.object_name.lower()) except ContentType.DoesNotExist: ct = ContentType(name=smart_unicode(opts.verbose_name_raw), app_label=opts.app_label, model=opts.object_name.lower()) ct.save()
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['accounts.User'])), ('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['accounts.User'])), ('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()
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()
def add_app_content_type(sender, **kwargs): for app in apps.get_app_configs(): appname = app.name try: ContentType.objects.get(model='', app_label=appname) except ContentType.DoesNotExist: ct = ContentType(model='', app_label=appname) ct.save()
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])
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'")
def create_content_type(model): opts = model._meta try: ct = ContentType.objects.get(app_label=opts.app_label, model=opts.object_name.lower()) except ContentType.DoesNotExist: ct = ContentType(app_label=opts.app_label, model=opts.object_name.lower()) ct.save()
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
def test_get_missing_permissions_for_app_config(mocker): ct1 = ContentType(app_label='myapp', model='mymodel1', id=1) ct2 = ContentType(app_label='myapp', model='mymodel2', id=2) model1 = mocker.Mock(_meta=mocker.Mock(model_name='mymodel1')) model2 = mocker.Mock(_meta=mocker.Mock(model_name='mymodel2')) app_config = CustomAppConfig('myapp', mocker.Mock()) mock_get_contenttypes = mocker.patch( 'django_north.management.permissions' '.get_all_contenttypes_for_app_config') mock_get_searched_perms = mocker.patch( 'django_north.management.permissions' '.get_searched_permissions') mock_get_all_perms = mocker.patch( 'django_north.management.permissions.get_all_permissions') # missing permissions mock_get_contenttypes.return_value = [(ct1, model1), (ct2, model2)] mock_get_searched_perms.return_value = [ (ct1, ('perm11', 'Perm11')), (ct1, ('perm12', 'Perm12')), (ct2, ('perm2', 'Perm2')), ] mock_get_all_perms.return_value = [ (1, 'perm11'), (2, 'perm2'), ] result = permissions.get_missing_permissions_for_app_config(app_config) assert len(result) == 1 new_perm = result[0] assert new_perm.codename == 'perm12' assert new_perm.name == 'Perm12' assert new_perm.content_type == ct1 # no existing contenttypes mock_get_contenttypes.return_value = [] mock_get_searched_perms.return_value = [ (ct1, ('perm11', 'Perm11')), (ct1, ('perm12', 'Perm12')), (ct2, ('perm2', 'Perm2')), ] mock_get_all_perms.return_value = [ (1, 'perm11'), (2, 'perm2'), ] result = permissions.get_missing_permissions_for_app_config(app_config) assert result == [] # no searched perms mock_get_contenttypes.return_value = [(ct1, model1), (ct2, model2)] mock_get_searched_perms.return_value = [] mock_get_all_perms.return_value = [ (1, 'perm11'), (2, 'perm2'), ] result = permissions.get_missing_permissions_for_app_config(app_config) assert result == []
def execute(self): app_label, model = self.model_name.lower().split('.') content_type = ContentType(app_label=app_label, model=model) content_object = content_type.get_object_for_this_type(id=self.instance_id) return Comment.objects.create( content_object=content_object, user_id=self.user_id, text=self.text, parent_id=self.parent_id )
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)
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'))
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
def setUp(self): self.permissions = SimplePermissions() self.request = Request() self.view = View() # Create a user user = User.objects.create_user(username='******', password='******') user.save() self.request.user = user # Create a content_type to test with self.content_type = ContentType(app_label='test_case', model='permissions') # noqa self.content_type.save()
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()
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......"
class Migration(migrations.Migration): dependencies = [ ('api', '0007_auto_20191013_1553'), ] try: con = ContentType.objects.get_by_natural_key(app_label='api', model='product') model = ContentType.model_class(con) db_table = model._meta.db_table operations = [ migrations.RunSQL( """ DROP TRIGGER IF EXISTS text_searchable_update ON api_product """, reverse_sql=migrations.RunSQL.noop, ), migrations.RunSQL( migrations.RunSQL.noop # заглушка # """ # CREATE TRIGGER text_searchable_update BEFORE INSERT OR UPDATE # ON api_product # FOR EACH ROW EXECUTE FUNCTION # tsvector_update_trigger(textsearchable_index_col, 'pg_catalog.english', description) # """ , reverse_sql=""" DROP TRIGGER IF EXISTS text_searchable_update ON api_product """, ) ] except ContentType.DoesNotExist: operations = []
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)
def get(self, ct: ContentType) -> FormFactory: # TODO: accept model directly ?? try: return self._form_factories[ct.model_class()] except KeyError as e: raise self.UnregisteredCTypeException( f'Unregistered ContentType: {ct}') from e
def increment_cc(instance, created=False, *args, **kwargs): if created: model = ContentType.model_class(instance.content_type) model.objects.filter(pk=instance.object).update( comments_count=F('comments_count') + 1) model.objects.filter(pk=instance.object).update( comments_count=F('comments_count') - 1)
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()
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
def action(): """Add a test action. """ action = Action( action="test action", question_text="test question", co2_formula="0.8 * test_parameter * 0.5", water_formula="0.8 * test_parameter * 0.5", waste_formula="0.8 * test_parameter * 0.5", version="version 1.0", content_type=ContentType(id=1), object_id=1, ) def _action(real_data): """Updates test action with realistic data if needed. """ if real_data: action.co2_formula = "0.8 * vegetarian_meals * 0.5" action.water_formula = "0.4 * current_meals" action.waste_formula = "0.9 * current_meals * vegetarian_meals" action.content_type = ContentType( id=3, app_label="pledges | food pledge", model=FoodPledge) action.save() return action return _action
class Like(models.Model): user = models.ForeignKey(get_user_model(), related_name='likes', on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = ContentType('content_type', 'object_id')
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')
def get(self, *args, **kwargs): # Special case for Django >= 1.11 which sometimes generates Q() objects # with a single filter when querying content types. This handles that one # case.. if we find there are others we'll have to do something less hacky! if args and not kwargs: if len(args) == 1 and len( args[0].children) == 1 and not args[0].negated: kwargs = dict(args[0].children) else: raise ValueError("Unsupported Q operation") ContentType = self._get_model() 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: ContentType = self._get_model() result = ContentType(**dic) result.save = new.instancemethod(disable_save, ContentType, result) self._store.constructed_instances[dic["id"]] = result return result
def get_descr(self): cache_key = self.get_descr_cache_key() descr = cache.get(cache_key) if not descr: descr = ContentType.get_object_for_this_type( self.content_type, id=self.object_id).get_descr() cache.set(cache_key, descr, 5) return descr
def get_validation_errors(self, token_value): model_class = ContentType.model_class(self.lookup_type) lookup = { str(self.field_name + "__iexact") : token_value.data } try: val = model_class.objects.get(**lookup) return None except model_class.DoesNotExist: return "%s not in list of %s %ss" % (token_value.data, self.lookup_type.name, self.field_name)
def get(self, *args, **kwargs): # Special case for Django >= 1.11 which sometimes generates Q() objects # with a single filter when querying content types. This handles that one # case.. if we find there are others we'll have to do something less hacky! if args and not kwargs: if len(args) == 1 and len(args[0].children) == 1 and not args[0].negated: kwargs = dict(args[0].children) else: raise ValueError("Unsupported Q operation") ContentType = self._get_model() 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: ContentType = self._get_model() result = ContentType(**dic) result.save = new.instancemethod(disable_save, ContentType, result) self._store.constructed_instances[dic["id"]] = result return result
def clean(self): su = super(ObjectsFormAdmin, self).clean() # TODO это просто бомба же for name in self.foreign_keys: if self.md_fields.get(name).to.model_class( ) in self.foreign_keys_models_with_magic: su[name] = ContentType(id=su[name].pk) return su
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)
def test_get_queryset_invalid_content_type_raises_404(self): # Arrange view = self.setUpView( content_type=ContentType(pk=1000000, app_label="Test", model="Test") ) # Act & Assert with self.assertRaises(Http404): view.get_queryset()
def gen_content_type(): from django.contrib.contenttypes.models import ContentType from django.apps import apps try: return ContentType.objects.get_for_model(choice(apps.get_models())) except AssertionError: warnings.warn('Database access disabled, returning ContentType raw instance') return ContentType()
def get_generickey_json(request): id = request.GET.get('id', None) if not id: raise Http404("id GET parameter") model_type = ContentType.objects.get_for_id(id) data = ContentType.get_all_objects_for_this_type(model_type) json = serializers.serialize('json', data) return HttpResponse(json, content_type='application/json')
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): try: content_type1 = ContentType.objects.get(app_label="frontend", model="Article", name="文章板块权限") except: content_type1 = ContentType(app_label="frontend", model="Article", name="文章板块权限") content_type1.save() try: content_type2 = ContentType.objects.get(app_label="frontend", model="Slider", name="幻灯片推送权限") except: content_type2 = ContentType(app_label="frontend", model="Slider", name="幻灯片推送权限") content_type2.save() try: content_type3 = ContentType.objects.get(app_label="frontend", model="Activity", name="活动发布权限") except: content_type3 = ContentType(app_label="frontend", model="Activity", name="活动发布权限") content_type3.save() translate = {"add": "添加", "delete": "删除", "change": "修改"} for permission in ["add", "delete", "change"]: try: codename = permission + "_" + self.codename + "_articles" Permission.objects.get(codename=codename) except: name = "允许" + translate[permission] + " " + self.name + " 内的文章" codename = permission + "_" + self.codename + "_articles" p = Permission(name=name, content_type=content_type1, codename=codename) p.save() try: codename = permission + "_" + self.codename + "_sliders" Permission.objects.get(codename=codename) except: name = "允许" + translate[permission] + " " + self.name + " 内的幻灯片" codename = permission + "_" + self.codename + "_sliders" p = Permission(name=name, content_type=content_type2, codename=codename) p.save() try: codename = permission + "_" + self.codename + "_activities" Permission.objects.get(codename=codename) except: name = "允许" + translate[permission] + " " + self.name + " 内的活动" codename = permission + "_" + self.codename + "_activities" p = Permission(name=name, content_type=content_type3, codename=codename) p.save() if self.order == None: self.order = self.id result = super(SecondaryMenu, self).save() return result
def setUp(self): person = Person() User.objects.create(username="******", password="******") person.user = User.objects.get(username="******") 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.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()
def get_absolute_url(self): """ link to dorsale’s generic `show_item` view """ mo = ContentType.model_class(self) return ('dorsale.views.show_item', (), { 'app_name' : mo.app_label, 'model_name': mo.model, 'object_id' : self.id, })
def get_mooclet_context(mooclet): # content_type for model that the mooclet is attached to parent_content_type = mooclet.type.content_type # parent object instance parent_content = ContentType.get_object_for_this_type(parent_content_type, pk=parent_content_id) if parent_content_type.name == 'question': question = parent_content elif parent_content_type.name == 'answer': answer = parent_content question = answer.question
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
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)
def mooclet_detail(request, **kwargs): ''' mooclet home page required kwargs: quiz, mooclet, and all parent objects ''' quiz = get_object_or_404(Quiz,pk=kwargs['quiz_id']) mooclet = get_object_or_404(Mooclet,pk=kwargs['mooclet_id']) # look up mooclet type and identify associated parent object # object class that the mooclet is attached to parent_content_type = mooclet.type.parent_content_type parent_content = ContentType.get_object_for_this_type(parent_content_type, pk=kwargs[parent_content_type.name+'_id']) # populate a mooclet context dict mooclet_context = {} if parent_content_type.name == 'question': mooclet_context['question'] = parent_content if parent_content_type.name == 'answer': mooclet_context['answer'] = parent_content mooclet_context['question'] = parent_content.question versions = mooclet.version_set.all() version_content_type = ContentType.objects.get_for_model(Version) mooclet_policy_form = MoocletPolicyForm(instance=mooclet) # page used to display variables that are version-specific if request.method == 'GET': context = { 'quiz':quiz, 'mooclet':mooclet, 'versions':versions, 'mooclet_policy_form':mooclet_policy_form, } # pass additional context variables for navigation context.update(mooclet_context) 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_detail.html',context) elif request.method == 'POST': # process mooclet policy form for adjusting policy mooclet_policy_form = MoocletPolicyForm(request.POST, instance=mooclet) mooclet = mooclet_policy_form.save() # converts dict of objs to dict of pks mooclet_context_pk = {name+'_id':obj.pk for name,obj in mooclet_context.items()} return redirect('engine:mooclet_detail', quiz_id=quiz.pk, mooclet_id=mooclet.pk, **mooclet_context_pk)
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()
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): try: content_type = ContentType.objects.get(app_label="frontend", model="Article", name="文章板块权限") except: content_type = ContentType(app_label="frontend", model="Article", name="文章板块权限") content_type.save() translate = {"add": "添加", "delete": "删除", "change": "修改"} for permission in ["add", "delete", "change"]: try: codename = permission + "_" + self.codename + "_articles" Permission.objects.get(codename=codename) except: name = "允许" + translate[permission] + " " + self.name + " 内的文章" codename = permission + "_" + self.codename + "_articles" p = Permission(name=name, content_type=content_type, codename=codename) p.save() if self.order == None: self.order = self.id result = super(MainMenu, self).save() return result
def install(sender, created_models, **kwargs): for model in get_models(): # TODO change to django.apps if getattr(model, 'BMFMeta', False): kwargs = { 'app_label': model._meta.app_label, 'model': model._meta.model_name, } # LOOK: maybe we could move this to a signal try: ct = ContentType.objects.get(**kwargs) except ContentType.DoesNotExist: ct = ContentType(**kwargs) ct.name = model._meta.verbose_name_raw ct.save() if model._bmfmeta.number_cycle: count = NumberCycle.objects.filter(ct=ct).count() if not count: obj = NumberCycle(ct=ct, name_template=model._bmfmeta.number_cycle) obj.save() return None