Search code examples
pythondjangodjango-modelsdjango-ajax-selects

configuring ajax lookup in django ajax_lookup


I was using the django_ajax library for ajax lookup in one of the form elements.

The model:

class Alpha(models.Model):
    name = models.CharField()
    description = models.TextField()
    submitted = models.BooleanField(default=False)

The form

class MyForm(forms.Form):
    alpha = AutoCompleteSelectField('alpha')

    def __init__(self, loser, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.loser = loser
        self.fields['alpha'].widget.attrs['class'] = 'big-text-box'

The problem with the current implementation is it shows me all the alpha entries, but in the lookup field i want only those alphas whose submitted is false.

How do I write a selector?


Solution

  • As is explained in the README of the project, you can achieve your goal using a custom lookup class.

    Create a file lookups.py (the name is conventional) in your app directory, and define the following class in it:

    from ajax_select import LookupChannel
    from django.utils.html import escape
    from django.db.models import Q
    from yourapp.models import *
    
    class AlphaLookup(LookupChannel):
    
        model = Alpha
    
        def get_query(self,q,request):
            # The real query
            # Here the filter will select only non-submitted entries
            return Alpha.objects.filter(Q(name__icontains = q) & Q(submitted = false)).order_by('name')
    
        def get_result(self,obj):
            u""" result is the simple text that is the completion of what the person typed """
            return obj.name
    
        def format_match(self,obj):
            """ (HTML) formatted item for display in the dropdown """
            return escape(obj.name)
    
        def format_item_display(self,obj):
            """ (HTML) formatted item for displaying item in the selected deck area """
            return escape(obj.name)
    

    Note that raw strings should always be escaped with the escape() function in format_match and format_item_display.

    The crucial thing, in your case, is the get_query method. The filter applied on Alpha.objects selects only non-submitted entries.

    Do not forget to update your settings.py to use the lookup class instead of the default behavior:

    AJAX_LOOKUP_CHANNELS = {
        'alpha' : ('yoursite.yourapp.lookups', 'AlphaLookup'),
    }