Question

I need help with implementing auto-complete fields in my Django Project. I am trying to get a list of relevant items from my database as the user types in the query.

I am using django-ajax-selects package.

My project name is computer builder, and builds and parts are apps. My file structure looks like this:

parts/models.py:

from django.db import models

# Create your models here.

class moboListing(models.Model):
    """This model makes a database for a list of motherboards and prices"""
    id = models.AutoField(primary_key=True)
    moboList = models.CharField(max_length=400)
    moboPrice = models.DecimalField(max_digits=5, decimal_places=2)

In database, moboListing is populated with names of motherboards.

builds/models.py:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class BuildsTable(models.Model):

    moboPart   = models.CharField(max_length=400)
    moboPrice  = models.DecimalField(max_digits=5, decimal_places=2)

builds/forms.py:

from django.forms.models import ModelForm
from django import forms
from ajax_select import make_ajax_field
from parts.models import moboListing
from builds.models import BuildsTable

class BuildsForm(ModelForm):

    class Meta:
        model = moboListing

    moboList  = make_ajax_field(moboListing, 'moboList', 'moboList', help_text=None

builds/lookups.py:

from ajax_select import LookupChannel
from django.db.models import Q
from django.utils.html import escape
from parts.models import moboListing

class moboLookup(LookupChannel):

    model = moboListing

    def get_query(self, q, request):
        return moboListing.objects.filter(Q(moboList__icontains=q)).order_by('name')
    def get_result(self, obj):
        """ 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 self.format_item_display(obj)

    def format_item_display(self, obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        return u"%s<div><i>%s</i></div>" % (escape(obj.moboList), escape(obj.moboPrice))

    def get_objects(self, ids):
        return moboListing.objects.filter(pk__in=ids)

builds/views.py:

from django.shortcuts import render, render_to_response
from django import forms
import datetime
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from ajax_select.fields import AutoCompleteField
from forms import BuildsForm
from builds.models import BuildsTable
from parts.models import moboListing

# Create your views here.

class SearchForm(forms.Form):

    q = AutoCompleteField(
            'moboList',
            required=True,
            help_text="Autocomplete will suggest motherboards",
            label="Motherboards",
            attrs={'size': 400}
            )

@login_required
def new_build(request):

    dd = {}
    if 'q' in request.GET:
        dd['entered'] = request.GET.get('q')
    initial = {'q': "Enter Motherboard query"}
    form = SearchForm(initial=initial)
    dd['form'] = form
    return render_to_response('new_build.html', dd, context_instance=RequestContext(request))

in settings.py:

    # define the lookup channels in use on the site
    AJAX_LOOKUP_CHANNELS = {
        #simple: search Person.objects.filter(name__icontains=q)
        #'person'  : {'model': 'example.person', 'search_field': 'name'},
        # define a custom lookup channel
        #'song'   : ('example.lookups', 'SongLookup')
        #'moboList' : {'model': 'parts.moboListing', 'search_field': 'moboList'},
        'moboList': ('builds.lookups', 'moboLookup')

    }

    AJAX_SELECT_BOOTSTRAP = True

However, on my html page, when I am on the test server, typing into the search field does not bring up any results from the database: http://i.imgur.com/3o1PONH.jpg

Also my source for the html shows that autocomplete is off, and the source is /admin/lookups/ajax_lookup/moboList, however when I visit that link, I get a 404:

<tr><th><label for="id_q">Motherboards:</label></th><td><input type="text" name="q" id="id_q" value="Enter Motherboard query" autocomplete="off" data-ajax-select="autocomplete" data-plugin-options="{min_length: 1, initial: Enter Motherboard query, html: true, source: /admin/lookups/ajax_lookup/moboList}"  maxlength="255" 

Anyone can help me on this? Thanks!

Was it helpful?

Solution

You also need to add the ajax lookup view to your urls.py

from django.conf.urls.defaults import *

from django.contrib import admin
from ajax_select import urls as ajax_select_urls

admin.autodiscover()

urlpatterns = patterns('',
    # include the lookup urls
    (r'^autocomplete/', include(ajax_select_urls)),
)

As you say:

/admin/lookups/ajax_lookup/moboList, however when I visit that link, I get a 404:

so that should point you to the problem immediately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top