def create(self, validated_data): resource_type = validated_data.get('resource_type', '') resource_id = validated_data.get('resource_id', '') resource = Pin.get_resource(resource_type, resource_id) item = Pin( user_id=validated_data.get('user_id', None), organization_id=validated_data.get('organization_id', None), resource=resource, ) if not resource: self._errors[ 'resource'] = 'Resource type %s with id %s does not exists.' % ( resource_type, resource_id) return item try: item.full_clean() item.save() except (ValidationError, IntegrityError): self._errors.update(dict(__all__='This pin already exists.')) return item
def test_get_resource(self): org = OrganizationFactory() source = OrganizationSourceFactory(organization=org) collection = OrganizationCollectionFactory(organization=org) self.assertEqual( Pin.get_resource(resource_type='Source', resource_id=source.id), source) self.assertEqual( Pin.get_resource(resource_type='collection', resource_id=collection.id), collection) self.assertEqual( Pin.get_resource(resource_type='org', resource_id=org.id), org) self.assertEqual( Pin.get_resource(resource_type='organization', resource_id=org.id), org) self.assertEqual( Pin.get_resource(resource_type='organization', resource_id=123), None) self.assertEqual( Pin.get_resource(resource_type='foobar', resource_id=123), None)