desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Returns a list of string names corresponding to each of the Fields
available in this Layer.'
| @property
def fields(self):
| return [force_text(capi.get_field_name(capi.get_field_defn(self._ldefn, i)), self._ds.encoding, strings_only=True) for i in xrange(self.num_fields)]
|
'Returns a list of the types of fields in this Layer. For example,
the list [OFTInteger, OFTReal, OFTString] would be returned for
an OGR layer that had an integer, a floating-point, and string
fields.'
| @property
def field_types(self):
| return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))] for i in xrange(self.num_fields)]
|
'Returns a list of the maximum field widths for the features.'
| @property
def field_widths(self):
| return [capi.get_field_width(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)]
|
'Returns the field precisions for the features.'
| @property
def field_precisions(self):
| return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)]
|
'Returns a list containing the given field name for every Feature
in the Layer.'
| def get_fields(self, field_name):
| if (not (field_name in self.fields)):
raise OGRException(('invalid field name: %s' % field_name))
return [feat.get(field_name) for feat in self]
|
'Returns a list containing the OGRGeometry for every Feature in
the Layer.'
| def get_geoms(self, geos=False):
| if geos:
from django.contrib.gis.geos import GEOSGeometry
return [GEOSGeometry(feat.geom.wkb) for feat in self]
else:
return [feat.geom for feat in self]
|
'Returns a bool indicating whether the this Layer supports the given
capability (a string). Valid capability strings include:
\'RandomRead\', \'SequentialWrite\', \'RandomWrite\', \'FastSpatialFilter\',
\'FastFeatureCount\', \'FastGetExtent\', \'CreateField\', \'Transactions\',
\'DeleteFeature\', and \'FastSetNextByIndex\'.'
| def test_capability(self, capability):
| return bool(capi.test_capability(self.ptr, force_bytes(capability)))
|
'Creates a GDAL OSR Spatial Reference object from the given input.
The input may be string of OGC Well Known Text (WKT), an integer
EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand
string (one of \'WGS84\', \'WGS72\', \'NAD27\', \'NAD83\').'
| def __init__(self, srs_input=''):
| srs_type = 'user'
if isinstance(srs_input, six.string_types):
if isinstance(srs_input, six.text_type):
srs_input = srs_input.encode('ascii')
try:
srid = int(srs_input)
srs_input = ('EPSG:%d' % srid)
except ValueError:
pass
elif isinstance(srs_input, six.integer_types):
srs_type = 'epsg'
elif isinstance(srs_input, self.ptr_type):
srs = srs_input
srs_type = 'ogr'
else:
raise TypeError(('Invalid SRS type "%s"' % srs_type))
if (srs_type == 'ogr'):
srs = srs_input
else:
buf = c_char_p('')
srs = capi.new_srs(buf)
if (not srs):
raise SRSException(('Could not create spatial reference from: %s' % srs_input))
else:
self.ptr = srs
if (srs_type == 'user'):
self.import_user_input(srs_input)
elif (srs_type == 'epsg'):
self.import_epsg(srs_input)
|
'Destroys this spatial reference.'
| def __del__(self):
| if self._ptr:
capi.release_srs(self._ptr)
|
'Returns the value of the given string attribute node, None if the node
doesn\'t exist. Can also take a tuple as a parameter, (target, child),
where child is the index of the attribute in the WKT. For example:
>>> wkt = \'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]\')
>>> srs = SpatialReference(wkt) # could also use \'WGS84\', or 4326
>>> print(srs[\'GEOGCS\'])
WGS 84
>>> print(srs[\'DATUM\'])
WGS_1984
>>> print(srs[\'AUTHORITY\'])
EPSG
>>> print(srs[\'AUTHORITY\', 1]) # The authority value
4326
>>> print(srs[\'TOWGS84\', 4]) # the fourth value in this wkt
0
>>> print(srs[\'UNIT|AUTHORITY\']) # For the units authority, have to use the pipe symbole.
EPSG
>>> print(srs[\'UNIT|AUTHORITY\', 1]) # The authority value for the untis
9122'
| def __getitem__(self, target):
| if isinstance(target, tuple):
return self.attr_value(*target)
else:
return self.attr_value(target)
|
'The string representation uses \'pretty\' WKT.'
| def __str__(self):
| return self.pretty_wkt
|
'The attribute value for the given target node (e.g. \'PROJCS\'). The index
keyword specifies an index of the child node to return.'
| def attr_value(self, target, index=0):
| if ((not isinstance(target, six.string_types)) or (not isinstance(index, int))):
raise TypeError
return capi.get_attr_value(self.ptr, force_bytes(target), index)
|
'Returns the authority name for the given string target node.'
| def auth_name(self, target):
| return capi.get_auth_name(self.ptr, force_bytes(target))
|
'Returns the authority code for the given string target node.'
| def auth_code(self, target):
| return capi.get_auth_code(self.ptr, force_bytes(target))
|
'Returns a clone of this SpatialReference object.'
| def clone(self):
| return SpatialReference(capi.clone_srs(self.ptr))
|
'Morphs this SpatialReference from ESRI\'s format to EPSG.'
| def from_esri(self):
| capi.morph_from_esri(self.ptr)
|
'This method inspects the WKT of this SpatialReference, and will
add EPSG authority nodes where an EPSG identifier is applicable.'
| def identify_epsg(self):
| capi.identify_epsg(self.ptr)
|
'Morphs this SpatialReference to ESRI\'s format.'
| def to_esri(self):
| capi.morph_to_esri(self.ptr)
|
'Checks to see if the given spatial reference is valid.'
| def validate(self):
| capi.srs_validate(self.ptr)
|
'Returns the name of this Spatial Reference.'
| @property
def name(self):
| if self.projected:
return self.attr_value('PROJCS')
elif self.geographic:
return self.attr_value('GEOGCS')
elif self.local:
return self.attr_value('LOCAL_CS')
else:
return None
|
'Returns the SRID of top-level authority, or None if undefined.'
| @property
def srid(self):
| try:
return int(self.attr_value('AUTHORITY', 1))
except (TypeError, ValueError):
return None
|
'Returns the name of the linear units.'
| @property
def linear_name(self):
| (units, name) = capi.linear_units(self.ptr, byref(c_char_p()))
return name
|
'Returns the value of the linear units.'
| @property
def linear_units(self):
| (units, name) = capi.linear_units(self.ptr, byref(c_char_p()))
return units
|
'Returns the name of the angular units.'
| @property
def angular_name(self):
| (units, name) = capi.angular_units(self.ptr, byref(c_char_p()))
return name
|
'Returns the value of the angular units.'
| @property
def angular_units(self):
| (units, name) = capi.angular_units(self.ptr, byref(c_char_p()))
return units
|
'Returns a 2-tuple of the units value and the units name,
and will automatically determines whether to return the linear
or angular units.'
| @property
def units(self):
| (units, name) = (None, None)
if (self.projected or self.local):
(units, name) = capi.linear_units(self.ptr, byref(c_char_p()))
elif self.geographic:
(units, name) = capi.angular_units(self.ptr, byref(c_char_p()))
if (name is not None):
name.decode()
return (units, name)
|
'Returns a tuple of the ellipsoid parameters:
(semimajor axis, semiminor axis, and inverse flattening)'
| @property
def ellipsoid(self):
| return (self.semi_major, self.semi_minor, self.inverse_flattening)
|
'Returns the Semi Major Axis for this Spatial Reference.'
| @property
def semi_major(self):
| return capi.semi_major(self.ptr, byref(c_int()))
|
'Returns the Semi Minor Axis for this Spatial Reference.'
| @property
def semi_minor(self):
| return capi.semi_minor(self.ptr, byref(c_int()))
|
'Returns the Inverse Flattening for this Spatial Reference.'
| @property
def inverse_flattening(self):
| return capi.invflattening(self.ptr, byref(c_int()))
|
'Returns True if this SpatialReference is geographic
(root node is GEOGCS).'
| @property
def geographic(self):
| return bool(capi.isgeographic(self.ptr))
|
'Returns True if this SpatialReference is local (root node is LOCAL_CS).'
| @property
def local(self):
| return bool(capi.islocal(self.ptr))
|
'Returns True if this SpatialReference is a projected coordinate system
(root node is PROJCS).'
| @property
def projected(self):
| return bool(capi.isprojected(self.ptr))
|
'Imports the Spatial Reference from the EPSG code (an integer).'
| def import_epsg(self, epsg):
| capi.from_epsg(self.ptr, epsg)
|
'Imports the Spatial Reference from a PROJ.4 string.'
| def import_proj(self, proj):
| capi.from_proj(self.ptr, proj)
|
'Imports the Spatial Reference from the given user input string.'
| def import_user_input(self, user_input):
| capi.from_user_input(self.ptr, force_bytes(user_input))
|
'Imports the Spatial Reference from OGC WKT (string)'
| def import_wkt(self, wkt):
| capi.from_wkt(self.ptr, byref(c_char_p(wkt)))
|
'Imports the Spatial Reference from an XML string.'
| def import_xml(self, xml):
| capi.from_xml(self.ptr, xml)
|
'Returns the WKT representation of this Spatial Reference.'
| @property
def wkt(self):
| return capi.to_wkt(self.ptr, byref(c_char_p()))
|
'Returns the \'pretty\' representation of the WKT.'
| @property
def pretty_wkt(self, simplify=0):
| return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify)
|
'Returns the PROJ.4 representation for this Spatial Reference.'
| @property
def proj(self):
| return capi.to_proj(self.ptr, byref(c_char_p()))
|
'Alias for proj().'
| @property
def proj4(self):
| return self.proj
|
'Returns the XML representation of this Spatial Reference.'
| @property
def xml(self, dialect=''):
| return capi.to_xml(self.ptr, byref(c_char_p()), dialect)
|
'Initializes on a source and target SpatialReference objects.'
| def __init__(self, source, target):
| if ((not isinstance(source, SpatialReference)) or (not isinstance(target, SpatialReference))):
raise TypeError('source and target must be of type SpatialReference')
self.ptr = capi.new_ct(source._ptr, target._ptr)
self._srs1_name = source.name
self._srs2_name = target.name
|
'Deletes this Coordinate Transformation object.'
| def __del__(self):
| if self._ptr:
capi.destroy_ct(self._ptr)
|
'A LayerMapping object is initialized using the given Model (not an instance),
a DataSource (or string path to an OGR-supported data file), and a mapping
dictionary. See the module level docstring for more details and keyword
argument usage.'
| def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None):
| if isinstance(data, six.string_types):
self.ds = DataSource(data, encoding=encoding)
else:
self.ds = data
self.layer = self.ds[layer]
self.using = (using if (using is not None) else router.db_for_write(model))
self.spatial_backend = connections[self.using].ops
self.mapping = mapping
self.model = model
self.check_layer()
if self.spatial_backend.mysql:
transform = False
else:
self.geo_field = self.geometry_field()
if transform:
self.source_srs = self.check_srs(source_srs)
self.transform = self.coord_transform()
else:
self.transform = transform
if encoding:
from codecs import lookup
lookup(encoding)
self.encoding = encoding
else:
self.encoding = None
if unique:
self.check_unique(unique)
transaction_mode = 'autocommit'
self.unique = unique
else:
self.unique = None
if (transaction_mode in self.TRANSACTION_MODES):
self.transaction_decorator = self.TRANSACTION_MODES[transaction_mode]
self.transaction_mode = transaction_mode
else:
raise LayerMapError(('Unrecognized transaction mode: %s' % transaction_mode))
|
'This checks the `fid_range` keyword.'
| def check_fid_range(self, fid_range):
| if fid_range:
if isinstance(fid_range, (tuple, list)):
return slice(*fid_range)
elif isinstance(fid_range, slice):
return fid_range
else:
raise TypeError
else:
return None
|
'This checks the Layer metadata, and ensures that it is compatible
with the mapping information and model. Unlike previous revisions,
there is no need to increment through each feature in the Layer.'
| def check_layer(self):
| self.geom_field = False
self.fields = {}
ogr_fields = self.layer.fields
ogr_field_types = self.layer.field_types
def check_ogr_fld(ogr_map_fld):
try:
idx = ogr_fields.index(ogr_map_fld)
except ValueError:
raise LayerMapError(('Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld))
return idx
for (field_name, ogr_name) in self.mapping.items():
try:
model_field = self.model._meta.get_field(field_name)
except models.fields.FieldDoesNotExist:
raise LayerMapError(('Given mapping field "%s" not in given Model fields.' % field_name))
fld_name = model_field.__class__.__name__
if isinstance(model_field, GeometryField):
if self.geom_field:
raise LayerMapError('LayerMapping does not support more than one GeometryField per model.')
coord_dim = model_field.dim
try:
if (coord_dim == 3):
gtype = OGRGeomType((ogr_name + '25D'))
else:
gtype = OGRGeomType(ogr_name)
except OGRException:
raise LayerMapError(('Invalid mapping for GeometryField "%s".' % field_name))
ltype = self.layer.geom_type
if (not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field))):
raise LayerMapError(('Invalid mapping geometry; model has %s%s, layer geometry type is %s.' % (fld_name, (((coord_dim == 3) and '(dim=3)') or ''), ltype)))
self.geom_field = field_name
self.coord_dim = coord_dim
fields_val = model_field
elif isinstance(model_field, models.ForeignKey):
if isinstance(ogr_name, dict):
rel_model = model_field.rel.to
for (rel_name, ogr_field) in ogr_name.items():
idx = check_ogr_fld(ogr_field)
try:
rel_field = rel_model._meta.get_field(rel_name)
except models.fields.FieldDoesNotExist:
raise LayerMapError(('ForeignKey mapping field "%s" not in %s fields.' % (rel_name, rel_model.__class__.__name__)))
fields_val = rel_model
else:
raise TypeError('ForeignKey mapping must be of dictionary type.')
else:
if (not (model_field.__class__ in self.FIELD_TYPES)):
raise LayerMapError(('Django field type "%s" has no OGR mapping (yet).' % fld_name))
idx = check_ogr_fld(ogr_name)
ogr_field = ogr_field_types[idx]
if (not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__])):
raise LayerMapError(('OGR field "%s" (of type %s) cannot be mapped to Django %s.' % (ogr_field, ogr_field.__name__, fld_name)))
fields_val = model_field
self.fields[field_name] = fields_val
|
'Checks the compatibility of the given spatial reference object.'
| def check_srs(self, source_srs):
| if isinstance(source_srs, SpatialReference):
sr = source_srs
elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()):
sr = source_srs.srs
elif isinstance(source_srs, (int, six.string_types)):
sr = SpatialReference(source_srs)
else:
sr = self.layer.srs
if (not sr):
raise LayerMapError('No source reference system defined.')
else:
return sr
|
'Checks the `unique` keyword parameter -- may be a sequence or string.'
| def check_unique(self, unique):
| if isinstance(unique, (list, tuple)):
for attr in unique:
if (not (attr in self.mapping)):
raise ValueError
elif isinstance(unique, six.string_types):
if (unique not in self.mapping):
raise ValueError
else:
raise TypeError('Unique keyword argument must be set with a tuple, list, or string.')
|
'Given an OGR Feature, this will return a dictionary of keyword arguments
for constructing the mapped model.'
| def feature_kwargs(self, feat):
| kwargs = {}
for (field_name, ogr_name) in self.mapping.items():
model_field = self.fields[field_name]
if isinstance(model_field, GeometryField):
try:
val = self.verify_geom(feat.geom, model_field)
except OGRException:
raise LayerMapError('Could not retrieve geometry from feature.')
elif isinstance(model_field, models.base.ModelBase):
val = self.verify_fk(feat, model_field, ogr_name)
else:
val = self.verify_ogr_field(feat[ogr_name], model_field)
kwargs[field_name] = val
return kwargs
|
'Given the feature keyword arguments (from `feature_kwargs`) this routine
will construct and return the uniqueness keyword arguments -- a subset
of the feature kwargs.'
| def unique_kwargs(self, kwargs):
| if isinstance(self.unique, six.string_types):
return {self.unique: kwargs[self.unique]}
else:
return dict(((fld, kwargs[fld]) for fld in self.unique))
|
'Verifies if the OGR Field contents are acceptable to the Django
model field. If they are, the verified value is returned,
otherwise the proper exception is raised.'
| def verify_ogr_field(self, ogr_field, model_field):
| if (isinstance(ogr_field, OFTString) and isinstance(model_field, (models.CharField, models.TextField))):
if self.encoding:
val = force_text(ogr_field.value, self.encoding)
else:
val = ogr_field.value
if (model_field.max_length and (len(val) > model_field.max_length)):
raise InvalidString(('%s model field maximum string length is %s, given %s characters.' % (model_field.name, model_field.max_length, len(val))))
elif (isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField)):
try:
d = Decimal(str(ogr_field.value))
except:
raise InvalidDecimal(('Could not construct decimal from: %s' % ogr_field.value))
dtup = d.as_tuple()
digits = dtup[1]
d_idx = dtup[2]
max_prec = (model_field.max_digits - model_field.decimal_places)
if (d_idx < 0):
n_prec = len(digits[:d_idx])
else:
n_prec = (len(digits) + d_idx)
if (n_prec > max_prec):
raise InvalidDecimal(('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' % (model_field.max_digits, model_field.decimal_places, max_prec)))
val = d
elif (isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField)):
try:
val = int(ogr_field.value)
except:
raise InvalidInteger(('Could not construct integer from: %s' % ogr_field.value))
else:
val = ogr_field.value
return val
|
'Given an OGR Feature, the related model and its dictionary mapping,
this routine will retrieve the related model for the ForeignKey
mapping.'
| def verify_fk(self, feat, rel_model, rel_mapping):
| fk_kwargs = {}
for (field_name, ogr_name) in rel_mapping.items():
fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))
try:
return rel_model.objects.using(self.using).get(**fk_kwargs)
except ObjectDoesNotExist:
raise MissingForeignKey(('No ForeignKey %s model found with keyword arguments: %s' % (rel_model.__name__, fk_kwargs)))
|
'Verifies the geometry -- will construct and return a GeometryCollection
if necessary (for example if the model field is MultiPolygonField while
the mapped shapefile only contains Polygons).'
| def verify_geom(self, geom, model_field):
| if (self.coord_dim != geom.coord_dim):
geom.coord_dim = self.coord_dim
if self.make_multi(geom.geom_type, model_field):
multi_type = self.MULTI_TYPES[geom.geom_type.num]
g = OGRGeometry(multi_type)
g.add(geom)
else:
g = geom
if self.transform:
g.transform(self.transform)
return g.wkt
|
'Returns the coordinate transformation object.'
| def coord_transform(self):
| SpatialRefSys = self.spatial_backend.spatial_ref_sys()
try:
target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs
return CoordTransform(self.source_srs, target_srs)
except Exception as msg:
raise LayerMapError(('Could not translate between the data source and model geometry: %s' % msg))
|
'Returns the GeometryField instance associated with the geographic column.'
| def geometry_field(self):
| opts = self.model._meta
(fld, model, direct, m2m) = opts.get_field_by_name(self.geom_field)
return fld
|
'Given the OGRGeomType for a geometry and its associated GeometryField,
determine whether the geometry should be turned into a GeometryCollection.'
| def make_multi(self, geom_type, model_field):
| return ((geom_type.num in self.MULTI_TYPES) and (model_field.__class__.__name__ == ('Multi%s' % geom_type.django)))
|
'Saves the contents from the OGR DataSource Layer into the database
according to the mapping dictionary given at initialization.
Keyword Parameters:
verbose:
If set, information will be printed subsequent to each model save
executed on the database.
fid_range:
May be set with a slice or tuple of (begin, end) feature ID\'s to map
from the data source. In other words, this keyword enables the user
to selectively import a subset range of features in the geographic
data source.
step:
If set with an integer, transactions will occur at every step
interval. For example, if step=1000, a commit would occur after
the 1,000th feature, the 2,000th feature etc.
progress:
When this keyword is set, status information will be printed giving
the number of features processed and sucessfully saved. By default,
progress information will pe printed every 1000 features processed,
however, this default may be overridden by setting this keyword with an
integer for the desired interval.
stream:
Status information will be written to this file handle. Defaults to
using `sys.stdout`, but any object with a `write` method is supported.
silent:
By default, non-fatal error notifications are printed to stdout, but
this keyword may be set to disable these notifications.
strict:
Execution of the model mapping will cease upon the first error
encountered. The default behavior is to attempt to continue.'
| def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False):
| default_range = self.check_fid_range(fid_range)
if progress:
if ((progress is True) or (not isinstance(progress, int))):
progress_interval = 1000
else:
progress_interval = progress
@self.transaction_decorator
def _save(feat_range=default_range, num_feat=0, num_saved=0):
if feat_range:
layer_iter = self.layer[feat_range]
else:
layer_iter = self.layer
for feat in layer_iter:
num_feat += 1
try:
kwargs = self.feature_kwargs(feat)
except LayerMapError as msg:
if strict:
raise
elif (not silent):
stream.write(('Ignoring Feature ID %s because: %s\n' % (feat.fid, msg)))
else:
is_update = False
if self.unique:
try:
u_kwargs = self.unique_kwargs(kwargs)
m = self.model.objects.using(self.using).get(**u_kwargs)
is_update = True
geom = getattr(m, self.geom_field).ogr
new = OGRGeometry(kwargs[self.geom_field])
for g in new:
geom.add(g)
setattr(m, self.geom_field, geom.wkt)
except ObjectDoesNotExist:
m = self.model(**kwargs)
else:
m = self.model(**kwargs)
try:
m.save(using=self.using)
num_saved += 1
if verbose:
stream.write(('%s: %s\n' % (((is_update and 'Updated') or 'Saved'), m)))
except SystemExit:
raise
except Exception as msg:
if (self.transaction_mode == 'autocommit'):
transaction.rollback_unless_managed()
if strict:
if (not silent):
stream.write(('Failed to save the feature (id: %s) into the model with the keyword arguments:\n' % feat.fid))
stream.write(('%s\n' % kwargs))
raise
elif (not silent):
stream.write(('Failed to save %s:\n %s\nContinuing\n' % (kwargs, msg)))
if (progress and ((num_feat % progress_interval) == 0)):
stream.write(('Processed %d features, saved %d ...\n' % (num_feat, num_saved)))
return (num_saved, num_feat)
nfeat = self.layer.num_feat
if (step and isinstance(step, int) and (step < nfeat)):
if default_range:
raise LayerMapError('The `step` keyword may not be used in conjunction with the `fid_range` keyword.')
(beg, num_feat, num_saved) = (0, 0, 0)
indices = range(step, nfeat, step)
n_i = len(indices)
for (i, end) in enumerate(indices):
if ((i + 1) == n_i):
step_slice = slice(beg, None)
else:
step_slice = slice(beg, end)
try:
(num_feat, num_saved) = _save(step_slice, num_feat, num_saved)
beg = end
except:
stream.write(('%s\nFailed to save slice: %s\n' % (('=-' * 20), step_slice)))
raise
else:
_save()
|
'Return the graph as a nested list.'
| def nested(self, format_callback=None):
| seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots
|
'We always want to load the objects into memory so that we can display
them to the user in confirm page.'
| def can_fast_delete(self, *args, **kwargs):
| return False
|
'Returns the proper model field name corresponding to the given
field_name to use for ordering. field_name may either be the name of a
proper model field or the name of a method (on the admin or model) or a
callable with the \'admin_order_field\' attribute. Returns None if no
proper model field name can be matched.'
| def get_ordering_field(self, field_name):
| try:
field = self.lookup_opts.get_field(field_name)
return field.name
except models.FieldDoesNotExist:
if callable(field_name):
attr = field_name
elif hasattr(self.model_admin, field_name):
attr = getattr(self.model_admin, field_name)
else:
attr = getattr(self.model, field_name)
return getattr(attr, 'admin_order_field', None)
|
'Returns the list of ordering fields for the change list.
First we check the get_ordering() method in model admin, then we check
the object\'s default ordering. Then, any manually-specified ordering
from the query string overrides anything. Finally, a deterministic
order is guaranteed by ensuring the primary key is used as the last
ordering field.'
| def get_ordering(self, request, queryset):
| params = self.params
ordering = list((self.model_admin.get_ordering(request) or self._get_default_ordering()))
if (ORDER_VAR in params):
ordering = []
order_params = params[ORDER_VAR].split('.')
for p in order_params:
try:
(none, pfx, idx) = p.rpartition('-')
field_name = self.list_display[int(idx)]
order_field = self.get_ordering_field(field_name)
if (not order_field):
continue
ordering.append((pfx + order_field))
except (IndexError, ValueError):
continue
ordering.extend(queryset.query.order_by)
pk_name = self.lookup_opts.pk.name
if (not (set(ordering) & set(['pk', '-pk', pk_name, ('-' + pk_name)]))):
ordering.append('-pk')
return ordering
|
'Returns a SortedDict of ordering field column numbers and asc/desc'
| def get_ordering_field_columns(self):
| ordering = self._get_default_ordering()
ordering_fields = SortedDict()
if (ORDER_VAR not in self.params):
for field in ordering:
if field.startswith('-'):
field = field[1:]
order_type = 'desc'
else:
order_type = 'asc'
for (index, attr) in enumerate(self.list_display):
if (self.get_ordering_field(attr) == field):
ordering_fields[index] = order_type
break
else:
for p in self.params[ORDER_VAR].split('.'):
(none, pfx, idx) = p.rpartition('-')
try:
idx = int(idx)
except ValueError:
continue
ordering_fields[idx] = ('desc' if (pfx == '-') else 'asc')
return ordering_fields
|
'Returns the edited object represented by this log entry'
| def get_edited_object(self):
| return self.content_type.get_object_for_this_type(pk=self.object_id)
|
'Returns the admin URL to edit the object represented by this log entry.
This is relative to the Django admin index page.'
| def get_admin_url(self):
| if (self.content_type and self.object_id):
return (u'%s/%s/%s/' % (self.content_type.app_label, self.content_type.model, quote(self.object_id)))
return None
|
'Outputs a <ul> for this set of radio fields.'
| def render(self):
| return format_html(u'<ul{0}>\n{1}\n</ul>', flatatt(self.attrs), format_html_join(u'\n', u'<li>{0}</li>', ((force_text(w),) for w in self)))
|
'Helper function for building an attribute dictionary.'
| def build_attrs(self, extra_attrs=None, **kwargs):
| self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs)
return self.attrs
|
'Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn\'t given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they\'ll be applied as options to the admin class.
If a model is already registered, this will raise AlreadyRegistered.
If a model is abstract, this will raise ImproperlyConfigured.'
| def register(self, model_or_iterable, admin_class=None, **options):
| if (not admin_class):
admin_class = ModelAdmin
if (admin_class and settings.DEBUG):
from django.contrib.admin.validation import validate
else:
validate = (lambda model, adminclass: None)
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured(('The model %s is abstract, so it cannot be registered with admin.' % model.__name__))
if (model in self._registry):
raise AlreadyRegistered(('The model %s is already registered' % model.__name__))
if (not model._meta.swapped):
if options:
options['__module__'] = __name__
admin_class = type(('%sAdmin' % model.__name__), (admin_class,), options)
validate(admin_class, model)
self._registry[model] = admin_class(model, self)
|
'Unregisters the given model(s).
If a model isn\'t already registered, this will raise NotRegistered.'
| def unregister(self, model_or_iterable):
| if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if (model not in self._registry):
raise NotRegistered(('The model %s is not registered' % model.__name__))
del self._registry[model]
|
'Register an action to be available globally.'
| def add_action(self, action, name=None):
| name = (name or action.__name__)
self._actions[name] = action
self._global_actions[name] = action
|
'Disable a globally-registered action. Raises KeyError for invalid names.'
| def disable_action(self, name):
| del self._actions[name]
|
'Explicitally get a registered global action wheather it\'s enabled or
not. Raises KeyError for invalid names.'
| def get_action(self, name):
| return self._global_actions[name]
|
'Get all the enabled actions as an iterable of (name, func).'
| @property
def actions(self):
| return six.iteritems(self._actions)
|
'Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.'
| def has_permission(self, request):
| return (request.user.is_active and request.user.is_staff)
|
'Check that all things needed to run the admin have been correctly installed.
The default implementation checks that LogEntry, ContentType and the
auth context processor are installed.'
| def check_dependencies(self):
| from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.models import ContentType
if (not LogEntry._meta.installed):
raise ImproperlyConfigured("Put 'django.contrib.admin' in your INSTALLED_APPS setting in order to use the admin application.")
if (not ContentType._meta.installed):
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting in order to use the admin application.")
if (not (('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS) or ('django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS))):
raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
|
'Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You\'ll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls import patterns, url
urls = super(MyAdminSite, self).get_urls()
urls += patterns(\'\',
url(r\'^my_view/$\', self.admin_view(some_view))
return urls
By default, admin_views are marked non-cacheable using the
``never_cache`` decorator. If the view can be safely cached, set
cacheable=True.'
| def admin_view(self, view, cacheable=False):
| def inner(request, *args, **kwargs):
if (not self.has_permission(request)):
if (request.path == reverse('admin:logout', current_app=self.name)):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
return self.login(request)
return view(request, *args, **kwargs)
if (not cacheable):
inner = never_cache(inner)
if (not getattr(view, 'csrf_exempt', False)):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
|
'Handles the "change password" task -- both form display and validation.'
| def password_change(self, request):
| from django.contrib.auth.views import password_change
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {'current_app': self.name, 'post_change_redirect': url}
if (self.password_change_template is not None):
defaults['template_name'] = self.password_change_template
return password_change(request, **defaults)
|
'Displays the "success" page after a password change.'
| def password_change_done(self, request, extra_context=None):
| from django.contrib.auth.views import password_change_done
defaults = {'current_app': self.name, 'extra_context': (extra_context or {})}
if (self.password_change_done_template is not None):
defaults['template_name'] = self.password_change_done_template
return password_change_done(request, **defaults)
|
'Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it\'s set to False, the
generated JavaScript will be leaner and faster.'
| def i18n_javascript(self, request):
| if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
|
'Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.'
| @never_cache
def logout(self, request, extra_context=None):
| from django.contrib.auth.views import logout
defaults = {'current_app': self.name, 'extra_context': (extra_context or {})}
if (self.logout_template is not None):
defaults['template_name'] = self.logout_template
return logout(request, **defaults)
|
'Displays the login form for the given HttpRequest.'
| @never_cache
def login(self, request, extra_context=None):
| from django.contrib.auth.views import login
context = {'title': _('Log in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path()}
context.update((extra_context or {}))
defaults = {'extra_context': context, 'current_app': self.name, 'authentication_form': (self.login_form or AdminAuthenticationForm), 'template_name': (self.login_template or 'admin/login.html')}
return login(request, **defaults)
|
'Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.'
| @never_cache
def index(self, request, extra_context=None):
| app_dict = {}
user = request.user
for (model, model_admin) in self._registry.items():
app_label = model._meta.app_label
has_module_perms = user.has_module_perms(app_label)
if has_module_perms:
perms = model_admin.get_model_perms(request)
if (True in perms.values()):
info = (app_label, model._meta.module_name)
model_dict = {'name': capfirst(model._meta.verbose_name_plural), 'perms': perms}
if perms.get('change', False):
try:
model_dict['admin_url'] = reverse(('admin:%s_%s_changelist' % info), current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add', False):
try:
model_dict['add_url'] = reverse(('admin:%s_%s_add' % info), current_app=self.name)
except NoReverseMatch:
pass
if (app_label in app_dict):
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {'name': app_label.title(), 'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name), 'has_module_perms': has_module_perms, 'models': [model_dict]}
app_list = list(six.itervalues(app_dict))
app_list.sort(key=(lambda x: x['name']))
for app in app_list:
app['models'].sort(key=(lambda x: x['name']))
context = {'title': _('Site administration'), 'app_list': app_list}
context.update((extra_context or {}))
return TemplateResponse(request, (self.index_template or 'admin/index.html'), context, current_app=self.name)
|
'Helper function that blocks the execution of the tests until the
specified callback returns a value that is not falsy. This function can
be called, for example, after clicking a link or submitting a form.
See the other public methods that call this function for more details.'
| def wait_until(self, callback, timeout=10):
| from selenium.webdriver.support.wait import WebDriverWait
WebDriverWait(self.selenium, timeout).until(callback)
|
'Helper function that blocks until the element with the given tag name
is found on the page.'
| def wait_loaded_tag(self, tag_name, timeout=10):
| self.wait_until((lambda driver: driver.find_element_by_tag_name(tag_name)), timeout)
|
'Block until page has started to load.'
| def wait_page_loaded(self):
| from selenium.common.exceptions import TimeoutException
try:
self.wait_loaded_tag('body')
except TimeoutException:
pass
|
'Helper function to log into the admin.'
| def admin_login(self, username, password, login_url='/admin/'):
| self.selenium.get(('%s%s' % (self.live_server_url, login_url)))
username_input = self.selenium.find_element_by_name('username')
username_input.send_keys(username)
password_input = self.selenium.find_element_by_name('password')
password_input.send_keys(password)
login_text = _('Log in')
self.selenium.find_element_by_xpath(('//input[@value="%s"]' % login_text)).click()
self.wait_page_loaded()
|
'Helper function that returns the value for the CSS attribute of an
DOM element specified by the given selector. Uses the jQuery that ships
with Django.'
| def get_css_value(self, selector, attribute):
| return self.selenium.execute_script(('return django.jQuery("%s").css("%s")' % (selector, attribute)))
|
'Returns the <OPTION> with the value `value` inside the <SELECT> widget
identified by the CSS selector `selector`.'
| def get_select_option(self, selector, value):
| from selenium.common.exceptions import NoSuchElementException
options = self.selenium.find_elements_by_css_selector(('%s > option' % selector))
for option in options:
if (option.get_attribute('value') == value):
return option
raise NoSuchElementException(('Option "%s" not found in "%s"' % (value, selector)))
|
'Asserts that the <SELECT> widget identified by `selector` has the
options with the given `values`.'
| def assertSelectOptions(self, selector, values):
| options = self.selenium.find_elements_by_css_selector(('%s > option' % selector))
actual_values = []
for option in options:
actual_values.append(option.get_attribute('value'))
self.assertEqual(values, actual_values)
|
'Returns True if the element identified by `selector` has the CSS class
`klass`.'
| def has_css_class(self, selector, klass):
| return (self.selenium.find_element_by_css_selector(selector).get_attribute('class').find(klass) != (-1))
|
'Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they\'re passed to the form Field\'s constructor.'
| def formfield_for_dbfield(self, db_field, **kwargs):
| request = kwargs.pop('request', None)
if db_field.choices:
return self.formfield_for_choice_field(db_field, request, **kwargs)
if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
if (db_field.__class__ in self.formfield_overrides):
kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
if isinstance(db_field, models.ForeignKey):
formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
elif isinstance(db_field, models.ManyToManyField):
formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
if (formfield and (db_field.name not in self.raw_id_fields)):
related_modeladmin = self.admin_site._registry.get(db_field.rel.to)
can_add_related = bool((related_modeladmin and related_modeladmin.has_add_permission(request)))
formfield.widget = widgets.RelatedFieldWidgetWrapper(formfield.widget, db_field.rel, self.admin_site, can_add_related=can_add_related)
return formfield
for klass in db_field.__class__.mro():
if (klass in self.formfield_overrides):
kwargs = dict(copy.deepcopy(self.formfield_overrides[klass]), **kwargs)
return db_field.formfield(**kwargs)
return db_field.formfield(**kwargs)
|
'Get a form Field for a database Field that has declared choices.'
| def formfield_for_choice_field(self, db_field, request=None, **kwargs):
| if (db_field.name in self.radio_fields):
if ('widget' not in kwargs):
kwargs['widget'] = widgets.AdminRadioSelect(attrs={'class': get_ul_class(self.radio_fields[db_field.name])})
if ('choices' not in kwargs):
kwargs['choices'] = db_field.get_choices(include_blank=db_field.blank, blank_choice=[('', _('None'))])
return db_field.formfield(**kwargs)
|
'Get a form Field for a ForeignKey.'
| def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
| db = kwargs.get('using')
if (db_field.name in self.raw_id_fields):
kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, self.admin_site, using=db)
elif (db_field.name in self.radio_fields):
kwargs['widget'] = widgets.AdminRadioSelect(attrs={'class': get_ul_class(self.radio_fields[db_field.name])})
kwargs['empty_label'] = ((db_field.blank and _('None')) or None)
return db_field.formfield(**kwargs)
|
'Get a form Field for a ManyToManyField.'
| def formfield_for_manytomany(self, db_field, request=None, **kwargs):
| if (not db_field.rel.through._meta.auto_created):
return None
db = kwargs.get('using')
if (db_field.name in self.raw_id_fields):
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, self.admin_site, using=db)
kwargs['help_text'] = ''
elif (db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal))):
kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
return db_field.formfield(**kwargs)
|
'Hook for specifying field ordering.'
| def get_ordering(self, request):
| return (self.ordering or ())
|
'Hook for specifying custom readonly fields.'
| def get_readonly_fields(self, request, obj=None):
| return self.readonly_fields
|
'Hook for specifying custom prepopulated fields.'
| def get_prepopulated_fields(self, request, obj=None):
| return self.prepopulated_fields
|
'Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.'
| def queryset(self, request):
| qs = self.model._default_manager.get_query_set()
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
|
'Returns True if the given request has permission to add an object.
Can be overriden by the user in subclasses.'
| def has_add_permission(self, request):
| opts = self.opts
return request.user.has_perm(((opts.app_label + '.') + opts.get_add_permission()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.