2008-07-19 07:54:34 +08:00
|
|
|
from django.db import models
|
2010-11-10 00:46:42 +08:00
|
|
|
from django.db.models.deletion import Collector
|
2010-10-17 23:17:52 +08:00
|
|
|
from django.db.models.related import RelatedObject
|
2010-04-11 16:35:04 +08:00
|
|
|
from django.forms.forms import pretty_name
|
2009-12-23 02:29:00 +08:00
|
|
|
from django.utils import formats
|
2008-07-19 07:54:34 +08:00
|
|
|
from django.utils.html import escape
|
|
|
|
from django.utils.safestring import mark_safe
|
|
|
|
from django.utils.text import capfirst
|
2009-12-23 02:29:00 +08:00
|
|
|
from django.utils.encoding import force_unicode, smart_unicode, smart_str
|
2010-10-12 09:03:53 +08:00
|
|
|
from django.utils.translation import ungettext
|
2009-03-24 04:22:56 +08:00
|
|
|
from django.core.urlresolvers import reverse, NoReverseMatch
|
2010-02-26 21:17:43 +08:00
|
|
|
from django.utils.datastructures import SortedDict
|
2009-12-23 02:29:00 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def quote(s):
|
|
|
|
"""
|
|
|
|
Ensure that primary key values do not confuse the admin URLs by escaping
|
|
|
|
any '/', '_' and ':' characters. Similar to urllib.quote, except that the
|
|
|
|
quoting is slightly different so that it doesn't get automatically
|
|
|
|
unquoted by the Web browser.
|
|
|
|
"""
|
|
|
|
if not isinstance(s, basestring):
|
|
|
|
return s
|
|
|
|
res = list(s)
|
|
|
|
for i in range(len(res)):
|
|
|
|
c = res[i]
|
|
|
|
if c in """:/_#?;@&=+$,"<>%\\""":
|
|
|
|
res[i] = '_%02X' % ord(c)
|
|
|
|
return ''.join(res)
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def unquote(s):
|
|
|
|
"""
|
|
|
|
Undo the effects of quote(). Based heavily on urllib.unquote().
|
|
|
|
"""
|
|
|
|
mychr = chr
|
|
|
|
myatoi = int
|
|
|
|
list = s.split('_')
|
|
|
|
res = [list[0]]
|
|
|
|
myappend = res.append
|
|
|
|
del list[0]
|
|
|
|
for item in list:
|
|
|
|
if item[1:2]:
|
|
|
|
try:
|
|
|
|
myappend(mychr(myatoi(item[:2], 16)) + item[2:])
|
|
|
|
except ValueError:
|
|
|
|
myappend('_' + item)
|
|
|
|
else:
|
|
|
|
myappend('_' + item)
|
|
|
|
return "".join(res)
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2008-08-18 23:49:58 +08:00
|
|
|
def flatten_fieldsets(fieldsets):
|
|
|
|
"""Returns a list of field names from an admin fieldsets structure."""
|
|
|
|
field_names = []
|
|
|
|
for name, opts in fieldsets:
|
|
|
|
for field in opts['fields']:
|
|
|
|
# type checking feels dirty, but it seems like the best way here
|
|
|
|
if type(field) == tuple:
|
|
|
|
field_names.extend(field)
|
|
|
|
else:
|
|
|
|
field_names.append(field)
|
|
|
|
return field_names
|
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def get_deleted_objects(objs, opts, user, admin_site, using):
|
2009-03-24 04:22:56 +08:00
|
|
|
"""
|
2010-11-10 00:46:42 +08:00
|
|
|
Find all objects related to ``objs`` that should also be deleted. ``objs``
|
|
|
|
must be a homogenous iterable of objects (e.g. a QuerySet).
|
2010-02-26 21:17:43 +08:00
|
|
|
|
|
|
|
Returns a nested list of strings suitable for display in the
|
|
|
|
template with the ``unordered_list`` filter.
|
2009-03-24 04:22:56 +08:00
|
|
|
|
|
|
|
"""
|
2010-11-10 00:46:42 +08:00
|
|
|
collector = NestedObjects(using=using)
|
|
|
|
collector.collect(objs)
|
2010-02-26 21:17:43 +08:00
|
|
|
perms_needed = set()
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def format_callback(obj):
|
|
|
|
has_admin = obj.__class__ in admin_site._registry
|
|
|
|
opts = obj._meta
|
2010-02-26 21:17:43 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
if has_admin:
|
|
|
|
admin_url = reverse('%s:%s_%s_change'
|
|
|
|
% (admin_site.name,
|
|
|
|
opts.app_label,
|
|
|
|
opts.object_name.lower()),
|
|
|
|
None, (quote(obj._get_pk_val()),))
|
|
|
|
p = '%s.%s' % (opts.app_label,
|
|
|
|
opts.get_delete_permission())
|
|
|
|
if not user.has_perm(p):
|
|
|
|
perms_needed.add(opts.verbose_name)
|
|
|
|
# Display a link to the admin page.
|
|
|
|
return mark_safe(u'%s: <a href="%s">%s</a>' %
|
|
|
|
(escape(capfirst(opts.verbose_name)),
|
|
|
|
admin_url,
|
|
|
|
escape(obj)))
|
|
|
|
else:
|
|
|
|
# Don't display link to edit, because it either has no
|
|
|
|
# admin or is edited inline.
|
|
|
|
return u'%s: %s' % (capfirst(opts.verbose_name),
|
|
|
|
force_unicode(obj))
|
2010-02-26 21:17:43 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
to_delete = collector.nested(format_callback)
|
2010-02-26 21:17:43 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
return to_delete, perms_needed
|
2010-02-26 21:17:43 +08:00
|
|
|
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
class NestedObjects(Collector):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(NestedObjects, self).__init__(*args, **kwargs)
|
|
|
|
self.edges = {} # {from_instance: [to_instances]}
|
2010-03-15 21:15:01 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def add_edge(self, source, target):
|
|
|
|
self.edges.setdefault(source, []).append(target)
|
2010-02-26 21:17:43 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def collect(self, objs, source_attr=None, **kwargs):
|
|
|
|
for obj in objs:
|
|
|
|
if source_attr:
|
|
|
|
self.add_edge(getattr(obj, source_attr), obj)
|
|
|
|
else:
|
|
|
|
self.add_edge(None, obj)
|
|
|
|
return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
|
2010-02-26 21:17:43 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def related_objects(self, related, objs):
|
|
|
|
qs = super(NestedObjects, self).related_objects(related, objs)
|
|
|
|
return qs.select_related(related.field.name)
|
2010-02-26 21:17:43 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def _nested(self, obj, seen, format_callback):
|
|
|
|
if obj in seen:
|
|
|
|
return []
|
|
|
|
seen.add(obj)
|
|
|
|
children = []
|
|
|
|
for child in self.edges.get(obj, ()):
|
|
|
|
children.extend(self._nested(child, seen, format_callback))
|
2010-02-26 21:17:43 +08:00
|
|
|
if format_callback:
|
2010-11-10 00:46:42 +08:00
|
|
|
ret = [format_callback(obj)]
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2010-02-26 21:17:43 +08:00
|
|
|
ret = [obj]
|
|
|
|
if children:
|
|
|
|
ret.append(children)
|
|
|
|
return ret
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def nested(self, format_callback=None):
|
2010-02-26 21:17:43 +08:00
|
|
|
"""
|
|
|
|
Return the graph as a nested list.
|
|
|
|
|
|
|
|
"""
|
2010-11-10 00:46:42 +08:00
|
|
|
seen = set()
|
2010-02-26 21:17:43 +08:00
|
|
|
roots = []
|
2010-11-10 00:46:42 +08:00
|
|
|
for root in self.edges.get(None, ()):
|
|
|
|
roots.extend(self._nested(root, seen, format_callback))
|
2010-02-26 21:17:43 +08:00
|
|
|
return roots
|
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
|
|
|
|
def model_format_dict(obj):
|
|
|
|
"""
|
|
|
|
Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
|
|
|
|
typically for use with string formatting.
|
|
|
|
|
|
|
|
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
|
|
|
|
|
|
|
|
"""
|
|
|
|
if isinstance(obj, (models.Model, models.base.ModelBase)):
|
|
|
|
opts = obj._meta
|
|
|
|
elif isinstance(obj, models.query.QuerySet):
|
|
|
|
opts = obj.model._meta
|
|
|
|
else:
|
|
|
|
opts = obj
|
|
|
|
return {
|
|
|
|
'verbose_name': force_unicode(opts.verbose_name),
|
|
|
|
'verbose_name_plural': force_unicode(opts.verbose_name_plural)
|
|
|
|
}
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
def model_ngettext(obj, n=None):
|
|
|
|
"""
|
2009-03-25 09:31:57 +08:00
|
|
|
Return the appropriate `verbose_name` or `verbose_name_plural` value for
|
|
|
|
`obj` depending on the count `n`.
|
2009-03-24 04:22:56 +08:00
|
|
|
|
|
|
|
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
|
|
|
|
If `obj` is a `QuerySet` instance, `n` is optional and the length of the
|
|
|
|
`QuerySet` is used.
|
|
|
|
|
|
|
|
"""
|
|
|
|
if isinstance(obj, models.query.QuerySet):
|
|
|
|
if n is None:
|
|
|
|
n = obj.count()
|
|
|
|
obj = obj.model
|
|
|
|
d = model_format_dict(obj)
|
2009-03-25 09:31:57 +08:00
|
|
|
singular, plural = d["verbose_name"], d["verbose_name_plural"]
|
|
|
|
return ungettext(singular, plural, n or 0)
|
2009-12-23 02:29:00 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2009-12-23 02:29:00 +08:00
|
|
|
def lookup_field(name, obj, model_admin=None):
|
|
|
|
opts = obj._meta
|
|
|
|
try:
|
|
|
|
f = opts.get_field(name)
|
|
|
|
except models.FieldDoesNotExist:
|
|
|
|
# For non-field values, the value is either a method, property or
|
|
|
|
# returned via a callable.
|
|
|
|
if callable(name):
|
|
|
|
attr = name
|
|
|
|
value = attr(obj)
|
|
|
|
elif (model_admin is not None and hasattr(model_admin, name) and
|
|
|
|
not name == '__str__' and not name == '__unicode__'):
|
|
|
|
attr = getattr(model_admin, name)
|
|
|
|
value = attr(obj)
|
|
|
|
else:
|
|
|
|
attr = getattr(obj, name)
|
|
|
|
if callable(attr):
|
|
|
|
value = attr()
|
|
|
|
else:
|
|
|
|
value = attr
|
|
|
|
f = None
|
|
|
|
else:
|
|
|
|
attr = None
|
2010-02-01 22:12:56 +08:00
|
|
|
value = getattr(obj, name)
|
2009-12-23 02:29:00 +08:00
|
|
|
return f, attr, value
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2010-01-10 11:36:59 +08:00
|
|
|
def label_for_field(name, model, model_admin=None, return_attr=False):
|
|
|
|
attr = None
|
2009-12-23 02:29:00 +08:00
|
|
|
try:
|
2010-10-17 23:17:52 +08:00
|
|
|
field = model._meta.get_field_by_name(name)[0]
|
|
|
|
if isinstance(field, RelatedObject):
|
|
|
|
label = field.opts.verbose_name
|
|
|
|
else:
|
|
|
|
label = field.verbose_name
|
2009-12-23 02:29:00 +08:00
|
|
|
except models.FieldDoesNotExist:
|
|
|
|
if name == "__unicode__":
|
2010-01-10 11:36:59 +08:00
|
|
|
label = force_unicode(model._meta.verbose_name)
|
|
|
|
elif name == "__str__":
|
|
|
|
label = smart_str(model._meta.verbose_name)
|
2009-12-23 02:29:00 +08:00
|
|
|
else:
|
2010-01-10 11:36:59 +08:00
|
|
|
if callable(name):
|
|
|
|
attr = name
|
|
|
|
elif model_admin is not None and hasattr(model_admin, name):
|
|
|
|
attr = getattr(model_admin, name)
|
|
|
|
elif hasattr(model, name):
|
|
|
|
attr = getattr(model, name)
|
|
|
|
else:
|
|
|
|
message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name)
|
|
|
|
if model_admin:
|
|
|
|
message += " or %s" % (model_admin.__name__,)
|
|
|
|
raise AttributeError(message)
|
2009-12-23 02:29:00 +08:00
|
|
|
|
2010-01-10 11:36:59 +08:00
|
|
|
if hasattr(attr, "short_description"):
|
|
|
|
label = attr.short_description
|
|
|
|
elif callable(attr):
|
|
|
|
if attr.__name__ == "<lambda>":
|
|
|
|
label = "--"
|
|
|
|
else:
|
2010-04-11 16:35:04 +08:00
|
|
|
label = pretty_name(attr.__name__)
|
2009-12-23 02:29:00 +08:00
|
|
|
else:
|
2010-04-11 16:35:04 +08:00
|
|
|
label = pretty_name(name)
|
2010-01-10 11:36:59 +08:00
|
|
|
if return_attr:
|
|
|
|
return (label, attr)
|
|
|
|
else:
|
|
|
|
return label
|
2009-12-23 02:29:00 +08:00
|
|
|
|
|
|
|
|
|
|
|
def display_for_field(value, field):
|
|
|
|
from django.contrib.admin.templatetags.admin_list import _boolean_icon
|
|
|
|
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
|
2010-01-10 05:28:54 +08:00
|
|
|
|
|
|
|
if field.flatchoices:
|
|
|
|
return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
|
2010-03-10 16:37:17 +08:00
|
|
|
# NullBooleanField needs special-case null-handling, so it comes
|
|
|
|
# before the general null test.
|
|
|
|
elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
|
|
|
|
return _boolean_icon(value)
|
2010-01-10 05:28:54 +08:00
|
|
|
elif value is None:
|
|
|
|
return EMPTY_CHANGELIST_VALUE
|
|
|
|
elif isinstance(field, models.DateField) or isinstance(field, models.TimeField):
|
2009-12-23 02:29:00 +08:00
|
|
|
return formats.localize(value)
|
|
|
|
elif isinstance(field, models.DecimalField):
|
|
|
|
return formats.number_format(value, field.decimal_places)
|
|
|
|
elif isinstance(field, models.FloatField):
|
|
|
|
return formats.number_format(value)
|
|
|
|
else:
|
|
|
|
return smart_unicode(value)
|