Skip to content

Commit

Permalink
[1.2.X] Fixed #13149 -- The admin ForeignKeyRawIdWidget now properl…
Browse files Browse the repository at this point in the history
…y handles non-integer values. Thanks, Chris Adams.

Backport of r13751 from trunk.


git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.2.X@13752 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
jbronn committed Sep 11, 2010
1 parent f4ebd70 commit e4bd5e8
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
6 changes: 3 additions & 3 deletions django/contrib/admin/widgets.py
Expand Up @@ -154,9 +154,9 @@ def label_for_value(self, value):
key = self.rel.get_related_field().name
try:
obj = self.rel.to._default_manager.using(self.db).get(**{key: value})
except self.rel.to.DoesNotExist:
return '&nbsp;<strong>%s</strong>' % escape(truncate_words(obj, 14))
except (ValueError, self.rel.to.DoesNotExist):
return ''
return '&nbsp;<strong>%s</strong>' % escape(truncate_words(obj, 14))

class ManyToManyRawIdWidget(ForeignKeyRawIdWidget):
"""
Expand All @@ -169,7 +169,7 @@ def __init__(self, rel, attrs=None, using=None):
def render(self, name, value, attrs=None):
attrs['class'] = 'vManyToManyRawIdAdminField'
if value:
value = ','.join([str(v) for v in value])
value = ','.join([force_unicode(v) for v in value])
else:
value = ''
return super(ManyToManyRawIdWidget, self).render(name, value, attrs)
Expand Down
2 changes: 1 addition & 1 deletion django/forms/models.py
Expand Up @@ -996,7 +996,7 @@ def to_python(self, value):
try:
key = self.to_field_name or 'pk'
value = self.queryset.get(**{key: value})
except self.queryset.model.DoesNotExist:
except (ValueError, self.queryset.model.DoesNotExist):
raise ValidationError(self.error_messages['invalid_choice'])
return value

Expand Down
12 changes: 12 additions & 0 deletions tests/regressiontests/admin_widgets/tests.py
@@ -1,3 +1,5 @@
# encoding: utf-8

from django import forms
from django.contrib import admin
from django.contrib.admin import widgets
Expand Down Expand Up @@ -151,3 +153,13 @@ def test_nonexistent_target_id(self):
post_data)
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')

def test_invalid_target_id(self):

for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234):
# This should result in an error message, not a server exception.
response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root,
{"band": test_str})

self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')

0 comments on commit e4bd5e8

Please sign in to comment.