Permalink
Browse files

newforms-admin: Backwards-incompatible change: Refactored raw_id_admi…

…n. It is no longer a valid attribute for fields. Instead, specify 'raw_id_fields', a list of field names, in the 'class Admin'. Also removed raw_id functionality for ManyToManyFields, as it was hackish.

git-svn-id: http://code.djangoproject.com/svn/django/branches/newforms-admin@4430 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent 12ad69d commit 39e63513a8e74716d8fd98c23b6301e824c8e042 @adrianholovaty adrianholovaty committed Jan 25, 2007
@@ -1,4 +1,4 @@
-// Handles related-objects functionality: lookup link for raw_id_admin=True
+// Handles related-objects functionality: lookup link for raw_id_fields
// and Add Another links.
function showRelatedObjectLookupPopup(triggeringLink) {
@@ -108,6 +108,7 @@ class ModelAdmin(object):
ordering = None
js = None
fields = None
+ raw_id_fields = ()
def __init__(self, model):
self.model = model
@@ -224,12 +225,16 @@ def formfield_for_dbfield(self, db_field, **kwargs):
return db_field.formfield(**kwargs)
# For ForeignKey or ManyToManyFields, use a special widget.
- if db_field.rel and isinstance(db_field.rel, (models.ManyToOneRel, models.ManyToManyRel)):
- # Wrap the widget's render() method with a method that adds
- # extra HTML to the end of the rendered output.
- formfield = db_field.formfield(**kwargs)
- formfield.widget.render = widgets.RelatedFieldWidgetWrapper(formfield.widget.render, db_field.rel)
- return formfield
+ if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
+ if isinstance(db_field, models.ForeignKey) and db_field.name in self.raw_id_fields:
+ kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel)
+ return db_field.formfield(**kwargs)
+ else:
+ # Wrap the widget's render() method with a method that adds
+ # extra HTML to the end of the rendered output.
+ formfield = db_field.formfield(**kwargs)
+ formfield.widget.render = widgets.RelatedFieldWidgetWrapper(formfield.widget.render, db_field.rel)
+ return formfield
# For any other type of field, just call its formfield() method.
return db_field.formfield(**kwargs)
@@ -3,6 +3,8 @@
"""
from django import newforms as forms
+from django.newforms.util import smart_unicode
+from django.utils.text import capfirst
class FilteredSelectMultiple(forms.SelectMultiple):
"""
@@ -41,6 +43,33 @@ def format_output(self, rendered_widgets):
return u'<p class="datetime">%s %s<br />%s %s</p>' % \
(_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1])
+class ForeignKeyRawIdWidget(forms.TextInput):
+ """
+ A Widget for displaying ForeignKeys in the "raw_id" interface rather than
+ in a <select> box.
+ """
+ def __init__(self, rel, attrs=None):
+ self.rel = rel
+ super(ForeignKeyRawIdWidget, self).__init__(attrs)
+
+ def render(self, name, value, attrs=None):
+ from django.conf import settings
+ related_url = '../../../%s/%s/' % (self.rel.to._meta.app_label, self.rel.to._meta.object_name.lower())
+ if self.rel.limit_choices_to:
+ url = '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in self.rel.limit_choices_to.items()])
+ else:
+ url = ''
+ attrs['class'] = 'vRawIdAdminField' # The JavaScript looks for this hook.
+ output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)]
+ # TODO: "id_" is hard-coded here. This should instead use the correct
+ # API to determine the ID dynamically.
+ output.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % \
+ (related_url, url, name))
+ output.append('<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="Lookup"></a>' % settings.ADMIN_MEDIA_PREFIX)
+ return u''.join(output)
+ #if self.change: # TODO
+ #output.append('&nbsp;<strong>TODO</strong>')
+
class RelatedFieldWidgetWrapper(object):
"""
This class is a wrapper whose __call__() method mimics the interface of a
@@ -54,19 +83,7 @@ def __call__(self, name, value, *args, **kwargs):
rel_to = self.rel.to
related_url = '../../../%s/%s/' % (rel_to._meta.app_label, rel_to._meta.object_name.lower())
output = [self.render_func(name, value, *args, **kwargs)]
- if self.rel.raw_id_admin:
- if self.rel.limit_choices_to:
- url = '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in self.rel.limit_choices_to.items()])
- else:
- url = ''
- # TODO: "id_" is hard-coded here. This should instead use the correct
- # API to determine the ID dynamically.
- output.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % \
- (related_url, url, name))
- output.append('<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="Lookup"></a>' % settings.ADMIN_MEDIA_PREFIX)
- #if self.change: # TODO
- #output.append('&nbsp;<strong>TODO</strong>')
- elif rel_to._meta.admin: # If the related object has an admin interface:
+ if rel_to._meta.admin: # If the related object has an admin interface:
# TODO: "id_" is hard-coded here. This should instead use the correct
# API to determine the ID dynamically.
output.append(u'<a href="%sadd/" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
@@ -62,7 +62,7 @@ def user_is_moderator(self, user):
return False
class Comment(models.Model):
- user = models.ForeignKey(User, raw_id_admin=True)
+ user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.IntegerField(_('object ID'))
headline = models.CharField(_('headline'), maxlength=255, blank=True)
@@ -101,6 +101,7 @@ class Admin:
list_filter = ('submit_date',)
date_hierarchy = 'submit_date'
search_fields = ('comment', 'user__username')
+ raw_id_fields = ('user',)
def __repr__(self):
return "%s: %s..." % (self.user.username, self.comment[:100])
@@ -16,37 +16,37 @@ class GenericForeignKey(object):
Provides a generic relation to any object through content-type/object-id
fields.
"""
-
+
def __init__(self, ct_field="content_type", fk_field="object_id"):
self.ct_field = ct_field
self.fk_field = fk_field
-
+
def contribute_to_class(self, cls, name):
- # Make sure the fields exist (these raise FieldDoesNotExist,
+ # Make sure the fields exist (these raise FieldDoesNotExist,
# which is a fine error to raise here)
self.name = name
self.model = cls
self.cache_attr = "_%s_cache" % name
-
+
# For some reason I don't totally understand, using weakrefs here doesn't work.
dispatcher.connect(self.instance_pre_init, signal=signals.pre_init, sender=cls, weak=False)
# Connect myself as the descriptor for this field
setattr(cls, name, self)
def instance_pre_init(self, signal, sender, args, kwargs):
- # Handle initalizing an object with the generic FK instaed of
- # content-type/object-id fields.
+ # Handle initalizing an object with the generic FK instaed of
+ # content-type/object-id fields.
if kwargs.has_key(self.name):
value = kwargs.pop(self.name)
kwargs[self.ct_field] = self.get_content_type(value)
kwargs[self.fk_field] = value._get_pk_val()
-
+
def get_content_type(self, obj):
# Convenience function using get_model avoids a circular import when using this model
ContentType = get_model("contenttypes", "contenttype")
return ContentType.objects.get_for_model(obj)
-
+
def __get__(self, instance, instance_type=None):
if instance is None:
raise AttributeError, "%s must be accessed via instance" % self.name
@@ -77,21 +77,21 @@ def __set__(self, instance, value):
setattr(instance, self.ct_field, ct)
setattr(instance, self.fk_field, fk)
setattr(instance, self.cache_attr, value)
-
+
class GenericRelation(RelatedField, Field):
"""Provides an accessor to generic related objects (i.e. comments)"""
def __init__(self, to, **kwargs):
kwargs['verbose_name'] = kwargs.get('verbose_name', None)
- kwargs['rel'] = GenericRel(to,
+ kwargs['rel'] = GenericRel(to,
related_name=kwargs.pop('related_name', None),
limit_choices_to=kwargs.pop('limit_choices_to', None),
symmetrical=kwargs.pop('symmetrical', True))
-
+
# Override content-type/object-id field names on the related class
self.object_id_field_name = kwargs.pop("object_id_field", "object_id")
- self.content_type_field_name = kwargs.pop("content_type_field", "content_type")
-
+ self.content_type_field_name = kwargs.pop("content_type_field", "content_type")
+
kwargs['blank'] = True
kwargs['editable'] = False
Field.__init__(self, **kwargs)
@@ -115,7 +115,7 @@ def m2m_db_table(self):
def m2m_column_name(self):
return self.object_id_field_name
-
+
def m2m_reverse_name(self):
return self.object_id_field_name
@@ -130,13 +130,13 @@ def contribute_to_class(self, cls, name):
def contribute_to_related_class(self, cls, related):
pass
-
+
def set_attributes_from_rel(self):
pass
def get_internal_type(self):
return "ManyToManyField"
-
+
class ReverseGenericRelatedObjectsDescriptor(object):
"""
This class provides the functionality that makes the related-object
@@ -190,12 +190,12 @@ def create_generic_related_manager(superclass):
Factory function for a manager that subclasses 'superclass' (which is a
Manager) and adds behavior for generic related objects.
"""
-
+
class GenericRelatedObjectManager(superclass):
def __init__(self, model=None, core_filters=None, instance=None, symmetrical=None,
join_table=None, source_col_name=None, target_col_name=None, content_type=None,
content_type_field_name=None, object_id_field_name=None):
-
+
super(GenericRelatedObjectManager, self).__init__()
self.core_filters = core_filters or {}
self.model = model
@@ -209,10 +209,10 @@ def __init__(self, model=None, core_filters=None, instance=None, symmetrical=Non
self.content_type_field_name = content_type_field_name
self.object_id_field_name = object_id_field_name
self.pk_val = self.instance._get_pk_val()
-
+
def get_query_set(self):
query = {
- '%s__pk' % self.content_type_field_name : self.content_type.id,
+ '%s__pk' % self.content_type_field_name : self.content_type.id,
'%s__exact' % self.object_id_field_name : self.pk_val,
}
return superclass.get_query_set(self).filter(**query)
@@ -252,8 +252,5 @@ def __init__(self, to, related_name=None, limit_choices_to=None, symmetrical=Tru
self.filter_interface = None
self.limit_choices_to = limit_choices_to or {}
self.edit_inline = False
- self.raw_id_admin = False
self.symmetrical = symmetrical
self.multiple = True
- assert not (self.raw_id_admin and self.filter_interface), \
- "Generic relations may not use both raw_id_admin and filter_interface"
Oops, something went wrong.

0 comments on commit 39e6351

Please sign in to comment.