Hi
I am trying to get a lookup to display text (from a `code` field) for my Site
model in the autocomplete, but when the form returns the data to the view,
it should be the corresponding primary key.
# forms.py
site = forms.CharField(
widget=AutoCompleteWidget(SiteLookup),
label=_u('TREES_NEWINFUSION_SITE_name'),
required=False)
# lookup.py
class SiteLookup(ModelLookup):
model = Site
search_fields = (
'code__icontains',
'alias__icontains',
)
def get_item_id(self, item):
return item # FIRST ATTEMPT
try:
registry.register(SiteLookup)
except LookupAlreadyRegistered:
pass
Traceback (most recent call last):
File "/home/gamesbook/.virtualenvs/bldg/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gamesbook/.virtualenvs/bldg/local/lib/python2.7/site-packages/selectable/views.py", line 15, in get_lookup
return lookup.results(request)
File "/home/gamesbook/.virtualenvs/bldg/local/lib/python2.7/site-packages/selectable/base.py", line 103, in results
content = self.serialize_results(results)
File "/home/gamesbook/.virtualenvs/bldg/local/lib/python2.7/site-packages/selectable/base.py", line 128, in serialize_results
return json.dumps(results, cls=DjangoJSONEncoder, ensure_ascii=False)
File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/home/gamesbook/.virtualenvs/bldg/local/lib/python2.7/site-packages/django/core/serializers/json.py", line 104, in default
return super(DjangoJSONEncoder, self).default(o)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Site: ACCSO01> is not JSON serializable
But:
class SiteLookup(ModelLookup):
model = Site
search_fields = (
'code__icontains',
'alias__icontains',
)
def get_item_id(self, item):
try:
registry.register(SiteLookup)
except LookupAlreadyRegistered:
pass
Just returns the Site code as a string, and not the Site's ID value.
What is the correct combination to get back the data that I need?
Thanks
Derek