django ajax select for ManyToMany
2 March 2009
I've posted the first of many django apps:
http://code.google.com/p/django-ajax-selects/
Initial version
This is working for foreign key fields and many to many fields.
Improvements still to come.
Requirements
Django 1.0 +
jquery 1.26 +
Autocomplete - jQuery plugin 1.0.2 http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
jquery.autocomplete.css
Usage
install as a normal django app
INSTALLED_APPS = (
...,
'ajax_select'
)
There is a single view for ajax lookups that uses named channels and lookup objects that do the searching and formatting work.
peoplez/managers.py
from peoplez.models import Contact
from django.db.models import Q
class ContactLookup(object):
def get_query(self,q,request):<br /> """ perform the search. you have access to the request in case you need to check user permissions """<br /> return Contact.objects.filter(Q(name__startswith=q) | Q(fname__startswith=q) | Q(lname__startswith=q) | Q(email__icontains=q))<br /> <br /> def format_item(self,contact):<br /> """ simple display of an object """<br /> return unicode(contact)
def format_result(self,contact):<br /> """ a more verbose display, used in the search results display. may contain html and multi-lines """<br /> return u"%s %s %s (%s)" % (contact.fname, contact.lname,contact.name,contact.email)
def get_objects(self,ids):<br /> """ given a list of ids, return the objects ordered as you would like them on the admin page """<br /> return Contact.objects.filter(pk__in=ids).order_by('name','lname')<br />in your settings.py define the channels in use on the site:
AJAX_LOOKUP_CHANNELS = {
'contact' : ('peoplez.managers', 'ContactLookup'),
'country' : ('placez.lookups', 'CountryLookup'),
'label' : ('music.lookups','LabelLookup'),
'release' : ('music.lookups','ReleaseLookup'),
}
this specifies to look for ContactLookup in the peoplez.managers module
include the lookup url in your site's urls.py
(r'^ajax/', include('ajax_select.urls')),<br />or insert it directly (there is only one):
url(r'^ajax_lookup/(?P<channel>[-\w]+)$',<br /> 'ajax_select.views.ajax_lookup',<br /> name = 'ajax_lookup'<br /> )<br />for an example model:
class ContactMailing(AbsMail):
""" can mail to contacts """
contacts = models.ManyToManyField(Contact,blank=True)
...
in the admin.py for this app:
class ContactMailingAdmin(admin.ModelAdmin):
# specify a form
form = ContactMailingForm
admin.site.register(ContactMailing,ContactMailingAdmin)
in forms.py for that app:
from ajax_select.fields import AutoCompleteSelectMultipleField
class ContactMailingForm(models.ModelForm):
# specify to use the field and specify the named channel that it uses<br /> contacts = AutoCompleteSelectMultipleField('contact', required=False)<br />Note that the form can be used outside of the django admin.
make sure that
jquery 1.26 +
Autocomplete - jQuery plugin 1.0.2
jquery.autocomplete.css
appear on the page.
Foreign Key Fields
Foreign keys use AutoCompleteSelectField and use the same lookup channel
from ajax_select.fields import AutoCompleteSelectField
contact = AutoCompleteSelectField('contact')
customizing
select_template is used to choose a template to render the interface:
autocompleteselect_{channel}.html or autocompleteselect.html
blocks will be defined later that will allow you to inherit from the main widget template
Improvements
including of media will be improved to use field/admin's Media but it would be preferable if that can be integrated with django-compress
a factory to generate simple lookup channels
a factory to generate a form for an admin class if you don't want to write a form class
ajax niceness (searching...)
integration with (+) add item via popup in django-admin
help_text still not showing
let channel customize the interface's help text
make css tags work with jquery-ui
more posts in tech notes
- django.db.utils.DatabaseError: relation "django_content_type" does not exist
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco} I was getting an error while running unit tests and the test database was failing to be created.django.db.utils.DatabaseError: relation "django_content_type" does not existeventually found the problem. I had the following in a file that was imported to a models.py:hrd_type = ContentType.objects.get_for_model(HttpReferrerDomain)The idea being that it can just set the var when it loads up and after that its always there. But this means for creating a fresh database, the db is ...
- django has two classes called ValidationError
There is one in django.core.exceptions and one in django.forms.util Using that space age IDE Eclipse I have to say I'm enjoying how much time I've saved just going shift-command-O to organize and resolve all of my imports. But today I've just lost a few hours due to my ok-ing the wrong class. Quite mysterious it was, I raised a ValidationError (core exceptions one) in my form's clean() and watched as the try: except ValidationError: in django's full_clean() completely ignored my ...
- GDAL fails to build: `.rodata' can not be used when making a shared object; recompile with -fPIC
libtool: link: g++ -shared -nostdlib /usr/lib/gcc/x86_64-linux-gnu/4.4.1/../../../../lib/crti.o /usr/lib/gcc/x86_64-linux-gnu/4.4.1/crtbeginS.o .libs/libgdal.la.lnkscript -L/usr/local/lib /usr/local/lib/libgeos_c.so /usr/local/lib/libgeos.so /usr/local/lib/libexpat.so -L/usr/lib -lpq -lrt -ldl /usr/lib/libcurl.so -lssl -lcrypto -lz -L/usr/lib/gcc/x86_64-linux-gnu/4.4.1 -L/usr/lib/gcc/x86_64-linux-gnu/4.4.1/../../../../lib -L/lib/../lib -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/4.4.1/../../.. -lstdc++ -lm -lc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/4.4.1/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/4.4.1/../../../../lib/crtn.o -Wl,-soname -Wl,libgdal.so.1 -o .libs/libgdal.so.1.13.2 /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libz.a: could not read symbols: Bad value collect2: ld returned 1 exit status make[1]: *** [libgdal.la] Error 1 make[1]: Leaving directory `/home/crucial/tmp/gdal-1.6.2' ...
- installing MySQLdb on Ubuntu (mysql-python)
MySQLdb is the python support bindings for MySQL. Not that the name would lead you to beleive that. Its sourceforge page calls it http://sourceforge.net/projects/mysql-python/ which makes more sense. you need setuptools, which you usually already have: sudo aptitude install python-setuptools You need MySQL-devel to compile, but its not called that, its called: libmysql++-dev on Ubuntu sudo apt-get install libmysql++-dev download MySQLdb itself from: http://sourceforge.net/projects/mysql-python/ # the version you download will be more recent tar xfz ...
- Full index for tech notes
- django.db.utils.DatabaseError: relation "django_content_type" does not exist


1 TP says...
Is it possible to get full example from this?
Posted at 10:05 p.m. on March 15, 2009