Templating autocompletes¶
This documentation drives through the example app
test_project/template_autocomplete
.
You can use AutocompleteTemplate
as a mixin
just like us:
class AutocompleteModelTemplate(AutocompleteModel, AutocompleteTemplate):
pass
You could also directly inherit from AutocompleteModelTemplate
.
Anyway, this enable two new attributes: choice_template
and autocomplete_template
Example¶
In this case, all you have to do, is use AutocompleteModelTemplate
instead
of AutocompleteModelBase
. For example, in
test_project/template_autocomplete/autocomplete_light_registry.py
:
import autocomplete_light
from models import TemplatedChoice
autocomplete_light.register(TemplatedChoice,
autocomplete_light.AutocompleteModelTemplate,
choice_template='template_autocomplete/templated_choice.html')
This example template makes choices clickable, it is
test_project/template_autocomplete/templates/template_autocomplete/templated_choice.html
:
<div data-value="{{ choice.pk }}">
<a href="{% url admin:template_autocomplete_templatedchoice_change choice.pk %}?_popup=1" target="_blank">
{{ choice }}
</a>
</div>
Alternative¶
FTR, here’s another way to do it, assuming your models have a get_absolute_update_url method defined:
class AutocompleteEditableModelBase(autocomplete_light.AutocompleteModelBase):
choice_html_format = u'''
<span class="div" data-value="%s">%s</span>
<a href="%s" title="%s"><img src="%s%s" /></a>
'''
def choice_html(self, choice):
"""
Return a choice formated according to self.choice_html_format.
"""
return self.choice_html_format % (
self.choice_value(choice), self.choice_label(choice),
choice.get_absolute_update_url(), _(u'Update'),
settings.STATIC_URL, 'admin/img/icon_changelink.gif')
autocomplete_light.register(AppCategory, AutocompleteEditableModelBase,
add_another_url_name='appstore_appcategory_create')
autocomplete_light.register(AppFeature, AutocompleteEditableModelBase,
add_another_url_name='appstore_appfeature_create')