Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds extra_data support for AutoModelSelect2Field #17

Merged
merged 1 commit into from
Dec 13, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion django_select2/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,19 @@ def label_from_instance(self, obj):
"""
return smart_unicode(obj)

def extra_data_from_instance(self, obj):
"""
Sub-classes should override this to generate extra data for values. These are passed to
Javascript and can be used for custom rendering.

:param obj: The model object.
:type obj: :py:class:`django.model.Model`

:return: The extra data dictionary.
:rtype: :py:obj:`dict`
"""
return {}

def prepare_qs_params(self, request, search_term, search_fields):
"""
Prepares queryset parameter to use for searching.
Expand Down Expand Up @@ -246,7 +259,8 @@ def get_results(self, request, term, page, context):
res = list(qs.filter(*params['or'], **params['and']))
has_more = False

res = [(getattr(obj, self.to_field_name), self.label_from_instance(obj), ) for obj in res]
res = [(getattr(obj, self.to_field_name), self.label_from_instance(obj), self.extra_data_from_instance(obj))
for obj in res]
return (NO_ERR_RESP, has_more, res, )


Expand Down
9 changes: 7 additions & 2 deletions django_select2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,13 @@ def _results_to_context(self, output):
err, has_more, results = output
res = []
if err == NO_ERR_RESP:
for id_, text in results:
res.append({'id': id_, 'text': text})
for result in results:
id_, text = result[:2]
if len(result)>2:
extra_data = result[2]
else:
extra_data = {}
res.append(dict(id=id_, text=text, **extra_data))
return {
'err': err,
'more': has_more,
Expand Down