I can't seem to make django-ajax-selects work

1.8k Views Asked by At

I have followed the installation guide for django-ajax-selects at this url, and still, nothing happens : when I type something into the rendered field, nothing is displayed, to POST request are sent, etc.. Because this package was made for the admin, I must be missing something in my out-of-admin form.

I have done the following :

settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'fr',
    ...
    'ajax_select', # pip install django-ajax-selects
)

lookups.py (under the 'fr' app folder)

from ajax_select import register, LookupChannel
from fr.models.generalModels import City

@register('city')
class CityLookup(LookupChannel):

    model = City

    def get_query(self, q, request):
        return self.model.objects.filter(full_name__icontains=q)

    def format_item_display(self, item):
        return u"<span class='tag'>%s</span>" % item.full_name

forms.py

class JobOfferForm(forms.ModelForm):
    city = AutoCompleteSelectField('city')
    class Meta:
        model = JobOffer

template.html

<script src="{% static 'ajax_select/js/bootstrap.js' %}"></script>
<script src="{% static 'ajax_select/js/ajax_select.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'ajax_select/css/ajax_select.css' %}">
...
<form class="center-align card-panel" enctype="multipart/form-data" id="JobOfferForm" action="" method="POST">
    {% csrf_token %}
    {{ jobOfferForm.city }}
    {{ jobOfferForm.meta }}
</form>
...

What am I doing wrong?

EDIT : It appears that I missed the bootstrap.js file and the css one, as well as the form.meta (but I'm not sure this last one does anything).
I now have a Forbidden (403) error in the console. I'm pretty sure it's because I don't have a crsf_token in the ajax request, even though it's in the form.

2

There are 2 best solutions below

0
On

i think you need to define the method

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

this method will manage the request result. take a look here: http://django-ajax-selects.readthedocs.org/en/latest/LookupChannel.html#lookups-py

and here: https://github.com/crucialfelix/django-ajax-selects/blob/master/example/example/lookups.py

0
On

adding

{{ form.media }} 

will solve your problem.

http://django-ajax-selects.readthedocs.io/en/latest/Outside-of-Admin.html