├── __init__.py ├── example ├── views.py ├── __init__.py ├── urls.py ├── install.sh ├── manage.py ├── README.txt ├── forms.py ├── models.py ├── admin.py ├── lookups.py └── settings.py ├── .gitignore ├── ajax_select ├── models.py ├── static │ ├── images │ │ └── loading-indicator.gif │ ├── css │ │ └── ajax_select.css │ └── js │ │ └── ajax_select.js ├── LICENSE.txt ├── urls.py ├── admin.py ├── templates │ ├── ajax_select │ │ └── bootstrap.html │ ├── autocomplete.html │ ├── autocompleteselect.html │ └── autocompleteselectmultiple.html ├── views.py ├── __init__.py └── fields.py ├── MANIFEST.in ├── setup.py ├── OrderedManyToMany.md └── README.md /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /example/views.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /example/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.egg-info/ 3 | example/AJAXSELECTS/* -------------------------------------------------------------------------------- /ajax_select/models.py: -------------------------------------------------------------------------------- 1 | # blank file so django recognizes the app 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include ajax_select *.css *.py *.gif *.html *.txt *.js *.md 2 | recursive-include example *.py *.sh *.txt -------------------------------------------------------------------------------- /ajax_select/static/images/loading-indicator.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sjrd/django-ajax-selects/HEAD/ajax_select/static/images/loading-indicator.gif -------------------------------------------------------------------------------- /ajax_select/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009-2011 Chris Sattinger 2 | 3 | Dual licensed under the MIT and GPL licenses: 4 | http://www.opensource.org/licenses/mit-license.php 5 | http://www.gnu.org/licenses/gpl.html 6 | -------------------------------------------------------------------------------- /example/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls.defaults import * 2 | 3 | from django.contrib import admin 4 | from ajax_select import urls as ajax_select_urls 5 | 6 | admin.autodiscover() 7 | 8 | urlpatterns = patterns('', 9 | (r'^admin/lookups/', include(ajax_select_urls)), 10 | (r'^admin/', include(admin.site.urls)), 11 | ) 12 | -------------------------------------------------------------------------------- /ajax_select/urls.py: -------------------------------------------------------------------------------- 1 | 2 | from django.conf.urls.defaults import * 3 | 4 | 5 | urlpatterns = patterns('', 6 | url(r'^ajax_lookup/(?P[-\w]+)$', 7 | 'ajax_select.views.ajax_lookup', 8 | name = 'ajax_lookup' 9 | ), 10 | url(r'^add_popup/(?P\w+)/(?P\w+)$', 11 | 'ajax_select.views.add_popup', 12 | name = 'add_popup' 13 | ) 14 | ) 15 | 16 | -------------------------------------------------------------------------------- /ajax_select/admin.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from ajax_select.fields import autoselect_fields_check_can_add 4 | from django.contrib import admin 5 | 6 | 7 | class AjaxSelectAdmin(admin.ModelAdmin): 8 | 9 | """ in order to get + popup functions subclass this or do the same hook inside of your get_form """ 10 | 11 | def get_form(self, request, obj=None, **kwargs): 12 | form = super(AjaxSelectAdmin,self).get_form(request,obj,**kwargs) 13 | 14 | autoselect_fields_check_can_add(form,self.model,request.user) 15 | return form 16 | 17 | -------------------------------------------------------------------------------- /example/install.sh: -------------------------------------------------------------------------------- 1 | 2 | # creates a virtualenv and installs a django here 3 | virtualenv AJAXSELECTS 4 | source AJAXSELECTS/bin/activate 5 | easy_install django 6 | 7 | # put ajax selects in the path 8 | ln -s ../ajax_select/ ./ajax_select 9 | 10 | # create sqllite database 11 | ./manage.py syncdb 12 | 13 | echo "type 'source AJAXSELECTS/bin/activate' to activate the virtualenv" 14 | echo "then run: ./manage.py runserver" 15 | echo "and visit http://127.0.0.1:8000/admin/" 16 | echo "type 'deactivate' to close the virtualenv or just close the shell" 17 | 18 | -------------------------------------------------------------------------------- /example/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from django.core.management import execute_manager 3 | try: 4 | import settings # Assumed to be in the same directory. 5 | except ImportError: 6 | import sys 7 | sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) 8 | sys.exit(1) 9 | 10 | if __name__ == "__main__": 11 | execute_manager(settings) 12 | -------------------------------------------------------------------------------- /example/README.txt: -------------------------------------------------------------------------------- 1 | 2 | A test application to play with django-ajax-selects 3 | 4 | 5 | INSTALL ±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±± 6 | 7 | Install a local django in a virtualenv: 8 | 9 | ./install.sh 10 | 11 | This will also activate the virtualenv and create a sqlite db 12 | 13 | 14 | Run the server: 15 | 16 | ./manage.py runserver 17 | 18 | Go visit the admin site and play around: 19 | 20 | http://127.0.0.1:8000/admin 21 | 22 | 23 | DEACTIVATE ±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±± 24 | 25 | To deactiveate the virtualenv just close the shell or: 26 | 27 | deactivate 28 | 29 | 30 | REACTIVATE ±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±±± 31 | 32 | Reactivate it later: 33 | 34 | source AJAXSELECTS/bin/activate 35 | 36 | -------------------------------------------------------------------------------- /ajax_select/templates/ajax_select/bootstrap.html: -------------------------------------------------------------------------------- 1 | 15 | -------------------------------------------------------------------------------- /ajax_select/templates/autocomplete.html: -------------------------------------------------------------------------------- 1 | {% if bootstrap %}{% include "ajax_select/bootstrap.html" %}{% endif %} 2 | 3 | 23 | {% block help %}{% if help_text %}

{{ help_text }}

{% endif %}{% endblock %} 24 | {{ inline }} -------------------------------------------------------------------------------- /ajax_select/templates/autocompleteselect.html: -------------------------------------------------------------------------------- 1 | {% if bootstrap %}{% include "ajax_select/bootstrap.html" %}{% endif %} 2 | 3 | 4 | {% if add_link %} 5 | add 6 | {% endif %} 7 | 8 |
{{current_result|safe}}
9 | 21 | {% block help %}{% if help_text %}

{{help_text}}

{% endif %}{% endblock %} 22 |
23 | {{ inline }} -------------------------------------------------------------------------------- /ajax_select/templates/autocompleteselectmultiple.html: -------------------------------------------------------------------------------- 1 | {% if bootstrap %}{% include "ajax_select/bootstrap.html" %}{% endif %} 2 | 3 | {% if add_link %} 4 | add 5 | {% endif %} 6 | 7 |
8 | 21 | {# django admin adds the help text. this is for use outside of the admin #} 22 | {% block help %}{% if help_text %}

{{help_text}}

{% endif %}{% endblock %} 23 | {{ inline }} -------------------------------------------------------------------------------- /example/forms.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from django import forms 4 | from django.forms.models import ModelForm 5 | from ajax_select import make_ajax_field 6 | from example.models import Release 7 | 8 | 9 | class ReleaseForm(ModelForm): 10 | 11 | class Meta: 12 | model = Release 13 | 14 | # args: this model, fieldname on this model, lookup_channel_name 15 | group = make_ajax_field(Release,'group','group') 16 | 17 | # no help text at all 18 | label = make_ajax_field(Release,'label','label',help_text=None) 19 | 20 | # any extra kwargs are passed onto the field, so you may pass a custom help_text here 21 | songs = make_ajax_field(Release,'songs','song',help_text=u"Search for song by title") 22 | 23 | # if you are creating a form for use outside of the django admin to specify show_m2m_help=True : 24 | # label = make_ajax_field(Release,'label','label',show_m2m_help=True) 25 | # so that it will show the help text in manytomany fields 26 | 27 | title = make_ajax_field(Release,'title','cliche',help_text=u"Autocomplete will search the database for clichés about cats.") 28 | 29 | -------------------------------------------------------------------------------- /ajax_select/static/css/ajax_select.css: -------------------------------------------------------------------------------- 1 | 2 | .results_on_deck .ui-icon-trash { 3 | float: left; 4 | cursor: pointer; 5 | } 6 | .results_on_deck { 7 | padding: 0.25em 0; 8 | } 9 | .results_on_deck > div { 10 | margin-bottom: 0.5em; 11 | } 12 | .ui-autocomplete-loading { 13 | background: url('https://github.com/crucialfelix/django-ajax-selects/raw/master/ajax_select/static/images/loading-indicator.gif') no-repeat; 14 | background-origin: content-box; 15 | background-position: right; 16 | } 17 | ul.ui-autocomplete { 18 | /* 19 | this is the dropdown menu. 20 | max-width: 320px; 21 | 22 | if max-width is not set and you are using django-admin 23 | then the dropdown is the width of your whole page body (totally wrong). 24 | so set it in your own css to your preferred width of dropdown 25 | OR the ajax_select.js will automatically match it to the size of the text field 26 | which is what jquery's autocomplete does normally (but django's admin is breaking). 27 | tldr: it just works. set max-width if you want it wider 28 | */ 29 | margin: 0; 30 | padding: 0; 31 | } 32 | ul.ui-autocomplete li { 33 | list-style-type: none; 34 | padding: 0; 35 | } 36 | ul.ui-autocomplete li a { 37 | display: block; 38 | padding: 2px 3px; 39 | cursor: pointer; 40 | } 41 | -------------------------------------------------------------------------------- /example/models.py: -------------------------------------------------------------------------------- 1 | 2 | from django.db import models 3 | 4 | 5 | class Person(models.Model): 6 | 7 | """ an actual singular human being """ 8 | name = models.CharField(blank=True, max_length=100) 9 | email = models.EmailField() 10 | 11 | def __unicode__(self): 12 | return self.name 13 | 14 | 15 | class Group(models.Model): 16 | 17 | """ a music group """ 18 | 19 | name = models.CharField(max_length=200,unique=True) 20 | members = models.ManyToManyField(Person,blank=True,help_text="Enter text to search for and add each member of the group.") 21 | url = models.URLField(blank=True, verify_exists=False) 22 | 23 | def __unicode__(self): 24 | return self.name 25 | 26 | 27 | class Label(models.Model): 28 | 29 | """ a record label """ 30 | 31 | name = models.CharField(max_length=200,unique=True) 32 | owner = models.ForeignKey(Person,blank=True,null=True) 33 | url = models.URLField(blank=True, verify_exists=False) 34 | 35 | def __unicode__(self): 36 | return self.name 37 | 38 | 39 | class Song(models.Model): 40 | 41 | """ a song """ 42 | 43 | title = models.CharField(blank=False, max_length=200) 44 | group = models.ForeignKey(Group) 45 | 46 | def __unicode__(self): 47 | return self.title 48 | 49 | 50 | class Release(models.Model): 51 | 52 | """ a music release/product """ 53 | 54 | title = models.CharField(max_length=100) 55 | catalog = models.CharField(blank=True, max_length=100) 56 | 57 | group = models.ForeignKey(Group,blank=True,null=True) 58 | label = models.ForeignKey(Label,blank=False,null=False) 59 | songs = models.ManyToManyField(Song,blank=True) 60 | 61 | def __unicode__(self): 62 | return self.title 63 | 64 | 65 | 66 | class Author(models.Model): 67 | name = models.CharField(max_length=100) 68 | 69 | class Book(models.Model): 70 | author = models.ForeignKey(Author) 71 | title = models.CharField(max_length=100) 72 | about_group = models.ForeignKey(Group) 73 | mentions_persons = models.ManyToManyField(Person) 74 | 75 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from distutils.core import setup 4 | 5 | setup(name='django-ajax-selects', 6 | version='1.2.3', 7 | description='jQuery-powered auto-complete fields for editing ForeignKey, ManyToManyField and CharField', 8 | author='crucialfelix', 9 | author_email='crucialfelix@gmail.com', 10 | url='http://code.google.com/p/django-ajax-selects/', 11 | packages=['ajax_select', ], 12 | package_data={'ajax_select': ['*.py','*.txt','static/css/*','static/images/*','static/js/*','templates/*.html', 'templates/ajax_select/*.html']}, 13 | classifiers = [ 14 | "Programming Language :: Python", 15 | "Programming Language :: Python :: 2", 16 | "Development Status :: 5 - Production/Stable", 17 | 'Environment :: Web Environment', 18 | "Intended Audience :: Developers", 19 | "License :: OSI Approved :: MIT License", 20 | "Operating System :: OS Independent", 21 | "Topic :: Software Development :: Libraries :: Python Modules", 22 | "Topic :: Software Development :: User Interfaces", 23 | "Framework :: Django", 24 | ], 25 | long_description = """\ 26 | Enables editing of `ForeignKey`, `ManyToManyField` and `CharField` using jQuery UI AutoComplete. 27 | 28 | 1. The user types a search term into the text field 29 | 2. An ajax request is sent to the server. 30 | 3. The dropdown menu is populated with results. 31 | 4. User selects by clicking or using arrow keys 32 | 5. Selected result displays in the "deck" area directly below the input field. 33 | 6. User can click trashcan icon to remove a selected item 34 | 35 | + Django 1.2+ 36 | + Optional boostrap mode allows easy installation by automatic inclusion of jQueryUI from the googleapis CDN 37 | + Compatible with staticfiles, appmedia, django-compressor etc 38 | + Popup to add a new item is supported 39 | + Admin inlines now supported 40 | + Ajax Selects works in the admin and also in public facing forms. 41 | + Rich formatting can be easily defined for the dropdown display and the selected "deck" display. 42 | + Templates and CSS are fully customizable 43 | + JQuery triggers enable you to add javascript to respond when items are added or removed, so other interface elements on the page can react 44 | + Default (but customizable) security prevents griefers from pilfering your data via JSON requests 45 | 46 | """ 47 | ) 48 | -------------------------------------------------------------------------------- /example/admin.py: -------------------------------------------------------------------------------- 1 | 2 | from django.contrib import admin 3 | from ajax_select import make_ajax_form 4 | from ajax_select.admin import AjaxSelectAdmin 5 | from example.forms import ReleaseForm 6 | from example.models import * 7 | 8 | 9 | 10 | class PersonAdmin(admin.ModelAdmin): 11 | 12 | pass 13 | 14 | admin.site.register(Person,PersonAdmin) 15 | 16 | 17 | 18 | class LabelAdmin(AjaxSelectAdmin): 19 | """ to get + popup buttons, subclass AjaxSelectAdmin 20 | 21 | multi-inheritance is also possible if you have an Admin class you want to inherit from: 22 | 23 | class PersonAdmin(YourAdminSuperclass,AjaxSelectAdmin): 24 | 25 | this acts as a MixIn to add the relevant methods 26 | """ 27 | # this shows a ForeignKey field 28 | 29 | # create an ajax form class using the factory function 30 | # model,fieldlist, [form superclass] 31 | form = make_ajax_form(Label,{'owner':'person'}) 32 | 33 | admin.site.register(Label,LabelAdmin) 34 | 35 | 36 | 37 | class GroupAdmin(AjaxSelectAdmin): 38 | 39 | # this shows a ManyToMany field 40 | form = make_ajax_form(Group,{'members':'person'}) 41 | 42 | admin.site.register(Group,GroupAdmin) 43 | 44 | 45 | 46 | class SongAdmin(AjaxSelectAdmin): 47 | 48 | form = make_ajax_form(Song,{'group':'group','title':'cliche'}) 49 | 50 | admin.site.register(Song,SongAdmin) 51 | 52 | 53 | 54 | class ReleaseAdmin(AjaxSelectAdmin): 55 | 56 | # specify a form class manually (normal django way) 57 | # see forms.py 58 | form = ReleaseForm 59 | 60 | admin.site.register(Release,ReleaseAdmin) 61 | 62 | 63 | 64 | class BookInline(admin.TabularInline): 65 | 66 | model = Book 67 | form = make_ajax_form(Book,{'about_group':'group','mentions_persons':'person'},show_m2m_help=True) 68 | extra = 2 69 | 70 | # + check add still not working 71 | # no + appearing 72 | # def get_formset(self, request, obj=None, **kwargs): 73 | # from ajax_select.fields import autoselect_fields_check_can_add 74 | # fs = super(BookInline,self).get_formset(request,obj,**kwargs) 75 | # autoselect_fields_check_can_add(fs.form,self.model,request.user) 76 | # return fs 77 | 78 | class AuthorAdmin(admin.ModelAdmin): 79 | inlines = [ 80 | BookInline, 81 | ] 82 | 83 | admin.site.register(Author, AuthorAdmin) 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /ajax_select/views.py: -------------------------------------------------------------------------------- 1 | 2 | from ajax_select import get_lookup 3 | from django.contrib.admin import site 4 | from django.db import models 5 | from django.http import HttpResponse 6 | from django.utils import simplejson 7 | 8 | 9 | def ajax_lookup(request,channel): 10 | 11 | """ this view supplies results for foreign keys and many to many fields """ 12 | 13 | # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set 14 | # in which case we'll support POST 15 | if request.method == "GET": 16 | # we could also insist on an ajax request 17 | if 'term' not in request.GET: 18 | return HttpResponse('') 19 | query = request.GET['term'] 20 | else: 21 | if 'term' not in request.POST: 22 | return HttpResponse('') # suspicious 23 | query = request.POST['term'] 24 | 25 | lookup = get_lookup(channel) 26 | if hasattr(lookup,'check_auth'): 27 | lookup.check_auth(request) 28 | 29 | if len(query) >= getattr(lookup, 'min_length', 1): 30 | instances = lookup.get_query(query,request) 31 | else: 32 | instances = [] 33 | 34 | results = simplejson.dumps([ 35 | { 36 | 'pk': unicode(getattr(item,'pk',None)), 37 | 'value': lookup.get_result(item), 38 | 'match' : lookup.format_match(item), 39 | 'repr': lookup.format_item_display(item) 40 | } for item in instances 41 | ]) 42 | 43 | return HttpResponse(results, mimetype='application/javascript') 44 | 45 | 46 | def add_popup(request,app_label,model): 47 | """ this presents the admin site popup add view (when you click the green +) 48 | 49 | make sure that you have added ajax_select.urls to your urls.py: 50 | (r'^ajax_select/', include('ajax_select.urls')), 51 | this URL is expected in the code below, so it won't work under a different path 52 | 53 | this view then hijacks the result that the django admin returns 54 | and instead of calling django's dismissAddAnontherPopup(win,newId,newRepr) 55 | it calls didAddPopup(win,newId,newRepr) which was added inline with bootstrap.html 56 | """ 57 | themodel = models.get_model(app_label, model) 58 | admin = site._registry[themodel] 59 | 60 | # TODO : should detect where we really are 61 | admin.admin_site.root_path = "/ajax_select/" 62 | 63 | response = admin.add_view(request,request.path) 64 | if request.method == 'POST': 65 | if 'opener.dismissAddAnotherPopup' in response.content: 66 | return HttpResponse( response.content.replace('dismissAddAnotherPopup','didAddPopup' ) ) 67 | return response 68 | 69 | -------------------------------------------------------------------------------- /OrderedManyToMany.md: -------------------------------------------------------------------------------- 1 | 2 | Ordered ManyToMany fields without a full Through model 3 | ====================================================== 4 | 5 | When re-editing a previously saved model that has a ManyToMany field, the order of the recalled ids can be somewhat random. 6 | The user sees Arnold, Bosco, Cooly in the interface, saves, comes back later to edit it and he sees Bosco, Cooly, Arnold. So he files a bug report. 7 | 8 | A proper solution would be to use a separate Through model, an order field and the ability to drag the items in the interface to rearrange. But a proper Through model would also introduce extra fields and that would be out of the scope of ajax_selects. Maybe some future version. 9 | 10 | It is possible however to offer an intuitive experience for the user: save them in the order they added them and the next time they edit it they should see them in same order. 11 | 12 | Problem 13 | ------- 14 | 15 | class Agent(models.Model): 16 | name = models.CharField(blank=True, max_length=100) 17 | 18 | class Apartment(models.Model): 19 | agents = models.ManyToManyField(Agent) 20 | 21 | When the AutoCompleteSelectMultipleField saves it does so by saving each relationship in the order they were added in the interface. 22 | 23 | # this query does not have a guaranteed order (especially on postgres) 24 | # and certainly not the order that we added them 25 | apartment.agents.all() 26 | 27 | 28 | # this retrieves the joined objects in the order of their id (the join table id) 29 | # and thus gets them in the order they were added 30 | apartment.agents.through.objects.filter(apt=self).select_related('agent').order_by('id') 31 | 32 | 33 | Temporary Solution 34 | ------------------ 35 | 36 | class AgentOrderedManyToManyField(models.ManyToManyField): 37 | """ regardless of using a through class, 38 | only the Manager of the related field is used for fetching the objects for many to many interfaces. 39 | with postgres especially this means that the sort order is not determinable other than by the related field's manager. 40 | 41 | this fetches from the join table, then fetches the Agents in the fixed id order 42 | the admin ensures that the agents are always saved in the fixed id order that the form was filled out with 43 | """ 44 | def value_from_object(self,object): 45 | from company.models import Agent 46 | rel = getattr(object, self.attname) 47 | qry = {self.related.var_name:object} 48 | qs = rel.through.objects.filter(**qry).order_by('id') 49 | aids = qs.values_list('agent_id',flat=True) 50 | agents = dict( (a.pk,a) for a in Agent.objects.filter(pk__in=aids) ) 51 | try: 52 | return [agents[aid] for aid in aids ] 53 | except KeyError: 54 | raise Exception("Agent is missing: %s > %s" % (aids,agents)) 55 | 56 | class Apartment(models.Model): 57 | agents = AgentOrderedManyToManyField() 58 | 59 | 60 | class AgentLookup(object): 61 | 62 | def get_objects(self,ids): 63 | # now that we have a dependable ordering 64 | # we know the ids are in the order they were originally added 65 | # return models in original ordering 66 | ids = [int(id) for id in ids] 67 | agents = dict( (a.pk,a) for a in Agent.objects.filter(pk__in=ids) ) 68 | return [agents[aid] for aid in ids] 69 | 70 | -------------------------------------------------------------------------------- /ajax_select/static/js/ajax_select.js: -------------------------------------------------------------------------------- 1 | 2 | if(typeof jQuery.fn.autocompletehtml != 'function') { 3 | 4 | (function($) { 5 | 6 | function _init($deck,$text) { 7 | $text.autocompletehtml(); 8 | if($deck.parents(".module.aligned").length > 0) { 9 | // in django-admin, place deck directly below input 10 | $deck.position({ 11 | my: "right top", 12 | at: "right bottom", 13 | of: $text, 14 | offset: "0 5" 15 | }); 16 | } 17 | } 18 | $.fn.autocompletehtml = function() { 19 | var $text = $(this), sizeul = true; 20 | this.data("autocomplete")._renderItem = function _renderItemHTML(ul, item) { 21 | if(sizeul) { 22 | if(ul.css('max-width')=='none') ul.css('max-width',$text.outerWidth()); 23 | sizeul = false; 24 | } 25 | return $("
  • ") 26 | .data("item.autocomplete", item) 27 | .append("" + item.match + "") 28 | .appendTo(ul); 29 | }; 30 | return this; 31 | } 32 | $.fn.autocompleteselect = function(options) { 33 | 34 | return this.each(function() { 35 | var id = this.id; 36 | var $this = $(this); 37 | 38 | var $text = $("#"+id+"_text"); 39 | var $deck = $("#"+id+"_on_deck"); 40 | 41 | function receiveResult(event, ui) { 42 | if ($this.val()) { 43 | kill(); 44 | } 45 | $this.val(ui.item.pk); 46 | $text.val(''); 47 | addKiller(ui.item.repr); 48 | $deck.trigger("added"); 49 | 50 | return false; 51 | } 52 | 53 | function addKiller(repr,pk) { 54 | killer_id = "kill_" + pk + id; 55 | killButton = 'X '; 56 | if (repr) { 57 | $deck.empty(); 58 | $deck.append("
    " + killButton + repr + "
    "); 59 | } else { 60 | $("#"+id+"_on_deck > div").prepend(killButton); 61 | } 62 | $("#" + killer_id).click(function() { 63 | kill(); 64 | $deck.trigger("killed"); 65 | }); 66 | } 67 | 68 | function kill() { 69 | $this.val(''); 70 | $deck.children().fadeOut(1.0).remove(); 71 | } 72 | 73 | options.select = receiveResult; 74 | $text.autocomplete(options); 75 | _init($deck,$text); 76 | 77 | if (options.initial) { 78 | its = options.initial; 79 | addKiller(its[0], its[1]); 80 | } 81 | 82 | $this.bind('didAddPopup', function(event, pk, repr) { 83 | ui = { item: { pk: pk, repr: repr } } 84 | receiveResult(null, ui); 85 | }); 86 | }); 87 | }; 88 | 89 | $.fn.autocompleteselectmultiple = function(options) { 90 | return this.each(function() { 91 | var id = this.id; 92 | 93 | var $this = $(this); 94 | var $text = $("#"+id+"_text"); 95 | var $deck = $("#"+id+"_on_deck"); 96 | 97 | function receiveResult(event, ui) { 98 | pk = ui.item.pk; 99 | prev = $this.val(); 100 | 101 | if (prev.indexOf("|"+pk+"|") == -1) { 102 | $this.val((prev ? prev : "|") + pk + "|"); 103 | addKiller(ui.item.repr, pk); 104 | $text.val(''); 105 | $deck.trigger("added"); 106 | } 107 | 108 | return false; 109 | } 110 | 111 | function addKiller(repr, pk) { 112 | killer_id = "kill_" + pk + id; 113 | killButton = 'X '; 114 | $deck.append('
    ' + killButton + repr + '
    '); 115 | 116 | $("#"+killer_id).click(function() { 117 | kill(pk); 118 | $deck.trigger("killed"); 119 | }); 120 | } 121 | 122 | function kill(pk) { 123 | $this.val($this.val().replace("|" + pk + "|", "|")); 124 | $("#"+id+"_on_deck_"+pk).fadeOut().remove(); 125 | } 126 | 127 | options.select = receiveResult; 128 | $text.autocomplete(options); 129 | _init($deck,$text); 130 | 131 | if (options.initial) { 132 | $.each(options.initial, function(i, its) { 133 | addKiller(its[0], its[1]); 134 | }); 135 | } 136 | 137 | $this.bind('didAddPopup', function(event, pk, repr) { 138 | ui = { item: { pk: pk, repr: repr } } 139 | receiveResult(null, ui); 140 | }); 141 | }); 142 | }; 143 | })(jQuery); 144 | 145 | function addAutoComplete(prefix_id, callback/*(html_id)*/) { 146 | /* detects inline forms and converts the html_id if needed */ 147 | var prefix = 0; 148 | var html_id = prefix_id; 149 | if(html_id.indexOf("__prefix__") != -1) { 150 | // Some dirty loop to find the appropriate element to apply the callback to 151 | while (jQuery('#'+html_id).length) { 152 | html_id = prefix_id.replace(/__prefix__/, prefix++); 153 | } 154 | html_id = prefix_id.replace(/__prefix__/, prefix-2); 155 | // Ignore the first call to this function, the one that is triggered when 156 | // page is loaded just because the "empty" form is there. 157 | if (jQuery("#"+html_id+", #"+html_id+"_text").hasClass("ui-autocomplete-input")) 158 | return; 159 | } 160 | callback(html_id); 161 | } 162 | /* the popup handler 163 | requires RelatedObjects.js which is part of the django admin js 164 | so if using outside of the admin then you would need to include that manually */ 165 | function didAddPopup(win,newId,newRepr) { 166 | var name = windowname_to_id(win.name); 167 | jQuery("#"+name).trigger('didAddPopup',[html_unescape(newId),html_unescape(newRepr)]); 168 | win.close(); 169 | } 170 | } -------------------------------------------------------------------------------- /example/lookups.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from django.db.models import Q 4 | from django.utils.html import escape 5 | from example.models import * 6 | from ajax_select import LookupChannel 7 | 8 | 9 | class PersonLookup(LookupChannel): 10 | 11 | model = Person 12 | 13 | def get_query(self,q,request): 14 | return Person.objects.filter(Q(name__icontains=q) | Q(email__istartswith=q)).order_by('name') 15 | 16 | def get_result(self,obj): 17 | u""" result is the simple text that is the completion of what the person typed """ 18 | return obj.name 19 | 20 | def format_match(self,obj): 21 | """ (HTML) formatted item for display in the dropdown """ 22 | return self.format_item_display(obj) 23 | 24 | def format_item_display(self,obj): 25 | """ (HTML) formatted item for displaying item in the selected deck area """ 26 | return u"%s
    %s
    " % (escape(obj.name),escape(obj.email)) 27 | 28 | 29 | 30 | class GroupLookup(LookupChannel): 31 | 32 | model = Group 33 | 34 | def get_query(self,q,request): 35 | return Group.objects.filter(name__icontains=q).order_by('name') 36 | 37 | def get_result(self,obj): 38 | return unicode(obj) 39 | 40 | def format_match(self,obj): 41 | return self.format_item_display(obj) 42 | 43 | def format_item_display(self,obj): 44 | return u"%s
    %s
    " % (escape(obj.name),escape(obj.url)) 45 | 46 | def can_add(self,user,model): 47 | """ customize can_add by allowing anybody to add a Group. 48 | the superclass implementation uses django's permissions system to check. 49 | only those allowed to add will be offered a [+ add] popup link 50 | """ 51 | return True 52 | 53 | 54 | class SongLookup(LookupChannel): 55 | 56 | model = Song 57 | 58 | def get_query(self,q,request): 59 | return Song.objects.filter(title__icontains=q).select_related('group').order_by('title') 60 | 61 | def get_result(self,obj): 62 | return unicode(obj.title) 63 | 64 | def format_match(self,obj): 65 | return self.format_item_display(obj) 66 | 67 | def format_item_display(self,obj): 68 | return "%s
    by %s
    " % (escape(obj.title),escape(obj.group.name)) 69 | 70 | 71 | 72 | class ClicheLookup(LookupChannel): 73 | 74 | """ an autocomplete lookup does not need to search models 75 | though the words here could also be stored in a model and 76 | searched as in the lookups above 77 | """ 78 | 79 | words = [ 80 | u"rain cats and dogs", 81 | u"quick as a cat", 82 | u"there's more than one way to skin a cat", 83 | u"let the cat out of the bag", 84 | u"fat cat", 85 | u"the early bird catches the worm", 86 | u"catch as catch can", 87 | u"you can catch more flies with honey than with vinegar", 88 | u"catbird seat", 89 | u"cat's paw", 90 | u"cat's meow", 91 | u"has the cat got your tongue?", 92 | u"busy as a cat on a hot tin roof", 93 | u"who'll bell the cat", 94 | u"cat's ass", 95 | u"more nervous than a long tailed cat in a room full of rocking chairs", 96 | u"all cats are grey in the dark", 97 | u"nervous as a cat in a room full of rocking chairs", 98 | u"can't a cat look at a queen?", 99 | u"curiosity killed the cat", 100 | u"cat's pajamas", 101 | u"look what the cat dragged in", 102 | u"while the cat's away the mice will play", 103 | u"Nervous as a cat in a room full of rocking chairs", 104 | u"Slicker than cat shit on a linoleum floor", 105 | u"there's more than one way to kill a cat than choking it with butter.", 106 | u"you can't swing a dead cat without hitting one", 107 | u"The cat's whisker", 108 | u"looking like the cat who swallowed the canary", 109 | u"not enough room to swing a cat", 110 | u"It's raining cats and dogs", 111 | u"He was on that like a pack of dogs on a three-legged cat.", 112 | u"like two tomcats in a gunny sack", 113 | u"I don't know your from adam's house cat!", 114 | u"nervous as a long tailed cat in a living room full of rockers", 115 | u"Busier than a three legged cat in a dry sand box.", 116 | u"Busier than a one-eyed cat watching two mouse holes.", 117 | u"kick the dog and cat", 118 | u"there's more than one way to kill a cat than to drown it in cream", 119 | u"how many ways can you skin a cat?", 120 | u"Looks like a black cat with a red bird in its mouth", 121 | u"Morals of an alley cat and scruples of a snake.", 122 | u"hotter than a six peckered alley cat", 123 | u"when the cats are away the mice will play", 124 | u"you can catch more flies with honey than vinegar", 125 | u"when the cat's away, the mice will play", 126 | u"Who opened the cattleguard?", 127 | u"your past might catch up with you", 128 | u"ain't that just the cats pyjamas", 129 | u"A Cat has nine lives", 130 | u"a cheshire-cat smile", 131 | u"cat's pajamas", 132 | u"cat got your tongue?"] 133 | 134 | def get_query(self,q,request): 135 | return sorted([w for w in self.words if q in w]) 136 | 137 | def get_result(self,obj): 138 | return obj 139 | 140 | def format_match(self,obj): 141 | return escape(obj) 142 | 143 | def format_item_display(self,obj): 144 | return escape(obj) 145 | 146 | -------------------------------------------------------------------------------- /example/settings.py: -------------------------------------------------------------------------------- 1 | # Django settings for example project. 2 | 3 | ########################################################################### 4 | 5 | INSTALLED_APPS = ( 6 | 'django.contrib.auth', 7 | 'django.contrib.contenttypes', 8 | 'django.contrib.sessions', 9 | 'django.contrib.sites', 10 | 'django.contrib.admin', 11 | 'example', 12 | 13 | #################################### 14 | 'ajax_select', # <- add the app 15 | #################################### 16 | ) 17 | 18 | 19 | ########################################################################### 20 | 21 | # DEFINE THE SEARCH CHANNELS: 22 | 23 | AJAX_LOOKUP_CHANNELS = { 24 | # simplest way, automatically construct a search channel by passing a dictionary 25 | 'label' : {'model':'example.label', 'search_field':'name'}, 26 | 27 | # Custom channels are specified with a tuple 28 | # channel: ( module.where_lookup_is, ClassNameOfLookup ) 29 | 'person' : ('example.lookups', 'PersonLookup'), 30 | 'group' : ('example.lookups', 'GroupLookup'), 31 | 'song' : ('example.lookups', 'SongLookup'), 32 | 'cliche' : ('example.lookups','ClicheLookup') 33 | } 34 | 35 | 36 | AJAX_SELECT_BOOTSTRAP = True 37 | # True: [easiest] 38 | # use the admin's jQuery if present else load from jquery's CDN 39 | # use jqueryUI if present else load from jquery's CDN 40 | # use jqueryUI theme if present else load one from jquery's CDN 41 | # False/None/Not set: [default] 42 | # you should include jQuery, jqueryUI + theme in your template 43 | 44 | 45 | AJAX_SELECT_INLINES = 'inline' 46 | # 'inline': [easiest] 47 | # includes the js and css inline 48 | # this gets you up and running easily 49 | # but on large admin pages or with higher traffic it will be a bit wasteful. 50 | # 'staticfiles': 51 | # @import the css/js from {{STATIC_URL}}/ajax_selects using django's staticfiles app 52 | # requires staticfiles to be installed and to run its management command to collect files 53 | # this still includes the css/js multiple times and is thus inefficient 54 | # but otherwise harmless 55 | # False/None: [default] 56 | # does not inline anything. include the css/js files in your compressor stack 57 | # or include them in the head of the admin/base_site.html template 58 | # this is the most efficient but takes the longest to configure 59 | 60 | # when using staticfiles you may implement your own ajax_select.css and customize to taste 61 | 62 | 63 | 64 | ########################################################################### 65 | 66 | # STANDARD CONFIG SETTINGS ############################################### 67 | 68 | 69 | DEBUG = True 70 | TEMPLATE_DEBUG = DEBUG 71 | 72 | ADMINS = ( 73 | # ('Your Name', 'your_email@domain.com'), 74 | ) 75 | 76 | MANAGERS = ADMINS 77 | 78 | DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 79 | DATABASE_NAME = 'ajax_selects_example' # Or path to database file if using sqlite3. 80 | DATABASE_USER = '' # Not used with sqlite3. 81 | DATABASE_PASSWORD = '' # Not used with sqlite3. 82 | DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. 83 | DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. 84 | 85 | DATABASES = { 86 | 'default': { 87 | 'ENGINE': 'django.db.backends.sqlite3', 88 | 'NAME': 'ajax_selects_example' 89 | } 90 | } 91 | 92 | # Local time zone for this installation. Choices can be found here: 93 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 94 | # although not all choices may be available on all operating systems. 95 | # If running in a Windows environment this must be set to the same as your 96 | # system time zone. 97 | TIME_ZONE = 'America/Chicago' 98 | 99 | # Language code for this installation. All choices can be found here: 100 | # http://www.i18nguy.com/unicode/language-identifiers.html 101 | LANGUAGE_CODE = 'en-us' 102 | 103 | SITE_ID = 1 104 | 105 | # If you set this to False, Django will make some optimizations so as not 106 | # to load the internationalization machinery. 107 | USE_I18N = False 108 | 109 | # Absolute path to the directory that holds media. 110 | # Example: "/home/media/media.lawrence.com/" 111 | MEDIA_ROOT = '' 112 | 113 | # URL that handles the media served from MEDIA_ROOT. Make sure to use a 114 | # trailing slash if there is a path component (optional in other cases). 115 | # Examples: "http://media.lawrence.com", "http://example.com/media/" 116 | MEDIA_URL = '' 117 | 118 | # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a 119 | # trailing slash. 120 | # Examples: "http://foo.com/media/", "/media/". 121 | ADMIN_MEDIA_PREFIX = '/media/' 122 | 123 | # Make this unique, and don't share it with nobody. 124 | SECRET_KEY = '=9fhrrwrazha6r_m)r#+in*@n@i322ubzy4r+zz%wz$+y(=qpb' 125 | 126 | # List of callables that know how to import templates from various sources. 127 | TEMPLATE_LOADERS = ( 128 | 'django.template.loaders.filesystem.load_template_source', 129 | 'django.template.loaders.app_directories.load_template_source', 130 | # 'django.template.loaders.eggs.load_template_source', 131 | ) 132 | 133 | MIDDLEWARE_CLASSES = ( 134 | 'django.middleware.common.CommonMiddleware', 135 | 'django.contrib.sessions.middleware.SessionMiddleware', 136 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 137 | ) 138 | 139 | ROOT_URLCONF = 'example.urls' 140 | 141 | TEMPLATE_DIRS = ( 142 | # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 143 | # Always use forward slashes, even on Windows. 144 | # Don't forget to use absolute paths, not relative paths. 145 | ) 146 | -------------------------------------------------------------------------------- /ajax_select/__init__.py: -------------------------------------------------------------------------------- 1 | """JQuery-Ajax Autocomplete fields for Django Forms""" 2 | __version__ = "1.2" 3 | __author__ = "crucialfelix" 4 | __contact__ = "crucialfelix@gmail.com" 5 | __homepage__ = "http://code.google.com/p/django-ajax-selects/" 6 | 7 | from django.conf import settings 8 | from django.core.exceptions import ImproperlyConfigured, PermissionDenied 9 | from django.db.models.fields.related import ForeignKey, ManyToManyField 10 | from django.contrib.contenttypes.models import ContentType 11 | from django.forms.models import ModelForm 12 | from django.utils.text import capfirst 13 | from django.utils.translation import ugettext_lazy as _, ugettext 14 | 15 | 16 | class LookupChannel(object): 17 | 18 | """Subclass this, setting model and overiding the methods below to taste""" 19 | 20 | model = None 21 | min_length = 1 22 | 23 | def get_query(self,q,request): 24 | """ return a query set searching for the query string q 25 | either implement this method yourself or set the search_field 26 | in the LookupChannel class definition 27 | """ 28 | kwargs = { "%s__icontains" % self.search_field : q } 29 | return self.model.objects.filter(**kwargs).order_by(self.search_field) 30 | 31 | def get_result(self,obj): 32 | """ The text result of autocompleting the entered query """ 33 | return unicode(obj) 34 | 35 | def format_match(self,obj): 36 | """ (HTML) formatted item for displaying item in the dropdown """ 37 | return unicode(obj) 38 | 39 | def format_item_display(self,obj): 40 | """ (HTML) formatted item for displaying item in the selected deck area """ 41 | return unicode(obj) 42 | 43 | def get_objects(self,ids): 44 | """ Get the currently selected objects when editing an existing model """ 45 | # return in the same order as passed in here 46 | # this will be however the related objects Manager returns them 47 | # which is not guaranteed to be the same order they were in when you last edited 48 | # see OrdredManyToMany.md 49 | ids = [int(id) for id in ids] 50 | things = self.model.objects.in_bulk(ids) 51 | return [things[aid] for aid in ids if things.has_key(aid)] 52 | 53 | def can_add(self,user,argmodel): 54 | """ Check if the user has permission to add 55 | one of these models. This enables the green popup + 56 | Default is the standard django permission check 57 | """ 58 | ctype = ContentType.objects.get_for_model(argmodel) 59 | return user.has_perm("%s.add_%s" % (ctype.app_label,ctype.model)) 60 | 61 | def check_auth(self,request): 62 | """ to ensure that nobody can get your data via json simply by knowing the URL. 63 | public facing forms should write a custom LookupChannel to implement as you wish. 64 | also you could choose to return HttpResponseForbidden("who are you?") 65 | instead of raising PermissionDenied (401 response) 66 | """ 67 | if not request.user.is_staff: 68 | raise PermissionDenied 69 | 70 | 71 | 72 | def make_ajax_form(model,fieldlist,superclass=ModelForm,show_m2m_help=False): 73 | """ Creates a ModelForm subclass with autocomplete fields 74 | 75 | usage: 76 | class YourModelAdmin(Admin): 77 | ... 78 | form = make_ajax_form(YourModel,{'contacts':'contact','author':'contact'}) 79 | 80 | where 81 | 'contacts' is a ManyToManyField specifying to use the lookup channel 'contact' 82 | and 83 | 'author' is a ForeignKeyField specifying here to also use the lookup channel 'contact' 84 | """ 85 | 86 | class TheForm(superclass): 87 | 88 | class Meta: 89 | pass 90 | setattr(Meta, 'model', model) 91 | 92 | for model_fieldname,channel in fieldlist.iteritems(): 93 | f = make_ajax_field(model,model_fieldname,channel,show_m2m_help) 94 | 95 | TheForm.declared_fields[model_fieldname] = f 96 | TheForm.base_fields[model_fieldname] = f 97 | setattr(TheForm,model_fieldname,f) 98 | 99 | return TheForm 100 | 101 | 102 | def make_ajax_field(model,model_fieldname,channel,show_m2m_help = False,**kwargs): 103 | """ Makes a single autocomplete field for use in a Form 104 | 105 | optional args: 106 | help_text - default is the model field's help_text 107 | label - default is the model field's verbose name 108 | required - default is the model field's (not) blank 109 | 110 | show_m2m_help - 111 | Django will show help text in the Admin for ManyToMany fields, 112 | in which case the help text should not be shown in side the widget itself 113 | or it appears twice. 114 | 115 | ForeignKey fields do not behave like this. 116 | ManyToMany inside of admin inlines do not do this. [so set show_m2m_help=True] 117 | 118 | But if used outside of the Admin or in an ManyToMany admin inline then you need the help text. 119 | """ 120 | 121 | from ajax_select.fields import AutoCompleteField, \ 122 | AutoCompleteSelectMultipleField, \ 123 | AutoCompleteSelectField 124 | 125 | field = model._meta.get_field(model_fieldname) 126 | if kwargs.has_key('label'): 127 | label = kwargs.pop('label') 128 | else: 129 | label = _(capfirst(unicode(field.verbose_name))) 130 | 131 | if kwargs.has_key('help_text'): 132 | help_text = kwargs.pop('help_text') 133 | else: 134 | if isinstance(field.help_text,basestring) and field.help_text: 135 | help_text = _(field.help_text) 136 | else: 137 | help_text = field.help_text 138 | if kwargs.has_key('required'): 139 | required = kwargs.pop('required') 140 | else: 141 | required = not field.blank 142 | 143 | if isinstance(field,ManyToManyField): 144 | kwargs['show_help_text'] = show_m2m_help 145 | f = AutoCompleteSelectMultipleField( 146 | channel, 147 | required=required, 148 | help_text=help_text, 149 | label=label, 150 | **kwargs 151 | ) 152 | elif isinstance(field,ForeignKey): 153 | f = AutoCompleteSelectField( 154 | channel, 155 | required=required, 156 | help_text=help_text, 157 | label=label, 158 | **kwargs 159 | ) 160 | else: 161 | f = AutoCompleteField( 162 | channel, 163 | required=required, 164 | help_text=help_text, 165 | label=label, 166 | **kwargs 167 | ) 168 | return f 169 | 170 | 171 | #################### private ################################################## 172 | 173 | def get_lookup(channel): 174 | """ find the lookup class for the named channel. this is used internally """ 175 | try: 176 | lookup_label = settings.AJAX_LOOKUP_CHANNELS[channel] 177 | except AttributeError: 178 | raise ImproperlyConfigured("settings.AJAX_LOOKUP_CHANNELS is not configured") 179 | except KeyError: 180 | raise ImproperlyConfigured("settings.AJAX_LOOKUP_CHANNELS not configured correctly for %r" % channel) 181 | 182 | if isinstance(lookup_label,dict): 183 | # 'channel' : dict(model='app.model', search_field='title' ) 184 | # generate a simple channel dynamically 185 | return make_channel( lookup_label['model'], lookup_label['search_field'] ) 186 | else: # a tuple 187 | # 'channel' : ('app.module','LookupClass') 188 | # from app.module load LookupClass and instantiate 189 | lookup_module = __import__( lookup_label[0],{},{},['']) 190 | lookup_class = getattr(lookup_module,lookup_label[1] ) 191 | 192 | # monkeypatch older lookup classes till 1.3 193 | if not hasattr(lookup_class,'format_match'): 194 | setattr(lookup_class, 'format_match', 195 | getattr(lookup_class,'format_item', 196 | lambda self,obj: unicode(obj))) 197 | if not hasattr(lookup_class,'format_item_display'): 198 | setattr(lookup_class, 'format_item_display', 199 | getattr(lookup_class,'format_item', 200 | lambda self,obj: unicode(obj))) 201 | if not hasattr(lookup_class,'get_result'): 202 | setattr(lookup_class, 'get_result', 203 | getattr(lookup_class,'format_result', 204 | lambda self,obj: unicode(obj))) 205 | 206 | return lookup_class() 207 | 208 | 209 | def make_channel(app_model,arg_search_field): 210 | """ used in get_lookup 211 | app_model : app_name.model_name 212 | search_field : the field to search against and to display in search results 213 | """ 214 | from django.db import models 215 | app_label, model_name = app_model.split(".") 216 | themodel = models.get_model(app_label, model_name) 217 | 218 | class MadeLookupChannel(LookupChannel): 219 | 220 | model = themodel 221 | search_field = arg_search_field 222 | 223 | return MadeLookupChannel() 224 | 225 | 226 | -------------------------------------------------------------------------------- /ajax_select/fields.py: -------------------------------------------------------------------------------- 1 | 2 | from ajax_select import get_lookup 3 | from django import forms 4 | from django.conf import settings 5 | from django.contrib.contenttypes.models import ContentType 6 | from django.core.urlresolvers import reverse 7 | from django.forms.util import flatatt 8 | from django.template.defaultfilters import escapejs 9 | from django.template.loader import render_to_string 10 | from django.utils.safestring import mark_safe 11 | from django.utils.translation import ugettext as _ 12 | import os 13 | 14 | 15 | 16 | #################################################################################### 17 | 18 | class AutoCompleteSelectWidget(forms.widgets.TextInput): 19 | 20 | """ widget to select a model and return it as text """ 21 | 22 | add_link = None 23 | 24 | def __init__(self, 25 | channel, 26 | help_text='', 27 | *args, **kw): 28 | super(forms.widgets.TextInput, self).__init__(*args, **kw) 29 | self.channel = channel 30 | self.help_text = help_text 31 | 32 | def render(self, name, value, attrs=None): 33 | 34 | value = value or '' 35 | final_attrs = self.build_attrs(attrs) 36 | self.html_id = final_attrs.pop('id', name) 37 | 38 | lookup = get_lookup(self.channel) 39 | if value: 40 | objs = lookup.get_objects([value]) 41 | try: 42 | obj = objs[0] 43 | except IndexError: 44 | raise Exception("%s cannot find object:%s" % (lookup, value)) 45 | display = lookup.format_item_display(obj) 46 | current_repr = mark_safe( """new Array("%s",%s)""" % (escapejs(display),obj.pk) ) 47 | else: 48 | current_repr = 'null' 49 | 50 | context = { 51 | 'name': name, 52 | 'html_id' : self.html_id, 53 | 'min_length': getattr(lookup, 'min_length', 1), 54 | 'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}), 55 | 'current_id': value, 56 | 'current_repr': current_repr, 57 | 'help_text': self.help_text, 58 | 'extra_attrs': mark_safe(flatatt(final_attrs)), 59 | 'func_slug': self.html_id.replace("-",""), 60 | 'add_link' : self.add_link, 61 | } 62 | context.update(bootstrap()) 63 | 64 | return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context)) 65 | 66 | def value_from_datadict(self, data, files, name): 67 | 68 | got = data.get(name, None) 69 | if got: 70 | return long(got) 71 | else: 72 | return None 73 | 74 | def id_for_label(self, id_): 75 | return '%s_text' % id_ 76 | 77 | 78 | 79 | class AutoCompleteSelectField(forms.fields.CharField): 80 | 81 | """ form field to select a model for a ForeignKey db field """ 82 | 83 | channel = None 84 | 85 | def __init__(self, channel, *args, **kwargs): 86 | self.channel = channel 87 | widget = kwargs.get("widget", False) 88 | 89 | if not widget or not isinstance(widget, AutoCompleteSelectWidget): 90 | kwargs["widget"] = AutoCompleteSelectWidget(channel=channel,help_text=kwargs.get('help_text',_('Enter text to search.'))) 91 | super(AutoCompleteSelectField, self).__init__(max_length=255,*args, **kwargs) 92 | 93 | def clean(self, value): 94 | if value: 95 | lookup = get_lookup(self.channel) 96 | objs = lookup.get_objects( [ value] ) 97 | if len(objs) != 1: 98 | # someone else might have deleted it while you were editing 99 | # or your channel is faulty 100 | # out of the scope of this field to do anything more than tell you it doesn't exist 101 | raise forms.ValidationError(u"%s cannot find object: %s" % (lookup,value)) 102 | return objs[0] 103 | else: 104 | if self.required: 105 | raise forms.ValidationError(self.error_messages['required']) 106 | return None 107 | 108 | def check_can_add(self,user,model): 109 | _check_can_add(self,user,model) 110 | 111 | 112 | #################################################################################### 113 | 114 | 115 | class AutoCompleteSelectMultipleWidget(forms.widgets.SelectMultiple): 116 | 117 | """ widget to select multiple models """ 118 | 119 | add_link = None 120 | 121 | def __init__(self, 122 | channel, 123 | help_text='', 124 | show_help_text=None, 125 | *args, **kwargs): 126 | super(AutoCompleteSelectMultipleWidget, self).__init__(*args, **kwargs) 127 | self.channel = channel 128 | 129 | self.help_text = help_text or _('Enter text to search.') 130 | self.show_help_text = show_help_text 131 | 132 | def render(self, name, value, attrs=None): 133 | 134 | if value is None: 135 | value = [] 136 | 137 | final_attrs = self.build_attrs(attrs) 138 | self.html_id = final_attrs.pop('id', name) 139 | 140 | lookup = get_lookup(self.channel) 141 | 142 | # eg. value = [3002L, 1194L] 143 | if value: 144 | current_ids = "|" + "|".join( str(pk) for pk in value ) + "|" # |pk|pk| of current 145 | else: 146 | current_ids = "|" 147 | 148 | objects = lookup.get_objects(value) 149 | 150 | # text repr of currently selected items 151 | current_repr_json = [] 152 | for obj in objects: 153 | display = lookup.format_item_display(obj) 154 | current_repr_json.append( """new Array("%s",%s)""" % (escapejs(display),obj.pk) ) 155 | current_reprs = mark_safe("new Array(%s)" % ",".join(current_repr_json)) 156 | 157 | if self.show_help_text: 158 | help_text = self.help_text 159 | else: 160 | help_text = '' 161 | 162 | context = { 163 | 'name':name, 164 | 'html_id':self.html_id, 165 | 'min_length': getattr(lookup, 'min_length', 1), 166 | 'lookup_url':reverse('ajax_lookup',kwargs={'channel':self.channel}), 167 | 'current':value, 168 | 'current_ids':current_ids, 169 | 'current_reprs': current_reprs, 170 | 'help_text':help_text, 171 | 'extra_attrs': mark_safe(flatatt(final_attrs)), 172 | 'func_slug': self.html_id.replace("-",""), 173 | 'add_link' : self.add_link, 174 | } 175 | context.update(bootstrap()) 176 | 177 | return mark_safe(render_to_string(('autocompleteselectmultiple_%s.html' % self.channel, 'autocompleteselectmultiple.html'),context)) 178 | 179 | def value_from_datadict(self, data, files, name): 180 | # eg. u'members': [u'|229|4688|190|'] 181 | return [long(val) for val in data.get(name,'').split('|') if val] 182 | 183 | def id_for_label(self, id_): 184 | return '%s_text' % id_ 185 | 186 | 187 | 188 | class AutoCompleteSelectMultipleField(forms.fields.CharField): 189 | 190 | """ form field to select multiple models for a ManyToMany db field """ 191 | 192 | channel = None 193 | 194 | def __init__(self, channel, *args, **kwargs): 195 | self.channel = channel 196 | 197 | as_default_help = u'Enter text to search.' 198 | help_text = kwargs.get('help_text') 199 | if not (help_text is None): 200 | try: 201 | en_help = help_text.translate('en') 202 | except AttributeError: 203 | pass 204 | else: 205 | # monkey patch the django default help text to the ajax selects default help text 206 | django_default_help = u'Hold down "Control", or "Command" on a Mac, to select more than one.' 207 | if django_default_help in en_help: 208 | en_help = en_help.replace(django_default_help,'').strip() 209 | # probably will not show up in translations 210 | if en_help: 211 | help_text = _(en_help) 212 | else: 213 | help_text = _(as_default_help) 214 | else: 215 | help_text = _(as_default_help) 216 | 217 | # admin will also show help text, so by default do not show it in widget 218 | # if using in a normal form then set to True so the widget shows help 219 | show_help_text = kwargs.pop('show_help_text',False) 220 | 221 | kwargs['widget'] = AutoCompleteSelectMultipleWidget(channel=channel,help_text=help_text,show_help_text=show_help_text) 222 | kwargs['help_text'] = help_text 223 | 224 | super(AutoCompleteSelectMultipleField, self).__init__(*args, **kwargs) 225 | 226 | def clean(self, value): 227 | if not value and self.required: 228 | raise forms.ValidationError(self.error_messages['required']) 229 | return value # a list of IDs from widget value_from_datadict 230 | 231 | def check_can_add(self,user,model): 232 | _check_can_add(self,user,model) 233 | 234 | 235 | #################################################################################### 236 | 237 | 238 | class AutoCompleteWidget(forms.TextInput): 239 | """ 240 | Widget to select a search result and enter the result as raw text in the text input field. 241 | the user may also simply enter text and ignore any auto complete suggestions. 242 | """ 243 | channel = None 244 | help_text = '' 245 | html_id = '' 246 | 247 | def __init__(self, channel, *args, **kwargs): 248 | self.channel = channel 249 | self.help_text = kwargs.pop('help_text', '') 250 | 251 | super(AutoCompleteWidget, self).__init__(*args, **kwargs) 252 | 253 | def render(self, name, value, attrs=None): 254 | 255 | value = value or '' 256 | 257 | final_attrs = self.build_attrs(attrs) 258 | self.html_id = final_attrs.pop('id', name) 259 | 260 | lookup = get_lookup(self.channel) 261 | 262 | context = { 263 | 'current_repr': mark_safe("'%s'" % escapejs(value)), 264 | 'current_id': value, 265 | 'help_text': self.help_text, 266 | 'html_id': self.html_id, 267 | 'min_length': getattr(lookup, 'min_length', 1), 268 | 'lookup_url': reverse('ajax_lookup', args=[self.channel]), 269 | 'name': name, 270 | 'extra_attrs':mark_safe(flatatt(final_attrs)), 271 | 'func_slug': self.html_id.replace("-",""), 272 | } 273 | context.update(bootstrap()) 274 | 275 | templates = ('autocomplete_%s.html' % self.channel, 276 | 'autocomplete.html') 277 | return mark_safe(render_to_string(templates, context)) 278 | 279 | 280 | 281 | class AutoCompleteField(forms.CharField): 282 | """ 283 | Field uses an AutoCompleteWidget to lookup possible completions using a channel and stores raw text (not a foreign key) 284 | """ 285 | channel = None 286 | 287 | def __init__(self, channel, *args, **kwargs): 288 | self.channel = channel 289 | 290 | widget = AutoCompleteWidget(channel,help_text=kwargs.get('help_text', _('Enter text to search.'))) 291 | 292 | defaults = {'max_length': 255,'widget': widget} 293 | defaults.update(kwargs) 294 | 295 | super(AutoCompleteField, self).__init__(*args, **defaults) 296 | 297 | 298 | #################################################################################### 299 | 300 | def _check_can_add(self,user,model): 301 | """ check if the user can add the model, deferring first to 302 | the channel if it implements can_add() 303 | else using django's default perm check. 304 | if it can add, then enable the widget to show the + link 305 | """ 306 | lookup = get_lookup(self.channel) 307 | if hasattr(lookup,'can_add'): 308 | can_add = lookup.can_add(user,model) 309 | else: 310 | ctype = ContentType.objects.get_for_model(model) 311 | can_add = user.has_perm("%s.add_%s" % (ctype.app_label,ctype.model)) 312 | if can_add: 313 | self.widget.add_link = reverse('add_popup', 314 | kwargs={'app_label':model._meta.app_label,'model':model._meta.object_name.lower()}) 315 | 316 | 317 | def autoselect_fields_check_can_add(form,model,user): 318 | """ check the form's fields for any autoselect fields and enable their widgets with + sign add links if permissions allow""" 319 | for name,form_field in form.declared_fields.iteritems(): 320 | if isinstance(form_field,(AutoCompleteSelectMultipleField,AutoCompleteSelectField)): 321 | db_field = model._meta.get_field_by_name(name)[0] 322 | form_field.check_can_add(user,db_field.rel.to) 323 | 324 | 325 | def bootstrap(): 326 | b = {} 327 | b['bootstrap'] = getattr(settings,'AJAX_SELECT_BOOTSTRAP',False) 328 | inlines = getattr(settings,'AJAX_SELECT_INLINES',None) 329 | 330 | b['inline'] = '' 331 | if inlines == 'inline': 332 | directory = os.path.dirname( os.path.realpath(__file__) ) 333 | f = open(os.path.join(directory,"static","css","ajax_select.css")) 334 | css = f.read() 335 | f = open(os.path.join(directory,"static","js","ajax_select.js")) 336 | js = f.read() 337 | b['inline'] = mark_safe(u"""""" % (css,js)) 338 | elif inlines == 'staticfiles': 339 | b['inline'] = mark_safe("""""" % (settings.STATIC_URL,settings.STATIC_URL)) 340 | 341 | return b 342 | 343 | 344 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Enables editing of `ForeignKey`, `ManyToMany` and `CharField` using jQuery UI Autocomplete. 3 | 4 | User experience 5 | =============== 6 | 7 | selecting: 8 | 9 | 10 | 11 | selected: 12 | 13 | 14 | 15 | [Note: screen shots are from the older version. Styling has changed slightly] 16 | 17 | 1. The user types a search term into the text field 18 | 2. An ajax request is sent to the server. 19 | 3. The dropdown menu is populated with results. 20 | 4. User selects by clicking or using arrow keys 21 | 5. Selected result displays in the "deck" area directly below the input field. 22 | 6. User can click trashcan icon to remove a selected item 23 | 24 | Features 25 | ======== 26 | 27 | + Django 1.2+ 28 | + Optional boostrap mode allows easy installation by automatic inclusion of jQueryUI from the googleapis CDN 29 | + Compatible with staticfiles, appmedia, django-compressor etc 30 | + Popup to add a new item is supported 31 | + Admin inlines now supported 32 | + Ajax Selects works in the admin and also in public facing forms. 33 | + Rich formatting can be easily defined for the dropdown display and the selected "deck" display. 34 | + Templates and CSS are fully customizable 35 | + JQuery triggers enable you to add javascript to respond when items are added or removed, so other interface elements on the page can react 36 | + Default (but customizable) security prevents griefers from pilfering your data via JSON requests 37 | 38 | 39 | 40 | Quick Installation 41 | ================== 42 | 43 | Get it 44 | 45 | `pip install django-ajax-selects` 46 | or 47 | `easy_install django-ajax-selects` 48 | or 49 | download or checkout the distribution 50 | or 51 | install using buildout by adding `django-ajax-selects` to your `eggs` 52 | 53 | on fedora: 54 | su -c 'yum install django-ajax-selects' 55 | (note: this version may not be up to date) 56 | 57 | 58 | In settings.py : 59 | 60 | # add the app 61 | INSTALLED_APPS = ( 62 | ..., 63 | 'ajax_select' 64 | ) 65 | 66 | # define the lookup channels in use on the site 67 | AJAX_LOOKUP_CHANNELS = { 68 | # pass a dict with the model and the field to search against 69 | 'person' : {'model':'example.person', 'search_field':'name'} 70 | } 71 | # magically include jqueryUI/js/css 72 | AJAX_SELECT_BOOTSTRAP = True 73 | AJAX_SELECT_INLINES = 'inline' 74 | 75 | In your urls.py: 76 | 77 | from django.conf.urls.defaults import * 78 | 79 | from django.contrib import admin 80 | from ajax_select import urls as ajax_select_urls 81 | 82 | admin.autodiscover() 83 | 84 | urlpatterns = patterns('', 85 | # include the lookup urls 86 | (r'^admin/lookups/', include(ajax_select_urls)), 87 | (r'^admin/', include(admin.site.urls)), 88 | ) 89 | 90 | In your admin.py: 91 | 92 | from django.contrib import admin 93 | from ajax_select import make_ajax_form 94 | from ajax_select.admin import AjaxSelectAdmin 95 | from example.models import * 96 | 97 | class PersonAdmin(admin.ModelAdmin): 98 | pass 99 | admin.site.register(Person,PersonAdmin) 100 | 101 | # subclass AjaxSelectAdmin 102 | class LabelAdmin(AjaxSelectAdmin): 103 | # create an ajax form class using the factory function 104 | # model,fieldlist, [form superclass] 105 | form = make_ajax_form(Label,{'owner':'person'}) 106 | admin.site.register(Label,LabelAdmin) 107 | 108 | 109 | This setup will give most people the ajax powered editing they need by bootstrapping in JS/CSS and implementing default security and simple ajax lookup channels. 110 | 111 | NOT SO QUICK INSTALLATION 112 | ========================= 113 | 114 | Things that can be customized: 115 | 116 | + how and from where jQuery, jQueryUI, jQueryUI theme are loaded 117 | + whether to include js/css inline or for better performance via staticfiles or django-compress etc. 118 | + define custom `LookupChannel` classes to customize: 119 | + HTML formatting for the drop down results and the item-selected display 120 | + custom search queries, ordering, user specific filtered results 121 | + custom channel security (default is staff only) 122 | + customizing the CSS 123 | + each channel could define its own template to change display or add extra javascript 124 | + custom javascript can respond to jQuery triggers when items are selected or removed 125 | 126 | 127 | Architecture 128 | ============ 129 | 130 | A single view services all of the ajax search requests, delegating the searches to named 'channels'. Each model that needs to be searched for has a channel defined for it. More than one channel may be defined for a Model to serve different needs such as public vs admin or channels that filter the query by specific categories etc. The channel also has access to the request and the user so it can personalize the query results. Those channels can be reused by any Admin that wishes to lookup that model for a ManyToMany or ForeignKey field. 131 | 132 | A simple channel can be specified in settings.py, a more complex one (with custom search, formatting, personalization or auth requirements) can be written in a lookups.py file. 133 | 134 | There are three model field types with corresponding form fields and widgets: 135 | 136 | 137 | 138 | 139 | 140 | 141 |
    Database fieldForm fieldForm widget
    models.CharFieldAutoCompleteFieldAutoCompleteWidget
    models.ForeignKeyAutoCompleteSelectFieldAutoCompleteSelectWidget
    models.ManyToManyFieldAutoCompleteSelectMultipleFieldAutoCompleteSelectMultipleWidget
    142 | 143 | Generally the helper functions documented below can be used to generate a complete form or an individual field (with widget) for a form. In rare cases you might need to specify the ajax form field explicitly in your Form. 144 | 145 | Example App 146 | =========== 147 | 148 | See the example app for a full working admin site with many variations and comments. It installs quickly using virtualenv and sqllite and comes fully configured. 149 | 150 | 151 | settings.py 152 | ----------- 153 | 154 | #### AJAX_LOOKUP_CHANNELS 155 | 156 | Defines the available lookup channels. 157 | 158 | + channel_name : {'model': 'app.modelname', 'search_field': 'name_of_field_to_search' } 159 | > This will create a channel automatically 160 | 161 | chanel_name : ( 'app.lookups', 'YourLookup' ) 162 | This points to a custom Lookup channel name YourLookup in app/lookups.py 163 | 164 | AJAX_LOOKUP_CHANNELS = { 165 | # channel : dict with settings to create a channel 166 | 'person' : {'model':'example.person', 'search_field':'name'}, 167 | 168 | # channel: ( module.where_lookup_is, ClassNameOfLookup ) 169 | 'song' : ('example.lookups', 'SongLookup'), 170 | } 171 | 172 | #### AJAX_SELECT_BOOTSTRAP 173 | 174 | Sets if it should automatically include jQuery/jQueryUI/theme. On large formsets this will cause it to check each time but it will only jQuery the first time. 175 | 176 | + True: [easiest] 177 | use jQuery if already present, else use the admin's jQuery else load from google's CDN 178 | use jqueryUI if present else load from google's CDN 179 | use jqueryUI theme if present else load one from google's CDN 180 | 181 | + False/None/Not set: [default] 182 | you should then include jQuery, jqueryUI + theme in your template or js compressor stack 183 | 184 | 185 | #### AJAX_SELECT_INLINES 186 | 187 | This controls if and how these: 188 | 189 | ajax_select/static/js/ajax_select.js 190 | ajax_select/static/css/ajax_select.css 191 | 192 | are included inline in the html with each form field. 193 | 194 | + 'inline': [easiest] 195 | Includes the js and css inline 196 | This gets you up and running easily and is fine for small sites. 197 | But with many form fields this will be less efficient. 198 | 199 | + 'staticfiles': 200 | @import the css/js from {{STATIC_URL}}/ajax_selects using `django.contrib.staticfiles` 201 | Requires staticfiles to be installed and to run its management command to collect files. 202 | This still imports the css/js multiple times and is thus inefficient but otherwise harmless. 203 | 204 | When using staticfiles you may implement your own `ajax_select.css` and customize to taste as long 205 | as your app is before ajax_select in the INSTALLED_APPS. 206 | 207 | + False/None: [default] 208 | Does not inline anything. You should include the css/js files in your compressor stack 209 | or include them in the head of the admin/base_site.html template. 210 | This is the most efficient but takes the longest to configure. 211 | 212 | 213 | urls.py 214 | ------- 215 | 216 | Simply include the ajax_select urls in your site's urlpatterns: 217 | 218 | from django.conf.urls.defaults import * 219 | 220 | from django.contrib import admin 221 | from ajax_select import urls as ajax_select_urls 222 | 223 | admin.autodiscover() 224 | 225 | urlpatterns = patterns('', 226 | (r'^admin/lookups/', include(ajax_select_urls)), 227 | (r'^admin/', include(admin.site.urls)), 228 | ) 229 | 230 | 231 | lookups.py 232 | ---------- 233 | 234 | By convention this is where you would define custom lookup channels 235 | 236 | Subclass `LookupChannel` and override any method you wish to customize. 237 | 238 | 1.1x Upgrade note: previous versions did not have a parent class. The methods format_result and format_item have been renamed to format_match and format_item_display respectively. 239 | Those old lookup channels will still work and the previous methods will be used. It is still better to adjust your lookup channels to inherit from the new base class. 240 | 241 | from ajax_select import LookupChannel 242 | from django.utils.html import escape 243 | from django.db.models import Q 244 | from example.models import * 245 | 246 | class PersonLookup(LookupChannel): 247 | 248 | model = Person 249 | 250 | def get_query(self,q,request): 251 | return Person.objects.filter(Q(name__icontains=q) | Q(email__istartswith=q)).order_by('name') 252 | 253 | def get_result(self,obj): 254 | u""" result is the simple text that is the completion of what the person typed """ 255 | return obj.name 256 | 257 | def format_match(self,obj): 258 | """ (HTML) formatted item for display in the dropdown """ 259 | return self.format_item_display(obj) 260 | 261 | def format_item_display(self,obj): 262 | """ (HTML) formatted item for displaying item in the selected deck area """ 263 | return u"%s
    %s
    " % (escape(obj.name),escape(obj.email)) 264 | 265 | Note that raw strings should always be escaped with the escape() function 266 | 267 | #### Methods you can override in your `LookupChannel` 268 | 269 | 270 | ###### model [property] 271 | 272 | The model class this channel searches 273 | 274 | ###### min_length [property, default=1] 275 | 276 | Minimum query length to return a result. Large datasets can choke if they search too often with small queries. 277 | Better to demand at least 2 or 3 characters. 278 | This param is also used in jQuery's UI when filtering results from its own cache. 279 | 280 | ###### search_field [property, optional] 281 | 282 | Name of the field for the query to search with icontains. This is used only in the default get_query implementation. 283 | Usually better to just implement your own get_query 284 | 285 | ###### get_query(self,q,request) 286 | 287 | return a query set searching for the query string q, ordering as appropriate. 288 | Either implement this method yourself or set the search_field property. 289 | Note that you may return any iterable so you can even use yield and turn this method into a generator, 290 | or return an generator or list comprehension. 291 | 292 | ###### get_result(self,obj): 293 | 294 | The text result of autocompleting the entered query. This is currently displayed only for a moment in the text field 295 | after the user has selected the item. Then the item is displayed in the item_display deck and the text field is cleared. 296 | Future versions may offer different handlers for how to display the selected item(s). In the current version you may 297 | add extra script and use triggers to customize. 298 | 299 | ###### format_match(self,obj): 300 | 301 | (HTML) formatted item for displaying item in the result dropdown 302 | 303 | ###### format_item_display(self,obj): 304 | 305 | (HTML) formatted item for displaying item in the selected deck area (directly below the text field). 306 | Note that we use jQuery .position() to correctly place the deck area below the text field regardless of 307 | whether the widget is in the admin, and admin inline or an outside form. ie. it does not depend on django's 308 | admin css to correctly place the selected display area. 309 | 310 | ###### get_objects(self,ids): 311 | 312 | Get the currently selected objects when editing an existing model 313 | 314 | Note that the order of the ids supplied for ManyToMany fields is dependent on how the objects manager fetches it. 315 | ie. what is returned by yourmodel.fieldname_set.all() 316 | 317 | In most situations (especially postgres) this order is random, not the order that you originally added them in the interface. With a bit of hacking I have convinced it to preserve the order [see OrderedManyToMany.md for solution] 318 | 319 | ###### can_add(self,user,argmodel): 320 | 321 | Check if the user has permission to add one of these models. 322 | This enables the green popup + 323 | Default is the standard django permission check 324 | 325 | ###### check_auth(self,request): 326 | 327 | To ensure that nobody can get your data via json simply by knowing the URL. 328 | The default is to limit it to request.user.is_staff and raise a PermissionDenied exception. 329 | By default this is an error with a 401 response, but your middleware may intercept and choose to do other things. 330 | 331 | Public facing forms should write a custom `LookupChannel` to implement as needed. 332 | Also you could choose to return HttpResponseForbidden("who are you?") instead of raising PermissionDenied 333 | 334 | 335 | admin.py 336 | -------- 337 | 338 | #### make_ajax_form(model,fieldlist,superclass=ModelForm,show_m2m_help=False) 339 | 340 | If your application does not otherwise require a custom Form class then you can use the make_ajax_form helper to create the entire form directly in admin.py. See forms.py below for cases where you wish to make your own Form. 341 | 342 | + *model*: your model 343 | + *fieldlist*: a dict of {fieldname : channel_name, ... } 344 | + *superclass*: [default ModelForm] Substitute a different superclass for the constructed Form class. 345 | + *show_m2m_help*: [default False] 346 | Leave blank [False] if using this form in a standard Admin. 347 | Set it True for InlineAdmin classes or if making a form for use outside of the Admin. 348 | See discussion below re: Help Text 349 | 350 | ######Example 351 | 352 | from ajax_select import make_ajax_form 353 | from ajax_select.admin import AjaxSelectAdmin 354 | from yourapp.models import YourModel 355 | 356 | class YourModelAdmin(AjaxSelectAdmin): 357 | # create an ajax form class using the factory function 358 | # model,fieldlist, [form superclass] 359 | form = make_ajax_form(Label,{'owner':'person'}) 360 | 361 | admin.site.register(YourModel,YourModelAdmin) 362 | 363 | You may use AjaxSelectAdmin as a mixin class and multiple inherit if you have another Admin class that you would like to use. You may also just add the hook into your own Admin class: 364 | 365 | def get_form(self, request, obj=None, **kwargs): 366 | form = super(YourAdminClass,self).get_form(request,obj,**kwargs) 367 | autoselect_fields_check_can_add(form,self.model,request.user) 368 | return form 369 | 370 | Note that ajax_selects does not need to be in an admin. Popups will still use an admin view (the registered admin for the model being added), even if the form from where the popup was launched does not. 371 | 372 | 373 | forms.py 374 | -------- 375 | 376 | subclass ModelForm just as usual. You may add ajax fields using the helper or directly. 377 | 378 | #### make_ajax_field(model,model_fieldname,channel,show_m2m_help = False,**kwargs) 379 | 380 | A factory function to makes an ajax field + widget. The helper ensures things are set correctly and simplifies usage and imports thus reducing programmer error. All kwargs are passed into the Field so it is no less customizable. 381 | 382 | + *model*: the model that this ModelForm is for 383 | + *model_fieldname*: the field on the model that is being edited (ForeignKey, ManyToManyField or CharField) 384 | + *channel*: the lookup channel to use for searches 385 | + *show_m2m_help*: [default False] When using in the admin leave this as False. 386 | When using in AdminInline or outside of the admin then set it to True. 387 | see Help Text section below. 388 | + *kwargs*: Additional kwargs are passed on to the form field. 389 | Of interest: 390 | help_text="Custom help text" 391 | or: 392 | # do not show any help at all 393 | help_text=None 394 | 395 | #####Example 396 | 397 | from ajax_select import make_ajax_field 398 | 399 | class ReleaseForm(ModelForm): 400 | 401 | class Meta: 402 | model = Release 403 | 404 | group = make_ajax_field(Release,'group','group',help_text=None) 405 | 406 | #### Without using the helper 407 | 408 | 409 | from ajax_select.fields import AutoCompleteSelectField 410 | 411 | class ReleaseForm(ModelForm): 412 | 413 | group = AutoCompleteSelectField('group', required=False, help_text=None) 414 | 415 | 416 | #### Using ajax selects in a `FormSet` 417 | 418 | There is possibly a better way to do this, but here is an initial example: 419 | 420 | `forms.py` 421 | 422 | from django.forms.models import modelformset_factory 423 | from django.forms.models import BaseModelFormSet 424 | from ajax_select.fields import AutoCompleteSelectMultipleField, AutoCompleteSelectField 425 | 426 | from models import * 427 | 428 | # create a superclass 429 | class BaseTaskFormSet(BaseModelFormSet): 430 | 431 | # that adds the field in, overwriting the previous default field 432 | def add_fields(self, form, index): 433 | super(BaseTaskFormSet, self).add_fields(form, index) 434 | form.fields["project"] = AutoCompleteSelectField('project', required=False) 435 | 436 | # pass in the base formset class to the factory 437 | TaskFormSet = modelformset_factory(Task,fields=('name','project','area'),extra=0,formset=BaseTaskFormSet) 438 | 439 | 440 | 441 | templates/ 442 | ---------- 443 | 444 | Each form field widget is rendered using a template. You may write a custom template per channel and extend the base template in order to implement these blocks: 445 | 446 | {% block extra_script %}{% endblock %} 447 | {% block help %}{% endblock %} 448 | 449 | 450 | 451 | 452 | 453 |
    form Fieldtries this firstdefault template
    AutoCompleteFieldtemplates/autocomplete_{{CHANNELNAME}}.htmltemplates/autocomplete.html
    AutoCompleteSelectFieldtemplates/autocompleteselect_{{CHANNELNAME}}.htmltemplates/autocompleteselect.html
    AutoCompleteSelectMultipleFieldtemplates/autocompleteselectmultiple_{{CHANNELNAME}}.htmltemplates/autocompleteselectmultiple.html
    454 | 455 | See ajax_select/static/js/ajax_select.js below for the use of jQuery trigger events 456 | 457 | 458 | ajax_select/static/css/ajax_select.css 459 | -------------------------------------- 460 | 461 | If you are using `django.contrib.staticfiles` then you can implement `ajax_select.css` and put your app ahead of ajax_select to cause it to be collected by the management command `collectfiles`. 462 | 463 | If you are doing your own compress stack then of course you can include whatever version you want. 464 | 465 | The display style now uses the jQuery UI theme and actually I find the drop down to be not very charming. The previous version (1.1x) which used the external jQuery AutoComplete plugin had nicer styling. I might decide to make the default more like that with alternating color rows and a stronger sense of focused item. Also the current jQuery one wiggles. 466 | 467 | The CSS refers to one image that is served from github (as a CDN): 468 | !['https://github.com/crucialfelix/django-ajax-selects/raw/master/ajax_select/static/images/loading-indicator.gif'](https://github.com/crucialfelix/django-ajax-selects/raw/master/ajax_select/static/images/loading-indicator.gif) 'https://github.com/crucialfelix/django-ajax-selects/raw/master/ajax_select/static/images/loading-indicator.gif' 469 | 470 | Your own site's CSS could redefine that with a stronger declaration to point to whatever you like. 471 | 472 | The trashcan icon comes from the jQueryUI theme by the css classes: 473 | 474 | "ui-icon ui-icon-trash" 475 | 476 | The css declaration: 477 | 478 | .results_on_deck .ui-icon.ui-icon-trash { } 479 | 480 | would be "stronger" than jQuery's style declaration and thus you could make trash look less trashy. 481 | 482 | 483 | ajax_select/static/js/ajax_select.js 484 | ------------------------------------ 485 | 486 | You probably don't want to mess with this one. But by using the extra_script block as detailed in templates/ above you can add extra javascript, particularily to respond to event Triggers. 487 | 488 | Triggers are a great way to keep code clean and untangled. see: http://docs.jquery.com/Events/trigger 489 | 490 | Two triggers/signals are sent: 'added' and 'killed'. These are sent to the $("#{{html_id}}_on_deck") element. That is the area that surrounds the currently selected items. 491 | 492 | Extend the template, implement the extra_script block and bind functions that will respond to the trigger: 493 | 494 | ##### multi select: 495 | 496 | {% block extra_script %} 497 | $("#{{html_id}}_on_deck").bind('added',function() { 498 | id = $("#{{html_id}}").val(); 499 | alert('added id:' + id ); 500 | }); 501 | $("#{{html_id}}_on_deck").bind('killed',function() { 502 | current = $("#{{html_id}}").val() 503 | alert('removed, current is:' + current); 504 | }); 505 | {% endblock %} 506 | 507 | ##### select: 508 | 509 | {% block extra_script %} 510 | $("#{{html_id}}_on_deck").bind('added',function() { 511 | id = $("#{{html_id}}").val(); 512 | alert('added id:' + id ); 513 | }); 514 | $("#{{html_id}}_on_deck").bind('killed',function() { 515 | alert('removed'); 516 | }); 517 | {% endblock %} 518 | 519 | ##### auto-complete text field: 520 | 521 | {% block extra_script %} 522 | $('#{{ html_id }}').bind('added',function() { 523 | entered = $('#{{ html_id }}').val(); 524 | alert( entered ); 525 | }); 526 | {% endblock %} 527 | 528 | There is no remove as there is no kill/delete button in a simple auto-complete. 529 | The user may clear the text themselves but there is no javascript involved. Its just a text field. 530 | 531 | 532 | Planned Improvements 533 | -------------------- 534 | 535 | TODO: + pop ups are not working in AdminInlines yet 536 | 537 | 538 | 539 | Contributors 540 | ------------ 541 | 542 | Many thanks to all who found bugs, asked for things, and hassled me to get a new release out. I'm glad people find good use out of the app. 543 | 544 | In particular thanks for help in the 1.2 version: sjrd (Sébastien Doeraene), Brian May 545 | 546 | 547 | License 548 | ------- 549 | 550 | Dual licensed under the MIT and GPL licenses: 551 | http://www.opensource.org/licenses/mit-license.php 552 | http://www.gnu.org/licenses/gpl.html 553 | 554 | 555 | --------------------------------------------------------------------------------