django-ajax-selects example usage

Serafeim picture Serafeim · Apr 19, 2012 · Viewed 7.6k times · Source

can anybody post the simplest possible example for django-ajax-selects ? Just one model with a field and a form that can be used to select instances of this model based on that field (not in admin but in a user form).

I tried reading the documentation of the project but found it very difficult to understand... Also, I was not able to make the Example App work (coudln't find out what is a Label ???) :(

Also, if you believe that there is an easiest solution than django-ajax-selects please tell me.

Thank you!

Answer

user1257144 picture user1257144 · Jun 22, 2012

Here is a simple example (from the example on github but not tested):

models.py:

class Person(models.Model):
    name = models.CharField(blank=True, max_length=100)
    email = models.EmailField()

    def __unicode__(self):
        return self.name


class Group(models.Model):
    name = models.CharField(max_length=200,unique=True)
    members = models.ManyToManyField(Person,blank=True,help_text="Enter text to search for and add each member of the group.")

    def __unicode__(self):
        return self.name

forms.py:

class GroupForm(ModelForm):

    class Meta:
        model = Group

    members  = make_ajax_field(Release,'members','person')

lookups.py:

class PersonLookup(LookupChannel):

    model = Person

    def get_query(self,q,request):
        return Person.objects.filter(name__icontains=q).order_by('name')

    def get_result(self,obj):
        return obj.name

    def format_match(self,obj):
        return self.format_item_display(obj)

    def format_item_display(self,obj):
        return u"%s" % escape(obj.name)

settings.py:

AJAX_LOOKUP_CHANNELS = {
     'person' : ('example.lookups', 'PersonLookup'),
}

views.py:

class Create(generic.CreateView):
    template_name = "create.html"
    form_class = GroupForm
    success_url = 'create'

create = Create.as_view()

urls.py:

urlpatterns = patterns('',
    url(r'^create',  view='views.create',name='create'),
    url(r'^ajax_lookup/(?P<channel>[-\w]+)$', 'ajax_select.views.ajax_lookup', name = 'ajax_lookup'),
)