django-autocomplete-light displays empty dropdown in the form
Asked Answered
T

1

9

I am trying to use django-autocomplete-light From this tutorial https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.rst

I Installed it with pip and added it to my settings file

INSTALLED_APPS = (
    'dal',
    'dal_select2',

for my tenant value

My tenant model is

class Tenant(CommonInfo):
    version = IntegerVersionField( )

    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    def __unicode__(self):
        return u'%s %s %s ' % ("#", self.id,"first_name", self.first_name, "last_name")

In my autocomplete view:

from django.shortcuts import render
from dal import autocomplete
from client.models import Tenant


    class TenantAutocomplete(autocomplete.Select2QuerySetView):
        def get_queryset(self):
            # Don't forget to filter out results depending on the visitor !
            if not self.request.user.is_authenticated():
                return Tenant.objects.none()

            qs = Tenant.objects.all()

            if self.q:
                qs = qs.filter(last_name__istartswith=self.q)

            return qs

in autocomplete url

from django.conf.urls import url, include,patterns
from client import views 

    urlpatterns = [
        url(
            r'^tenant-autocomplete/$',
            views.TenantAutocomplete.as_view(),
            name='tenant-autocomplete',
        ), 
    ]

and in form

class LeaseTenantForm(forms.ModelForm):
    tenant = forms.ModelChoiceField(
        queryset=LeaseTenant.objects.all(),
        widget=autocomplete.ModelSelect2(url='tenant-autocomplete')
        )
    class Meta:
        model = LeaseTenant
        exclude = ['lease']

However after rendering in browser I don't see the input text field but the empty dropdown. in actual view

def tenant_new(request,pk,uri):
    lease = get_object_or_404(Lease, pk=pk)
    title = 'tenant'
    uri = _get_redirect_url(request, uri)
    if request.method == "POST":
        form = LeaseTenantForm(request.POST)
        if form.is_valid():
            tenant = form.save(commit=False)  
            tenant.lease = lease      
            tenant.save()
            messages.add_message(request, messages.SUCCESS, str(tenant.id) + "-SUCCESS Object created sucssefully")


            return redirect(uri)
    else:
        form = LeaseTenantForm()
    return render(request, 'object_edit.html', {'form': form, 'title': title, 'extend': EXTEND})

My template file

{% block title %}
        Add/Edit {{ title  }}
{% endblock title %}


{% block content %}

<div class="container">
        <div class="row">
            <div class="col-md-6 col-sm-12">
                    <h4>{{ title  }}</h4>
                    <br><div class="center">
                <form method="POST"  class="form" action="" method="get">
                    <div class="form-group">
                        {% csrf_token %}
                        {{ form|crispy}}



                        {{ form.media }}

                        <BR><BR>
                        <button type="submit" class="btn btn-primary btn-primary">Save</button>
                    </div>
                </form>
               </div>
            </div>
        </div>
</div>

 {% endblock content %} 

So basically the autocomplete is not working . What should I validate to make it work?

enter image description here

Tessitura answered 13/11, 2016 at 12:52 Comment(2)
It seems to me that you forget else statement after Tenant.objects.none()Gammy
I'm getting this exact same error, I'll let you know if I figure it outTecu
T
19

I was running into the same problem. This was a good reference: django-autocompletion-light simple foreign key completion shows not editable drop-down widget

Make sure you are loading the jquery in your header file and that you use the {{ form.media }} tag for your form.

Here is how I load the jquery in my header file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

Also, have you tried going to the tenant-autocomplete/ url to see if you get the results on that page like it is mentioned in the tutorial https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html

If you can't get results from the url that should be the first bug you fix.

Tecu answered 13/11, 2016 at 21:9 Comment(5)
Thanks Joe. I get result from the url. Can you show me you view where you call the final form ?Tessitura
I don't get it . The template in the question you referring to, is actually template for autocomplete view only or this is the actual template for actual form.?Tessitura
Well I define my form in my forms.py file, then I create in my view file. Then to refer to it in the template you just write '{{<name of form>.as_p }}'Tecu
Mysteriously it started to work . I assume something was wrong with my tag {{ form.media }} in template . Thank you joe I really needed some support .Tessitura
Upvoted, awesome response. Has the same problem and adding {{ form.media }} did the job. That was so so easy to overlook in the tutorial!Bergren

© 2022 - 2024 — McMap. All rights reserved.