Back to index

plone3  3.1.7
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Static Private Attributes
Archetypes.Field.ImageField Class Reference
Inheritance diagram for Archetypes.Field.ImageField:
Inheritance graph
[legend]
Collaboration diagram for Archetypes.Field.ImageField:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def set
def getAvailableSizes
def rescaleOriginal
def createOriginal
def removeScales
def createScales
def scale
def getSize
def getScale
def getScaleName
def get_size
def tag
def setContentType
def getContentType
def get
def getBaseUnit
def getFilename
def setFilename
def validate_required
def download
def getIndexAccessor
def getIndexable
def getRaw
def unset
def setStorage
def getStorage
def getStorageName
def getStorageType
def copy
def __repr__
def validate
def validate_validators
def validate_vocabulary
def Vocabulary
def checkPermission
def writeable
def checkExternalEditor
def getWidgetName
def getName
def getType
def getDefault
def getAccessor
def getEditAccessor
def getMutator
def getIndexAccessorName
def toString
def isLanguageIndependent
def getI18nDomain

Public Attributes

 storage
 widget
 validators
 index_method

Static Public Attributes

tuple security = ClassSecurityInfo()
string default_view = "view"

Private Member Functions

def _make_image

Static Private Attributes

tuple _properties = FileField._properties.copy()

Detailed Description

implements an image attribute. it stores
    it's data in an image sub-object

    sizes is an dictionary containing the sizes to
    scale the image to. PIL is required for that.

    Format:
    sizes={'mini': (50,50),
           'normal' : (100,100), ... }
    syntax: {'name': (width,height), ... }

    the scaled versions can then be accessed as
    object/<imagename>_<scalename>

    e.g. object/image_mini

    where <imagename> is the fieldname and <scalename>
    is the name from the dictionary

    original_size -- this parameter gives the size in (w,h)
    to which the original image will be scaled. If it's None,
    then no scaling will take place.
    This is important if you don't want to store megabytes of
    imagedata if you only need a max. of 100x100 ;-)

    max_size -- similar to max_size but if it's given then the image
                is checked to be no bigger than any of the given values
                of width or height.

    example:

    ImageField('image',
        original_size=(600,600),
        sizes={ 'mini' : (80,80),
                'normal' : (200,200),
                'big' : (300,300),
                'maxi' : (500,500)})

    will create an attribute called "image"
    with the sizes mini, normal, big, maxi as given
    and a original sized image of max 600x600.
    This will be accessible as
    object/image

    and the sizes as

    object/image_mini
    object/image_normal
    object/image_big
    object/image_maxi

    the official API to get tag (in a pagetemplate) is
    obj.getField('image').tag(obj, scale='mini')
    ...

    sizes may be the name of a method in the instance or a callable which
    returns a dict.
    
    Don't remove scales once they exist! Instead of removing a scale
    from the list of sizes you should set the size to (0,0). Thus
    removeScales method is able to find the scales to delete the
    data.

    Scaling will only be available if PIL is installed!

    If 'DELETE_IMAGE' will be given as value, then all the images
    will be deleted (None is understood as no-op)

Definition at line 2082 of file Field.py.


Member Function Documentation

def Archetypes.Field.Field.__repr__ (   self) [inherited]
Return a string representation consisting of name, type and permissions.

Definition at line 236 of file Field.py.

00236 
00237     def __repr__(self):
00238         """
00239         Return a string representation consisting of name, type and permissions.
00240         """
00241         return "<Field %s(%s:%s)>" % (self.getName(), self.type, self.mode)

Here is the call graph for this function:

def Archetypes.Field.ImageField._make_image (   self,
  id,
  title = '',
  file = '',
  content_type = '',
  instance = None 
) [private]
Image content factory

Definition at line 2359 of file Field.py.

02359 
02360     def _make_image(self, id, title='', file='', content_type='', instance=None):
02361         """Image content factory"""
02362         return self.content_class(id, title, file, content_type)

Here is the caller graph for this function:

def Archetypes.Field.Field.checkExternalEditor (   self,
  instance 
) [inherited]
Checks if the user may edit this field and if
external editor is enabled on this instance 

Definition at line 550 of file Field.py.

00550 
00551     def checkExternalEditor(self, instance):
00552         """ Checks if the user may edit this field and if
00553         external editor is enabled on this instance """
00554 
00555         pp = getToolByName(instance, 'portal_properties')
00556         sp = getattr(pp, 'site_properties', None)
00557         if sp is not None:
00558             if getattr(sp, 'ext_editor', None) \
00559                    and self.checkPermission(mode='edit', instance=instance):
00560                 return True
00561         return None

Here is the call graph for this function:

def Archetypes.Field.Field.checkPermission (   self,
  mode,
  instance 
) [inherited]
Check whether the security context allows the given permission on
the given object.

Arguments:

mode -- 'w' for write or 'r' for read
instance -- The object being accessed according to the permission

Definition at line 507 of file Field.py.

00507 
00508     def checkPermission(self, mode, instance):
00509         """
00510         Check whether the security context allows the given permission on
00511         the given object.
00512 
00513         Arguments:
00514 
00515         mode -- 'w' for write or 'r' for read
00516         instance -- The object being accessed according to the permission
00517         """
00518         if mode in ('w', 'write', 'edit', 'set'):
00519             perm = self.write_permission
00520         elif mode in ('r', 'read', 'view', 'get'):
00521             perm = self.read_permission
00522         else:
00523             return None
00524         return getSecurityManager().checkPermission( perm, instance )
00525 

Here is the caller graph for this function:

def Archetypes.Field.Field.copy (   self,
  name = None 
) [inherited]
Return a copy of field instance, consisting of field name and
properties dictionary. field name can be changed to given name.

Definition at line 220 of file Field.py.

00220 
00221     def copy(self, name=None):
00222         """
00223         Return a copy of field instance, consisting of field name and
00224         properties dictionary. field name can be changed to given name.
00225         """
00226         cdict = dict(vars(self))
00227         cdict.pop('__name__')
00228         # Widget must be copied separatedly
00229         widget = cdict['widget']
00230         del cdict['widget']
00231         properties = deepcopy(cdict)
00232         properties['widget'] = widget.copy()
00233         name = name is not None and name or self.getName()
00234         return self.__class__(name, **properties)
00235 
    

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.createOriginal (   self,
  instance,
  value,
  kwargs 
)
create the original image (save it)

Definition at line 2275 of file Field.py.

02275 
02276     def createOriginal(self, instance, value, **kwargs):
02277         """create the original image (save it)
02278         """
02279         if value:
02280             image = self._wrapValue(instance, value, **kwargs)
02281         else:
02282             image = self.getDefault(instance)
02283 
02284         ObjectField.set(self, instance, image, **kwargs)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.createScales (   self,
  instance,
  value = _marker 
)
creates the scales and save them

Definition at line 2305 of file Field.py.

02305 
02306     def createScales(self, instance, value=_marker):
02307         """creates the scales and save them
02308         """
02309         sizes = self.getAvailableSizes(instance)
02310         if not HAS_PIL or not sizes:
02311             return
02312         # get data from the original size if value is None
02313         if value is _marker:
02314             img = self.getRaw(instance)
02315             if not img:
02316                 return
02317             data = str(img.data)
02318         else:
02319             data = value
02320 
02321         # empty string - stop rescaling because PIL fails on an empty string
02322         if not data:
02323             return
02324 
02325         filename = self.getFilename(instance)
02326 
02327         for n, size in sizes.items():
02328             if size == (0,0):
02329                 continue
02330             w, h = size
02331             id = self.getName() + "_" + n
02332             __traceback_info__ = (self, instance, id, w, h)
02333             try:
02334                 imgdata, format = self.scale(data, w, h)
02335             except (ConflictError, KeyboardInterrupt):
02336                 raise
02337             except:
02338                 if not self.swallowResizeExceptions:
02339                     raise
02340                 else:
02341                     log_exc()
02342                     # scaling failed, don't create a scaled version
02343                     continue
02344 
02345             mimetype = 'image/%s' % format.lower()
02346             image = self._make_image(id, title=self.getName(), file=imgdata,
02347                                      content_type=mimetype, instance=instance)
02348             # nice filename: filename_sizename.ext
02349             #fname = "%s_%s%s" % (filename, n, ext)
02350             #image.filename = fname
02351             image.filename = filename
02352             try:
02353                 delattr(image, 'title')
02354             except (KeyError, AttributeError):
02355                 pass
02356             # manually use storage
02357             self.getStorage(instance).set(id, instance, image,
02358                                           mimetype=mimetype, filename=filename)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.FileField.download (   self,
  instance,
  REQUEST = None,
  RESPONSE = None,
  no_output = False 
) [inherited]
Kicks download.

Writes data including file name and content type to RESPONSE

Definition at line 1138 of file Field.py.

01138 
01139     def download(self, instance, REQUEST=None, RESPONSE=None, no_output=False):
01140         """Kicks download.
01141 
01142         Writes data including file name and content type to RESPONSE
01143         """
01144         file = self.get(instance, raw=True)
01145         if not REQUEST:
01146             REQUEST = aq_get(instance, 'REQUEST')
01147         if not RESPONSE:
01148             RESPONSE = REQUEST.RESPONSE
01149         filename = self.getFilename(instance)
01150         if filename is not None:
01151             if FILE_NORMALIZER:
01152                 filename = IUserPreferredFileNameNormalizer(REQUEST).normalize(
01153                     unicode(filename, instance.getCharset()))
01154             else:
01155                 filename = unicode(filename, instance.getCharset())
01156             header_value = contentDispositionHeader(
01157                 disposition='attachment',
01158                 filename=filename)
01159             RESPONSE.setHeader("Content-Disposition", header_value)
01160         if no_output:
01161             return file
01162         return file.index_html(REQUEST, RESPONSE)

Here is the call graph for this function:

def Archetypes.Field.FileField.get (   self,
  instance,
  kwargs 
) [inherited]

Reimplemented from Archetypes.Field.ObjectField.

Definition at line 993 of file Field.py.

00993 
00994     def get(self, instance, **kwargs):
00995         value = ObjectField.get(self, instance, **kwargs)
00996         if value and not isinstance(value, self.content_class):
00997             value = self._wrapValue(instance, value)
00998         if (shasattr(value, '__of__', acquire=True)
00999             and not kwargs.get('unwrapped', False)):
01000             return value.__of__(instance)
01001         else:
01002             return value

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.get_size (   self,
  instance 
)
Get size of the stored data used for get_size in BaseObject

TODO: We should only return the size of the original image

Reimplemented from Archetypes.Field.FileField.

Definition at line 2433 of file Field.py.

02433 
02434     def get_size(self, instance):
02435         """Get size of the stored data used for get_size in BaseObject
02436         
02437         TODO: We should only return the size of the original image
02438         """
02439         sizes = self.getAvailableSizes(instance)
02440         original = self.get(instance)
02441         size = original and original.get_size() or 0
02442 
02443         if sizes:
02444             for name in sizes.keys():
02445                 id = self.getScaleName(scale=name)
02446                 try:
02447                     data = self.getStorage(instance).get(id, instance)
02448                 except AttributeError:
02449                     pass
02450                 else:
02451                     size+=data and data.get_size() or 0
02452         return size

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.getAccessor (   self,
  instance 
) [inherited]
Return the accessor method for getting data out of this
field

Definition at line 602 of file Field.py.

00602 
00603     def getAccessor(self, instance):
00604         """Return the accessor method for getting data out of this
00605         field"""
00606         if self.accessor:
00607             return getattr(instance, self.accessor, None)
00608         return None

Here is the caller graph for this function:

def Archetypes.Field.ImageField.getAvailableSizes (   self,
  instance 
)
Get sizes

Supports:
    self.sizes as dict
    A method in instance called like sizes that returns dict
    A callable

Definition at line 2214 of file Field.py.

02214 
02215     def getAvailableSizes(self, instance):
02216         """Get sizes
02217 
02218         Supports:
02219             self.sizes as dict
02220             A method in instance called like sizes that returns dict
02221             A callable
02222         """
02223         sizes = self.sizes
02224         if isinstance(sizes, dict):
02225             return sizes
02226         elif isinstance(sizes, basestring):
02227             assert(shasattr(instance, sizes))
02228             method = getattr(instance, sizes)
02229             data = method()
02230             assert(isinstance(data, dict))
02231             return data
02232         elif callable(sizes):
02233             return sizes()
02234         elif sizes is None:
02235             return {}
02236         else:
02237             raise TypeError, 'Wrong self.sizes has wrong type: %s' % type(sizes)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.FileField.getBaseUnit (   self,
  instance,
  full = False 
) [inherited]
Return the value of the field wrapped in a base unit object

Reimplemented in Archetypes.Field.TextField.

Definition at line 1081 of file Field.py.

01081 
01082     def getBaseUnit(self, instance, full=False):
01083         """Return the value of the field wrapped in a base unit object
01084         """
01085         filename = self.getFilename(instance, fromBaseUnit=False)
01086         if not filename:
01087             filename = '' # self.getName()
01088         mimetype = self.getContentType(instance, fromBaseUnit=False)
01089         value = self.getRaw(instance) or self.getDefault(instance)
01090         if isinstance(aq_base(value), File):
01091             value = value.data
01092             if full:
01093                 # This will read the whole file in memory, which is
01094                 # very expensive specially with big files over
01095                 # ZEO. With small files is not that much of an issue.
01096                 value = str(value)
01097             elif not isinstance(value, basestring):
01098                 # It's a Pdata object, get only the first chunk, which
01099                 # should be good enough for detecting the mimetype
01100                 value = value.data
01101         bu = BaseUnit(filename, aq_base(value), instance,
01102                       filename=filename, mimetype=mimetype)
01103         return bu

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.FileField.getContentType (   self,
  instance,
  fromBaseUnit = True 
) [inherited]
Return the mime type of object if known or can be guessed;
otherwise, return default_content_type value or fallback to
'application/octet-stream'.

Reimplemented from Archetypes.Field.ObjectField.

Definition at line 884 of file Field.py.

00884 
00885     def getContentType(self, instance, fromBaseUnit=True):
00886         file = self.get(instance)
00887         return getattr(file, 'content_type', self.default_content_type)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.getDefault (   self,
  instance 
) [inherited]
Return the default value to be used for initializing this
field

Definition at line 579 of file Field.py.

00579 
00580     def getDefault(self, instance):
00581         """Return the default value to be used for initializing this
00582         field"""
00583         dm = self.default_method
00584         if dm:
00585             if isinstance(dm, basestring) and shasattr(instance, dm):
00586                 method = getattr(instance, dm)
00587                 return method()
00588             elif callable(dm):
00589                 return dm()
00590             else:
00591                 raise ValueError('%s.default_method is neither a method of %s'
00592                                  ' nor a callable' % (self.getName(),
00593                                                       instance.__class__))
00594         
00595         if not self.default:
00596             default_adapter = component.queryAdapter(instance, IFieldDefaultProvider, name=self.__name__)
00597             if default_adapter is not None:
00598                 return default_adapter()
00599                 
00600         return self.default

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.getEditAccessor (   self,
  instance 
) [inherited]
Return the accessor method for getting raw data out of this
field e.g.: for editing

Definition at line 610 of file Field.py.

00610 
00611     def getEditAccessor(self, instance):
00612         """Return the accessor method for getting raw data out of this
00613         field e.g.: for editing
00614         """
00615         if self.edit_accessor:
00616             return getattr(instance, self.edit_accessor, None)
00617         return None

def Archetypes.Field.FileField.getFilename (   self,
  instance,
  fromBaseUnit = True 
) [inherited]
Get file name of underlaying file object

Definition at line 1105 of file Field.py.

01105 
01106     def getFilename(self, instance, fromBaseUnit=True):
01107         """Get file name of underlaying file object
01108         """
01109         filename = None
01110         if fromBaseUnit:
01111             bu = self.getBaseUnit(instance)
01112             return bu.getFilename()
01113         raw = self.getRaw(instance)
01114         filename = getattr(aq_base(raw), 'filename', None)
01115         # for OFS.Image.*
01116         if filename is None:
01117             filename = getattr(raw, 'filename', None)
01118         # might still be None
01119         if filename:
01120             # taking care of stupid IE and be backward compatible
01121             # BaseUnit hasn't have a fix for long so we might have an old name
01122             filename = filename.split("\\")[-1]
01123         return filename

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.getI18nDomain (   self) [inherited]
returns the internationalization domain for translation 

Definition at line 678 of file Field.py.

00678 
00679     def getI18nDomain(self):
00680         """ returns the internationalization domain for translation """
00681         pass
00682 
00683 #InitializeClass(Field)
00684 setSecurity(Field)

def Archetypes.Field.FileField.getIndexable (   self,
  instance 
) [inherited]

Definition at line 1182 of file Field.py.

01182 
01183     def getIndexable(self, instance):
01184         # XXX Naive implementation that loads all data contents into
01185         # memory.  To have this not happening set your field to not
01186         # 'searchable' (the default) or define your own 'index_method'
01187         # property.
01188         orig_mt = self.getContentType(instance)
01189 
01190         # If there's no path to text/plain, don't do anything
01191         transforms = getToolByName(instance, 'portal_transforms')
01192         if transforms._findPath(orig_mt, 'text/plain') is None:
01193             return ''
01194 
01195         f = self.get(instance)
01196 
01197         datastream = ''
01198         try:
01199             datastream = transforms.convertTo(
01200                 "text/plain",
01201                 str(f),
01202                 mimetype = orig_mt,
01203                 filename = self.getFilename(instance, 0),
01204                 )
01205         except (ConflictError, KeyboardInterrupt):
01206             raise
01207         except Exception, e:
01208             log("Error while trying to convert file contents to 'text/plain' "
01209                 "in %r.getIndexable() of %r: %s" % (self, instance, e))
01210 
01211         value = str(datastream)
01212         return value

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.FileField.getIndexAccessor (   self,
  instance 
) [inherited]
Return the index accessor, i.e. the getter for an indexable
value.

Reimplemented from Archetypes.Field.Field.

Definition at line 1174 of file Field.py.

01174 
01175     def getIndexAccessor(self, instance):
01176         name = self.getIndexAccessorName()
01177         if name in (self.edit_accessor, self.accessor):
01178             return lambda: self.getIndexable(instance)
01179         else:
01180             return ObjectField.getIndexAccessor(self, instance)

Here is the call graph for this function:

def Archetypes.Field.Field.getIndexAccessorName (   self) [inherited]
Return the index accessor's name defined by the
'index_method' field property.

Definition at line 633 of file Field.py.

00633 
00634     def getIndexAccessorName(self):
00635         """Return the index accessor's name defined by the
00636         'index_method' field property."""
00637         if not hasattr(self, 'index_method'):
00638             return self.accessor
00639         elif self.index_method == '_at_accessor':
00640             return self.accessor
00641         elif self.index_method == '_at_edit_accessor':
00642             return self.edit_accessor or self.accessor
00643 
00644         # If index_method is not a string, we raise ValueError (this
00645         # is actually tested for in test_extensions_utils):
00646         elif not isinstance(self.index_method, (str, unicode)):
00647             raise ValueError("Bad index accessor value : %r"
00648                              % self.index_method)
00649         else:
00650             return self.index_method

Here is the caller graph for this function:

def Archetypes.Field.Field.getMutator (   self,
  instance 
) [inherited]
Return the mutator method used for changing the value
of this field

Definition at line 619 of file Field.py.

00619 
00620     def getMutator(self, instance):
00621         """Return the mutator method used for changing the value
00622         of this field"""
00623         if self.mutator:
00624             return getattr(instance, self.mutator, None)
00625         return None

Here is the caller graph for this function:

def Archetypes.Field.Field.getName (   self) [inherited]
Return the name of this field as a string

Definition at line 569 of file Field.py.

00569 
00570     def getName(self):
00571         """Return the name of this field as a string"""
00572         return self.__name__

def Archetypes.Field.ObjectField.getRaw (   self,
  instance,
  kwargs 
) [inherited]

Reimplemented in Archetypes.Field.BooleanField, and Archetypes.Field.LinesField.

Definition at line 716 of file Field.py.

00716 
00717     def getRaw(self, instance, **kwargs):
00718         if self.accessor is not None:
00719             accessor = self.getAccessor(instance)
00720         else:
00721             # self.accessor is None for fields wrapped by an I18NMixIn
00722             accessor = None
00723         kwargs.update({'field': self,
00724                        'encoding':kwargs.get('encoding', None),
00725                      })
00726         if accessor is None:
00727             args = [instance,]
00728             return mapply(self.get, *args, **kwargs)
00729         return mapply(accessor, **kwargs)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.getScale (   self,
  instance,
  scale = None,
  kwargs 
)
Get scale by name or original

Definition at line 2404 of file Field.py.

02404 
02405     def getScale(self, instance, scale=None, **kwargs):
02406         """Get scale by name or original
02407         """
02408         if scale is None:
02409             return self.get(instance, **kwargs)
02410         else:
02411             assert(scale in self.getAvailableSizes(instance).keys(),
02412                    'Unknown scale %s for %s' % (scale, self.getName()))
02413             id = self.getScaleName(scale=scale)
02414             try:
02415                 image = self.getStorage(instance).get(id, instance, **kwargs)
02416             except AttributeError:
02417                 return ''
02418             image = self._wrapValue(instance, image, **kwargs)
02419             if shasattr(image, '__of__', acquire=True) and not kwargs.get('unwrapped', False):
02420                 return image.__of__(instance)
02421             else:
02422                 return image

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.getScaleName (   self,
  scale = None 
)
Get the full name of the attribute for the scale

Definition at line 2424 of file Field.py.

02424 
02425     def getScaleName(self, scale=None):
02426         """Get the full name of the attribute for the scale
02427         """
02428         if scale:
02429             return self.getName() + "_" + scale
02430         else:
02431             return ''

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.getSize (   self,
  instance,
  scale = None 
)
get size of scale or original

Definition at line 2395 of file Field.py.

02395 
02396     def getSize(self, instance, scale=None):
02397         """get size of scale or original
02398         """
02399         img = self.getScale(instance, scale=scale)
02400         if not img:
02401             return 0, 0
02402         return img.width, img.height

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ObjectField.getStorage (   self,
  instance = None 
) [inherited]

Definition at line 758 of file Field.py.

00758 
00759     def getStorage(self, instance=None):
00760         return self.storage

Here is the caller graph for this function:

def Archetypes.Field.ObjectField.getStorageName (   self,
  instance = None 
) [inherited]
Return the storage name that is configured for this field
as a string

Definition at line 762 of file Field.py.

00762 
00763     def getStorageName(self, instance=None):
00764         """Return the storage name that is configured for this field
00765         as a string"""
00766         return self.getStorage(instance).getName()

Here is the call graph for this function:

def Archetypes.Field.ObjectField.getStorageType (   self,
  instance = None 
) [inherited]
Return the type of the storage of this field as a string

Definition at line 768 of file Field.py.

00768 
00769     def getStorageType(self, instance=None):
00770         """Return the type of the storage of this field as a string"""
00771         return className(self.getStorage(instance))

Here is the call graph for this function:

def Archetypes.Field.Field.getType (   self) [inherited]
Return the type of this field as a string

Definition at line 574 of file Field.py.

00574 
00575     def getType(self):
00576         """Return the type of this field as a string"""
00577         return className(self)

Here is the call graph for this function:

def Archetypes.Field.Field.getWidgetName (   self) [inherited]
Return the widget name that is configured for this field as
a string

Definition at line 563 of file Field.py.

00563 
00564     def getWidgetName(self):
00565         """Return the widget name that is configured for this field as
00566         a string"""
00567         return self.widget.getName()

def Archetypes.Field.Field.isLanguageIndependent (   self,
  instance 
) [inherited]
Get the language independed flag for i18n content

Definition at line 672 of file Field.py.

00672 
00673     def isLanguageIndependent(self, instance):
00674         """Get the language independed flag for i18n content
00675         """
00676         return self.languageIndependent

def Archetypes.Field.ImageField.removeScales (   self,
  instance,
  kwargs 
)
Remove the scaled image

Definition at line 2286 of file Field.py.

02286 
02287     def removeScales(self, instance, **kwargs):
02288         """Remove the scaled image
02289         """
02290         sizes = self.getAvailableSizes(instance)
02291         if sizes:
02292             for name, size in sizes.items():
02293                 id = self.getName() + "_" + name
02294                 try:
02295                     # the following line may throw exceptions on types, if the
02296                     # type-developer add sizes to a field in an existing
02297                     # instance and a user try to remove an image uploaded before
02298                     # that changed. The problem is, that the behavior for non
02299                     # existent keys isn't defined. I assume a keyerror will be
02300                     # thrown. Ignore that.
02301                     self.getStorage(instance).unset(id, instance, **kwargs)
02302                 except KeyError:
02303                     pass

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.rescaleOriginal (   self,
  value,
  kwargs 
)
rescales the original image and sets the data

for self.original_size or self.max_size

value must be an OFS.Image.Image instance

Definition at line 2239 of file Field.py.

02239 
02240     def rescaleOriginal(self, value, **kwargs):
02241         """rescales the original image and sets the data
02242 
02243         for self.original_size or self.max_size
02244         
02245         value must be an OFS.Image.Image instance
02246         """
02247         data = str(value.data)
02248         if not HAS_PIL:
02249             return data
02250         
02251         mimetype = kwargs.get('mimetype', self.default_content_type)
02252         
02253         if self.original_size or self.max_size:
02254             if not value:
02255                 return self.default
02256             w=h=0
02257             if self.max_size:
02258                 if value.width > self.max_size[0] or \
02259                        value.height > self.max_size[1]:
02260                     factor = min(float(self.max_size[0])/float(value.width),
02261                                  float(self.max_size[1])/float(value.height))
02262                     w = int(factor*value.width)
02263                     h = int(factor*value.height)
02264             elif self.original_size:
02265                 w,h = self.original_size
02266             if w and h:
02267                 __traceback_info__ = (self, value, w, h)
02268                 fvalue, format = self.scale(data, w, h)
02269                 data = fvalue.read()
02270         else:
02271             data = str(value.data)
02272             
02273         return data

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.ImageField.scale (   self,
  data,
  w,
  h,
  default_format = 'PNG' 
)
scale image (with material from ImageTag_Hotfix)

Definition at line 2364 of file Field.py.

02364 
02365     def scale(self, data, w, h, default_format = 'PNG'):
02366         """ scale image (with material from ImageTag_Hotfix)"""
02367         #make sure we have valid int's
02368         size = int(w), int(h)
02369 
02370         original_file=StringIO(data)
02371         image = PIL.Image.open(original_file)
02372         # consider image mode when scaling
02373         # source images can be mode '1','L,','P','RGB(A)'
02374         # convert to greyscale or RGBA before scaling
02375         # preserve palletted mode (but not pallette)
02376         # for palletted-only image formats, e.g. GIF
02377         # PNG compression is OK for RGBA thumbnails
02378         original_mode = image.mode
02379         if original_mode == '1':
02380             image = image.convert('L')
02381         elif original_mode == 'P':
02382             image = image.convert('RGBA')
02383         image.thumbnail(size, self.pil_resize_algo)
02384         format = image.format and image.format or default_format
02385         # decided to only preserve palletted mode
02386         # for GIF, could also use image.format in ('GIF','PNG')
02387         if original_mode == 'P' and format == 'GIF':
02388             image = image.convert('P')
02389         thumbnail_file = StringIO()
02390         # quality parameter doesn't affect lossless formats
02391         image.save(thumbnail_file, format, quality=self.pil_quality)
02392         thumbnail_file.seek(0)
02393         return thumbnail_file, format.lower()

Here is the caller graph for this function:

def Archetypes.Field.ImageField.set (   self,
  instance,
  value,
  kwargs 
)
Assign input value to object. If mimetype is not specified,
pass to processing method without one and add mimetype returned
to kwargs. Assign kwargs to instance.

Reimplemented from Archetypes.Field.FileField.

Definition at line 2176 of file Field.py.

02176 
02177     def set(self, instance, value, **kwargs):
02178         if not value:
02179             return
02180         # Do we have to delete the image?
02181         if value=="DELETE_IMAGE":
02182             self.removeScales(instance, **kwargs)
02183             # unset main field too
02184             ObjectField.unset(self, instance, **kwargs)
02185             return
02186 
02187         kwargs.setdefault('mimetype', None)
02188         default = self.getDefault(instance)
02189         value, mimetype, filename = self._process_input(value, default=default,
02190                                                         instance=instance, **kwargs)
02191         # value is an OFS.Image.File based instance
02192         # don't store empty images
02193         get_size = getattr(value, 'get_size', None)
02194         if get_size is not None and get_size() == 0:
02195             return
02196         
02197         kwargs['mimetype'] = mimetype
02198         kwargs['filename'] = filename
02199 
02200         try:
02201             data = self.rescaleOriginal(value, **kwargs)
02202         except (ConflictError, KeyboardInterrupt):
02203             raise
02204         except:
02205             if not self.swallowResizeExceptions:
02206                 raise
02207             else:
02208                 log_exc()
02209                 data = str(value.data)
02210         # TODO add self.ZCacheable_invalidate() later
02211         self.createOriginal(instance, data, **kwargs)
02212         self.createScales(instance, value=data)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.FileField.setContentType (   self,
  instance,
  value 
) [inherited]
Set mimetype in the base unit.

Reimplemented from Archetypes.Field.ObjectField.

Reimplemented in Archetypes.Field.TextField.

Definition at line 871 of file Field.py.

00871 
00872     def setContentType(self, instance, value):
00873         """Set mimetype in the base unit.
00874         """
00875         file = self.get(instance)
00876         try: 
00877             # file might be None or an empty string
00878             setattr(file, 'content_type', value)
00879         except AttributeError:
00880             pass
00881         else:
00882             self.set(instance, file)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.FileField.setFilename (   self,
  instance,
  filename 
) [inherited]
Set file name in the base unit.

Definition at line 1125 of file Field.py.

01125 
01126     def setFilename(self, instance, filename):
01127         """Set file name in the base unit.
01128         """
01129         bu = self.getBaseUnit(instance, full=True)
01130         bu.setFilename(filename)
01131         self.set(instance, bu)

Here is the call graph for this function:

def Archetypes.Field.ObjectField.setStorage (   self,
  instance,
  storage 
) [inherited]

Definition at line 746 of file Field.py.

00746 
00747     def setStorage(self, instance, storage):
00748         if not IStorage.isImplementedBy(storage):
00749             raise ObjectFieldException, "Not a valid Storage method"
00750         # raw=1 is required for TextField
00751         value = self.get(instance, raw=True)
00752         self.unset(instance)
00753         self.storage = storage
00754         if shasattr(self.storage, 'initializeInstance'):
00755             self.storage.initializeInstance(instance)
00756         self.set(instance, value)

Here is the call graph for this function:

def Archetypes.Field.ImageField.tag (   self,
  instance,
  scale = None,
  height = None,
  width = None,
  alt = None,
  css_class = None,
  title = None,
  kwargs 
)
Create a tag including scale

Definition at line 2455 of file Field.py.

02455 
02456             css_class=None, title=None, **kwargs):
02457         """Create a tag including scale
02458         """
02459         image = self.getScale(instance, scale=scale)
02460         if image:
02461             img_width, img_height = self.getSize(instance, scale=scale)
02462         else:
02463             img_height=0
02464             img_width=0
02465 
02466         if height is None:
02467             height=img_height
02468         if width is None:
02469             width=img_width
02470 
02471         url = instance.absolute_url()
02472         if scale:
02473             url+= '/' + self.getScaleName(scale)
02474         else:
02475             url+= '/' + self.getName()
02476 
02477         values = {'src' : url,
02478                   'alt' : escape(alt and alt or instance.Title(), 1),
02479                   'title' : escape(title and title or instance.Title(), 1),
02480                   'height' : height,
02481                   'width' : width,
02482                  }
02483 
02484         result = '<img src="%(src)s" alt="%(alt)s" title="%(title)s" '\
02485                  'height="%(height)s" width="%(width)s"' % values
02486 
02487         if css_class is not None:
02488             result = '%s class="%s"' % (result, css_class)
02489 
02490         for key, value in kwargs.items():
02491             if value:
02492                 result = '%s %s="%s"' % (result, key, value)
02493 
02494         return '%s />' % result
02495 
02496 # photo field implementation, derived from CMFPhoto by Magnus Heino
02497 # DEPRECATED

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.toString (   self) [inherited]
Utility method for converting a Field to a string for the
purpose of comparing fields.  This comparison is used for
determining whether a schema has changed in the auto update
function. Right now it's pretty crude.

Definition at line 652 of file Field.py.

00652 
00653     def toString(self):
00654         """Utility method for converting a Field to a string for the
00655         purpose of comparing fields.  This comparison is used for
00656         determining whether a schema has changed in the auto update
00657         function. Right now it's pretty crude."""
00658         # TODO fixme
00659         s = '%s(%s): {' % ( self.__class__.__name__, self.__name__ )
00660         sorted_keys = self._properties.keys()
00661         sorted_keys.sort()
00662         for k in sorted_keys:
00663             value = getattr( self, k, self._properties[k] )
00664             if k == 'widget':
00665                 value = value.__class__.__name__
00666             if type(value) is UnicodeType:
00667                 value = value.encode('utf-8')
00668             s = s + '%s:%s,' % (k, value )
00669         s = s + '}'
00670         return s

Here is the caller graph for this function:

def Archetypes.Field.ObjectField.unset (   self,
  instance,
  kwargs 
) [inherited]

Definition at line 740 of file Field.py.

00740 
00741     def unset(self, instance, **kwargs):
00742         #kwargs['field'] = self
00743         __traceback_info__ = (self.getName(), instance, kwargs)
00744         self.getStorage(instance).unset(self.getName(), instance, **kwargs)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.validate (   self,
  value,
  instance,
  errors = None,
  kwargs 
) [inherited]
Validate passed-in value using all field validators.
Return None if all validations pass; otherwise, return failed
result returned by validator

Definition at line 299 of file Field.py.

00299 
00300     def validate(self, value, instance, errors=None, **kwargs):
00301         """
00302         Validate passed-in value using all field validators.
00303         Return None if all validations pass; otherwise, return failed
00304         result returned by validator
00305         """
00306         if errors is None:
00307             errors = {}
00308         name = self.getName()
00309         if errors and errors.has_key(name):
00310             return True
00311 
00312         if self.required:
00313             res = self.validate_required(instance, value, errors)
00314             if res is not None:
00315                 return res
00316 
00317         if self.enforceVocabulary:
00318             res = self.validate_vocabulary(instance, value, errors)
00319             if res is not None:
00320                 return res
00321 
00322         res = instance.validate_field(name, value, errors)
00323         if res is not None:
00324             return res
00325 
00326         if self.validators:
00327             res = self.validate_validators(value, instance, errors, **kwargs)
00328             if res is not True:
00329                 return res
00330 
00331         # all ok
00332         return None

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.FileField.validate_required (   self,
  instance,
  value,
  errors 
) [inherited]

Reimplemented from Archetypes.Field.Field.

Definition at line 1133 of file Field.py.

01133 
01134     def validate_required(self, instance, value, errors):
01135         value = getattr(value, 'get_size', lambda: value and str(value))()
01136         return ObjectField.validate_required(self, instance, value, errors)

def Archetypes.Field.Field.validate_validators (   self,
  value,
  instance,
  errors,
  kwargs 
) [inherited]

Definition at line 334 of file Field.py.

00334 
00335     def validate_validators(self, value, instance, errors, **kwargs):
00336         """
00337         """
00338         if self.validators:
00339             result = self.validators(value, instance=instance, errors=errors,
00340                                      field=self, **kwargs)
00341         else:
00342             result = True
00343 
00344         if result is not True:
00345             return result

Here is the caller graph for this function:

def Archetypes.Field.Field.validate_vocabulary (   self,
  instance,
  value,
  errors 
) [inherited]
Make sure value is inside the allowed values
for a given vocabulary

Definition at line 363 of file Field.py.

00363 
00364     def validate_vocabulary(self, instance, value, errors):
00365         """Make sure value is inside the allowed values
00366         for a given vocabulary"""
00367         badvalues = []
00368         if value:
00369             # coerce value into a list called values
00370             values = value
00371             if type(value) in STRING_TYPES:
00372                 values = [value]
00373             elif type(value) == BooleanType:
00374                 values = [str(value)]
00375             elif type(value) not in (TupleType, ListType):
00376                 raise TypeError("Field value type error: %s" % type(value))
00377             vocab = self.Vocabulary(instance)
00378             # filter empty
00379             values = [instance.unicodeEncode(v)
00380                       for v in values if v.strip()]
00381             # extract valid values from vocabulary
00382             valids = []
00383             for v in vocab:
00384                 if type(v) in (TupleType, ListType):
00385                     v = v[0]
00386                 if not type(v) in STRING_TYPES:
00387                     v = str(v)
00388                 valids.append(instance.unicodeEncode(v))
00389             # check field values
00390             badvalues = [val for val in values if not val in valids]
00391 
00392         error = None
00393         if badvalues:
00394             request = aq_get(instance, 'REQUEST')
00395             label = self.widget.Label(instance)
00396             if isinstance(label, Message):
00397                 label = translate(label, context=request)
00398             if isinstance(val, Message):
00399                 val = translate(val, context=request)
00400             error = _( u'error_vocabulary',
00401                 default=u'Values ${val} is not allowed for vocabulary of element ${label}.',
00402                 mapping={'val': unicode(badvalues), 'name': label})
00403             error = translate(error, context=request)
00404             errors[self.getName()] = error
00405         return error

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.Vocabulary (   self,
  content_instance = None 
) [inherited]
Returns a DisplayList.

Uses self.vocabulary as source.

1) Static vocabulary

   - is already a DisplayList
   - is a list of 2-tuples with strings (see above)
   - is a list of strings (in this case a DisplayList
     with key=value will be created)

2) Dynamic vocabulary:

   - precondition: a content_instance is given.

   - has to return a:

* DisplayList or
* list of strings or
* list of 2-tuples with strings:
    '[("key1","value 1"),("key 2","value 2"),]'

   - the output is postprocessed like a static vocabulary.

   - vocabulary is a string:
if a method with the name of the string exists it will be called

   - vocabulary is a class implementing IVocabulary:
the "getDisplayList" method of the class will be called.

3) Zope 3 vocabulary factory vocabulary

    - precondition: a content_instance is given
    
    - self.vocabulary_factory is given
    
    - a named utility providing zope.schema.interfaces.IVocbularyFactory 
      exists for the name self.vocabulary_factory.

Reimplemented in Archetypes.Field.ReferenceField.

Definition at line 407 of file Field.py.

00407 
00408     def Vocabulary(self, content_instance=None):
00409         """
00410         Returns a DisplayList.
00411 
00412         Uses self.vocabulary as source.
00413 
00414         1) Static vocabulary
00415 
00416            - is already a DisplayList
00417            - is a list of 2-tuples with strings (see above)
00418            - is a list of strings (in this case a DisplayList
00419              with key=value will be created)
00420 
00421         2) Dynamic vocabulary:
00422 
00423            - precondition: a content_instance is given.
00424 
00425            - has to return a:
00426 
00427                 * DisplayList or
00428                 * list of strings or
00429                 * list of 2-tuples with strings:
00430                     '[("key1","value 1"),("key 2","value 2"),]'
00431 
00432            - the output is postprocessed like a static vocabulary.
00433 
00434            - vocabulary is a string:
00435                 if a method with the name of the string exists it will be called
00436 
00437            - vocabulary is a class implementing IVocabulary:
00438                 the "getDisplayList" method of the class will be called.
00439 
00440         3) Zope 3 vocabulary factory vocabulary
00441         
00442             - precondition: a content_instance is given
00443             
00444             - self.vocabulary_factory is given
00445             
00446             - a named utility providing zope.schema.interfaces.IVocbularyFactory 
00447               exists for the name self.vocabulary_factory.
00448 
00449         """
00450         value = self.vocabulary
00451         
00452         # Attempt to get the value from a a vocabulary factory if one was given
00453         # and no explicit vocabulary was set
00454         if not isinstance(value, DisplayList) and not value:
00455             factory_name = getattr(self, 'vocabulary_factory', None)
00456             if factory_name is not None:
00457                 factory = component.getUtility(schema.interfaces.IVocabularyFactory, name=factory_name)
00458                 factory_context = content_instance
00459                 if factory_context is None:
00460                     factory_context = self
00461                 value = DisplayList([(t.value, t.title or t.token) for t in factory(factory_context)])
00462                     
00463         if not isinstance(value, DisplayList):
00464 
00465             if content_instance is not None and isinstance(value, basestring):
00466                 # Dynamic vocabulary by method on class of content_instance
00467                 method = getattr(content_instance, value, None)
00468                 if method and callable(method):
00469                     args = []
00470                     kw = {'content_instance' : content_instance,
00471                           'field' : self}
00472                     value = mapply(method, *args, **kw)
00473             elif content_instance is not None and \
00474                  IVocabulary.isImplementedBy(value):
00475                 # Dynamic vocabulary provided by a class that
00476                 # implements IVocabulary
00477                 value = value.getDisplayList(content_instance)
00478 
00479             # Post process value into a DisplayList
00480             # Templates will use this interface
00481             sample = value[:1]
00482             if isinstance(sample, DisplayList):
00483                 # Do nothing, the bomb is already set up
00484                 pass
00485             elif isinstance(sample, (list, tuple)):
00486                 # Assume we have ((value, display), ...)
00487                 # and if not ('', '', '', ...)
00488                 if sample and not isinstance((sample[0]), (list, tuple)):
00489                     # if not a 2-tuple
00490                     value = zip(value, value)
00491                 value = DisplayList(value)
00492             elif len(sample) and isinstance(sample[0], basestring):
00493                 value = DisplayList(zip(value, value))
00494             else:
00495                 log('Unhandled type in Vocab')
00496                 log(value)
00497 
00498         if content_instance:
00499             # Translate vocabulary
00500             i18n_domain = (getattr(self, 'i18n_domain', None) or
00501                           getattr(self.widget, 'i18n_domain', None))
00502 
00503             return Vocabulary(value, content_instance, i18n_domain)
00504 
00505         return value

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.writeable (   self,
  instance,
  debug = False 
) [inherited]

Definition at line 527 of file Field.py.

00527 
00528     def writeable(self, instance, debug=False):
00529         if 'w' not in self.mode:
00530             if debug:
00531                 log("Tried to update %s:%s but field is not writeable." % \
00532                     (instance.portal_type, self.getName()))
00533             return False
00534 
00535         method = self.getMutator(instance)
00536         if not method:
00537             if debug:
00538                 log("No method %s on %s." % (self.mutator, instance))
00539             return False
00540 
00541         if not self.checkPermission('edit', instance):
00542             if debug:
00543                 log("User %s tried to update %s:%s but "
00544                     "doesn't have enough permissions." %
00545                     (_getAuthenticatedUser(instance).getId(),
00546                      instance.portal_type, self.getName()))
00547             return False
00548         return True

Here is the call graph for this function:


Member Data Documentation

tuple Archetypes.Field.ImageField._properties = FileField._properties.copy() [static, private]

Reimplemented from Archetypes.Field.FileField.

Definition at line 2154 of file Field.py.

string Archetypes.Field.ImageField.default_view = "view" [static]

Definition at line 2173 of file Field.py.

Definition at line 638 of file Field.py.

tuple Archetypes.Field.ImageField.security = ClassSecurityInfo() [static]

Reimplemented from Archetypes.Field.FileField.

Definition at line 2171 of file Field.py.

Definition at line 752 of file Field.py.

Definition at line 296 of file Field.py.

Definition at line 249 of file Field.py.


The documentation for this class was generated from the following file: