Giter Club home page Giter Club logo

django-ajax-selects's Introduction

Edit ForeignKey, ManyToManyField and CharField in Django Admin using jQuery UI AutoComplete

Build Status PyPI version

This Django app glues Django Admin, jQuery UI together to enable searching and managing ForeignKey and ManyToMany relationships.

At the time it was created Django did not have any way to do this, and this solution glued together some technologies of the day.

If you are building a new project then you should not use this.

Django has built in support now: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields


selecting

selected

Documentation

http://django-ajax-selects.readthedocs.org/en/latest/

Installation

pip install django-ajax-selects

Add the app:

# settings.py
INSTALLED_APPS = (
    ...
    'ajax_select',  # <-   add the app
    ...
)

Include the urls in your project:

# urls.py
from django.urls import path
from django.conf.urls import include

from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
from ajax_select import urls as ajax_select_urls

admin.autodiscover()

urlpatterns = [
    # This is the api endpoint that django-ajax-selects will call
    # to lookup your model ids by name
    path("admin/lookups/", include(ajax_select_urls)),
    path("admin/", admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Quick Usage

Define a lookup channel:

# yourapp/lookups.py
from ajax_select import register, LookupChannel
from .models import Tag

@register('tags')
class TagsLookup(LookupChannel):

    model = Tag

    def get_query(self, q, request):
        return self.model.objects.filter(name__icontains=q).order_by('name')[:50]

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

Add field to a form:

# yourapp/forms.py
from ajax_select.fields import AutoCompleteSelectMultipleField

class DocumentForm(ModelForm):

    class Meta:
        model = Document

    tags = AutoCompleteSelectMultipleField('tags')

This will now work in the Django Admin.

To use a form outside, be sure to include form.media on the template where you place the form:

{{ form.media }}
{{ form }}

Read the full documention here: outside of the admin

Fully customizable

  • Customize search query
  • Query other resources besides Django ORM
  • Format results with HTML
  • Customize styling
  • Customize security policy
  • Add additional custom UI alongside widget
  • Integrate with other UI elements elsewhere on the page using the javascript API
  • Works in Admin as well as in normal views

Assets included by default

https://jquery.com/ 3.7.1 https://jqueryui.com/ 1.13.2

Customize jquery

To use a custom jQuery UI theme you can set:

# settings.py
AJAX_SELECT_JQUERYUI_THEME = "/static/path-to-your-theme/jquery-ui-min.css"

https://jqueryui.com/themeroller/

If you need to use a different jQuery or jQuery UI then turn off the default assets:

# settings.py
AJAX_SELECT_BOOTSTRAP = False

and include jquery and jquery-ui yourself, making sure they are loaded before the Django admin loads.

Compatibility

  • Django >=3.2
  • Python >=3.10

Contributors

Many thanks to all contributors and pull requesters !

https://github.com/crucialfelix/django-ajax-selects/graphs/contributors/

License

Dual licensed under the MIT and GPL licenses:

django-ajax-selects's People

Contributors

alligatortower avatar andyzickler avatar artscoop avatar buriy avatar cabalist avatar crucialfelix avatar gertingold avatar hwkns avatar jellonek avatar jmerdich avatar jmfederico avatar karlmoritz avatar leogout avatar madison-ookla avatar morr0350 avatar mzdeb avatar nwp90 avatar onyekaa avatar rlskoeser avatar sebslomski avatar sjrd avatar skrzypek avatar sourcefilter avatar squidsoup avatar teelee7133 avatar theunraveler avatar tlangens avatar xbello avatar zablotski avatar zvolsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-ajax-selects's Issues

Document the use in template for 'quick installation'

Hi,
I have been trying to go through the quick installation process to see if I could see myself using this project, and it turns out it is not complete: you do not explain how to put the forms in the templates. This is really too bad as it turns people away from going deeper into your app.
Could you please complete it?
Thanks in advance.

Add popup broken for custom AdminSites

The add popup feature only works for models registered with the default AdminSite.

E.g.

from django.contrib.admin import ModelAdmin, site, sites
from myapp import models


class MyModelAdmin(ModelAdmin):
    # ...
    pass
site.register(models.MyModel, MyModelAdmin)  # This one can use popup add

# # # # # # # #

class MyCustomAdminSite(sites.AdminSite):
    # ...
    pass
custom_admin_site = MyCustomAdminSite(name='custom_admin')

class MyOtherModelAdmin(ModelAdmin):
    # ...
    pass
custom_admin_site.register(models.MyOtherModel, MyOtherModelAdmin)  # This one cannot use popup add

Bug in ajax_selects.js (addKiller function call)

I might have found a bug in the ajax_selects.js file on line 18:

addKiller(ui.item.repr);

instead of

addKiller(ui.item.repr, ui.item.pk);

This causes an invalid id on the trash icon: id="kill_undefinedid_owner" when adding a new item.

parameters to triggers

The triggers don't provide any information on the event that has occurred.

Please consider something like this patch, which provides the id and the repr of the object being added or killed:

@@ -33,7 +33,7 @@ $.fn.autocompleteselect = function(options) {
                        $this.val(ui.item.pk);
                        $text.val('');
                        addKiller(ui.item.repr);
-                       $deck.trigger("added");
+                       $deck.trigger("added", [ui.item.pk,ui.item.repr]);

                        return false;
                }
@@ -49,7 +49,7 @@ $.fn.autocompleteselect = function(options) {
                        }
                        $("#" + killer_id).click(function() {
                                kill();
-                               $deck.trigger("killed");
+                               $deck.trigger("killed", [pk,repr]);
                        });
                }

@@ -90,7 +90,7 @@ $.fn.autocompleteselectmultiple = function(options) {
                                $this.val((prev ? prev : "|") + pk + "|");
                                addKiller(ui.item.repr, pk);
                                $text.val('');
-                               $deck.trigger("added");
+                               $deck.trigger("added",  [pk,ui.item.repr]);
                        }

                        return false;
@@ -103,7 +103,7 @@ $.fn.autocompleteselectmultiple = function(options) {

                        $("#"+killer_id).click(function() {
                                kill(pk);
-                               $deck.trigger("killed");
+                               $deck.trigger("killed", [pk,repr]);
                        });
                }

ContentNotRenderedError

This one is thrown on django 1.5 when the object that was created in a popup already exists:

The response content must be rendered before it can be accessed.
views.py in add_popup
if 'opener.dismissAddAnotherPopup' in response.content:

non operation with mongodb

Hi there

I have been using ajax-selects for a few days now, and I am very impressed.

I am also investigating django integration with mongodb via django-nonrel. There are a lot of django work that just don't work with this, ajax-selects is one of them. However after investigating this boiled down to the fact that it expects the 'id' field of models to be an integer, however the id's used in mongodb are strings, of the type '4f4de9d23cc2a30a23000010'.

After looking through your code I found that it is explicitly casting the id returned to, in one case a long:
ajax_select/fields.py, line 77,

return long(got)

and to an int:
ajax_select/init.py line 49

ids = [int(id) for id in ids]

After I made the mods, which removed the casting to integers it then succesfully worked with mongodb via the admin interface, with one caveat, after you have entered a value via the make_ajax_form interface and re-enter the model entry again via the admin interface it doesn't show the value that had been chosen, it is just blank, even though if you check the contents of the database it is still there. My guess the prefetch of the admin is also sensitive to integers.

I understand if you think it is not worth supporting, I am merely reporting my observation in case you do. My interest in ajax-selects stems from trying to traverse a very big database that mongodb is designed to handle.

Error on Pop-Up

I have a ajax-select field, which has the option to add a value at it's right. The pop-up with the form opens, and I try to save it.

I there is an error while saving the data, then the following exception take place:

Traceback (most recent call last):

  File "/home/otendor/envs/otendor-data/lib/python2.6/site-packages/Django-1.4-py2.6.egg/django/core/handlers/base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)

  File "/home/otendor/envs/otendor-data/lib/python2.6/site-packages/django_ajax_selects-1.2.4-py2.6.egg/ajax_select/views.py", line 65, in add_popup
    if 'opener.dismissAddAnotherPopup' in response.content:

  File "/home/otendor/envs/otendor-data/lib/python2.6/site-packages/Django-1.4-py2.6.egg/django/template/response.py", line 123, in _get_content
    raise ContentNotRenderedError('The response content must be '

ContentNotRenderedError: The response content must be rendered before it can be accessed.

ValueError: translation table must be 256 characters long

Using version 1.2.4, I get the following error when trying to use a ManyToManyField:

Exception Type: ValueError
Exception Value:    translation table must be 256 characters long
Exception Location: /opt/Projects/datamining/eggs/django_ajax_selects-1.2.4-py2.6.egg/ajax_select/fields.py in __init__, line 210

That seems to be a problem with the line that reads:

en_help = help_text.translate('en')

which doesn't seem to be valid Python: http://docs.python.org/library/string.html#string.translate

I would submit a patch but I'm not sure exactly what was even intended here.

thanks.

"Uncaught TypeError: Cannot read property 'autocomplete' of undefined"

Dear All,

I am getting an error upon using django_ajax_select. This happens as soon as the page is loaded and the error i seen in chrome Javascript console.

The error is indicated to be on this line of ajax_select.js

var proto = $.ui.autocomplete.prototype,
initSource = proto._initSource;

The error is "Uncaught TypeError: Cannot read property 'autocomplete' of undefined"

I am using jquery-1.11.2.min.js and I have also includes the js that come with django_ajax_select viz
bootstrap.js and ajax_select.js

Please help. Below is the chrome screenshot.

image

Field appers duplicated when marked as readonly in admin

I have a field that can only be selected upon creation, so I am using the technique described in http://stackoverflow.com/a/4346448/578749 to make it readonly when editing:

class MyModelAdmin(admin.ModelAdmin):
    #...
    def get_readonly_fields(self, request, obj=None):
        if obj: # editing an existing object
            return self.readonly_fields + ('my_ajax_field')
        return self.readonly_fields

The problem is that the AJAX field, from a form created with make_ajax_form, appears duplicated when changed to readonly like this.

Please add a change trigger to the target.

Hi there,

I'm trying to do some ajax work after your field gets filled but changes in value of hidden elements don't automatically fire the .change() event. Would it be possible to change your triggers from 'added' and 'killed' to simply 'changed'? I'm not sure where 'added' or 'killed' is documented as standard event types but I couldn't find any references http://api.jquery.com/category/events/ [here] or http://www.quirksmode.org/dom/events/ [here].

Thanks!!

DeprecationWarning django.utils.simplejson

With django 1.6:

/usr/lib/python2.7/dist-packages/ajax_select/fields.py:12: DeprecationWarning: django.utils.simplejson is deprecated; use json instead.
from django.utils import simplejson

search_fields like in ModelAdmin

I think search_field should be replaced by a search_fields that works like the one in the ModelAdmin. It would make django-ajax-selects more consistent with the django API.

Here is how it can be achieved. I mostly adapted code from django/contrib/admin/views/main.py. I also added support for ordering.

import operator
from django.db.models import Q
from django.contrib.admin.util import lookup_needs_distinct
from ajax_select import LookupChannel

class LookupChannelExtended(LookupChannel):

    def __init__(self, *args, **kwargs):
        self.lookup_opts = self.model._meta
        self.root_query_set = self.model.objects.all()
        super(LookupChannel, self).__init__(*args, **kwargs)

    def get_ordering(self, request, queryset):
        """
        Returns the list of ordering fields. First we check the object's default
        ordering. Then, any manually-specified ordering overrides anything.
        Finally, a deterministic order is guaranteed by ensuring the primary key
        is used as the last ordering field.
        """
        ordering = []
        if self.lookup_opts.ordering:
            ordering = self.lookup_opts.ordering
        if hasattr(self, 'ordering'):
            ordering += list(self.ordering)
        # Ensure that the primary key is systematically present in the list of
        # ordering fields so we can guarantee a deterministic order across all
        # database backends.
        pk_name = self.lookup_opts.pk.name
        if not (set(ordering) & set(['pk', '-pk', pk_name, '-' + pk_name])):
            # The two sets do not intersect, meaning the pk isn't present. So
            # we add it.
            ordering.append('pk')

        return ordering

    def get_query(self, query, request):
        qs = self.root_query_set
        use_distinct = False

        # Set ordering.
        ordering = self.get_ordering(request, qs)
        qs = qs.order_by(*ordering)

        # Apply keyword searches.
        def construct_search(field_name):
            if field_name.startswith('^'):
                return "%s__istartswith" % field_name[1:]
            elif field_name.startswith('='):
                return "%s__iexact" % field_name[1:]
            elif field_name.startswith('@'):
                return "%s__search" % field_name[1:]
            else:
                return "%s__icontains" % field_name

        if self.search_fields and query:
            orm_lookups = [construct_search(str(search_field))
                           for search_field in self.search_fields]
            for bit in query.split():
                or_queries = [Q(**{orm_lookup: bit})
                              for orm_lookup in orm_lookups]
                qs = qs.filter(reduce(operator.or_, or_queries))
            if not use_distinct:
                for search_spec in orm_lookups:
                    if lookup_needs_distinct(self.lookup_opts, search_spec):
                        use_distinct = True
                        break

        if use_distinct:
            return qs.distinct()
        else:
            return qs

You can now do something like this:

class MemberLookup(LookupChannelExtended):
    model = Individual
    search_fields = ('first_name', 'middle_name', 'last_name')
    ordering = ('last_name', 'first_name')

Support reverse relationships

hi and thanks for the great project! I'd like to be able to query from the M2M on the other side of the relationship in the admin which doesn't currently work in master. Give me a second and I'll put up a patch.

__init__() got an unexpected keyword argument 'mimetype'

I am on Django 1.7.4 and django_ajax_select gives me an error.

The error is

init() got an unexpected keyword argument 'mimetype'

The complete stack trace is as below. What could i do to resolve this error? Could this be an issue in Django?

Is it ok that a GET is called instead of a POST. Does django_ajax_select does a GET and not POST? Please help.

TypeError at /autocomplete/lookup/ajax_lookup/TableItemLookup
init() got an unexpected keyword argument 'mimetype'

Request Method: GET
Request URL: http://127.0.0.1:8999/RESTO/autocomplete/lookup/ajax_lookup/TableItemLookup?term=Sam
Django Version: 1.7.4
Python Executable: C:\Apache Software Foundation\Apache2.2\bin\httpd.exe
Python Version: 2.7.6
Python Path: ['C:\Python27\lib\site-packages\setuptools-2.0.1-py2.7.egg', 'C:\Python27\lib\site-packages\django_debug_toolbar-0.11.0-py2.7.egg', 'C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg', 'C:\Python27\lib\site-packages\suds_jurko-0.6-py2.7.egg', 'C:\Python27\lib\site-packages\elaphe-0.6.0-py2.7.egg', 'C:\Python27\lib\site-packages\pillow-2.3.0-py2.7-win32.egg', 'C:\Python27\lib\site-packages\ghostscript-0.5dev-py2.7.egg', 'C:\Python27\lib\site-packages\south-0.8.3-py2.7.egg', 'C:\Python27\lib\site-packages\crochet-1.0.0-py2.7.egg', 'C:\Python27\lib\site-packages\django_ajax_selects-1.3.4-py2.7.egg', 'C:\Python27\lib\site-packages\scrapy-0.22.2-py2.7.egg', 'C:\Python27\lib\site-packages\six-1.7.2-py2.7.egg', 'C:\Python27\lib\site-packages\cssselect-0.9.1-py2.7.egg', 'C:\Python27\lib\site-packages\pyopenssl-0.14-py2.7.egg', 'C:\Python27\lib\site-packages\queuelib-1.1.1-py2.7.egg', 'C:\Python27\lib\site-packages\w3lib-1.6-py2.7.egg', 'C:\Python27\lib\site-packages\python_dateutil-1.5-py2.7.egg', 'C:\Python27\lib\site-packages\memory_profiler-0.32-py2.7.egg', 'C:\Python27\lib\site-packages\cython-0.21.1-py2.7-win32.egg', 'C:\Python27\lib\site-packages\line_profiler-1.0-py2.7-win32.egg', 'C:\Python27\lib\site-packages\pika-0.9.14-py2.7.egg', 'C:\Python27\lib\site-packages\pyws-1.1.5-py2.7.egg', 'C:\Python27\lib\site-packages\nose-1.3.4-py2.7.egg', 'C:\Python27\lib\site-packages\jinja2-2.7.3-py2.7.egg', 'C:\Python27\lib\site-packages\httplib2-0.9-py2.7.egg', 'C:\Python27\lib\site-packages\argparse-1.3.0-py2.7.egg', 'C:\Python27\lib\site-packages\markupsafe-0.23-py2.7-win32.egg', 'C:\Python27\lib\site-packages\soapfish-0.6dev-py2.7.egg', 'C:\Python27\lib\site-packages\soapbox-0.3.8.dev-py2.7.egg', 'C:\Python27\lib\site-packages\num2words-0.5.2-py2.7.egg', 'C:\Python27\lib\site-packages\unidecode-0.04.17-py2.7.egg', 'C:\Windows\system32\python27.zip', 'C:\Python27\Lib', 'C:\Python27\DLLs', 'C:\Python27\Lib\lib-tk', 'C:\Apache Software Foundation\Apache2.2', 'C:\Apache Software Foundation\Apache2.2\bin', 'C:\Python27', 'C:\Python27\lib\site-packages', 'C:\Python27\lib\site-packages\PIL', 'C:\Python27\lib\site-packages\win32', 'C:\Python27\lib\site-packages\win32\lib', 'C:\Python27\lib\site-packages\Pythonwin', 'D:/RESTO/RESTO..', 'D:/RESTO/RESTO', 'D:/RESTO/RESTO..']
Server time: Fri, 27 Feb 2015 03:04:44 -0300
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'RESTO_App',
'ajax_select')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response

  1.                 response = wrapped_callback(request, _callback_args, *_callback_kwargs)
    
    File "C:\Python27\lib\site-packages\django_ajax_selects-1.3.4-py2.7.egg\ajax_select\views.py" in ajax_lookup
  2. return HttpResponse(results, mimetype='application/javascript')
    
    File "C:\Python27\lib\site-packages\django\http\response.py" in init
  3.     super(HttpResponse, self).**init**(_args, *_kwargs)
    

Exception Type: TypeError at /autocomplete/lookup/ajax_lookup/TableItemLookup
Exception Value: init() got an unexpected keyword argument 'mimetype'
Request information:
GET:
term = u'Sam'

POST: No POST data

FILES: No FILES data

COOKIES:
csrftoken = '5ZMf6xaGtSuWG9MASQVagsqPQ61puPAh'
sessionid = 'cno7s0h8slwvr7zbvs3laddhiff2hf0p'

META:
wsgi.multiprocess = False
HTTP_REFERER = 'http://127.0.0.1:8999/RESTO/manage_individual_table'
SERVER_PROTOCOL = 'HTTP/1.1'
SERVER_SOFTWARE = 'Apache/2.2.25 (Win32) mod_wsgi/3.3 Python/2.7.6 mod_fcgid/2.3.6'
SCRIPT_NAME = u'/RESTO'
mod_wsgi.handler_script = ''
SERVER_SIGNATURE = ''
REQUEST_METHOD = 'GET'
PATH_INFO = u'/autocomplete/lookup/ajax_lookup/TableItemLookup'
SystemRoot = 'C:\Windows'
QUERY_STRING = 'term=Sam'
HTTP_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'
HTTP_CONNECTION = 'keep-alive'
HTTP_COOKIE = 'sessionid=cno7s0h8slwvr7zbvs3laddhiff2hf0p; csrftoken=5ZMf6xaGtSuWG9MASQVagsqPQ61puPAh'
SERVER_NAME = '127.0.0.1'
REMOTE_ADDR = '127.0.0.1'
mod_wsgi.request_handler = 'wsgi-script'
wsgi.url_scheme = 'http'
PATH_TRANSLATED = 'C:\Apache Software Foundation\Apache2.2\htdocs\autocomplete\lookup\ajax_lookup\TableItemLookup'
SERVER_PORT = '8999'
mod_wsgi.version =
mod_wsgi.input_chunked = '0'
SERVER_ADDR = '127.0.0.1'
DOCUMENT_ROOT = 'C:/Apache Software Foundation/Apache2.2/htdocs'
mod_wsgi.process_group = ''
COMSPEC = 'C:\Windows\system32\cmd.exe'
HTTP_X_REQUESTED_WITH = 'XMLHttpRequest'
SCRIPT_FILENAME = 'D:/RESTO/RESTO/wsgi.py'
wsgi.input = <mod_wsgi.Input object at 0x04C12F98>
HTTP_HOST = '127.0.0.1:8999'
mod_wsgi.callable_object = 'application'
wsgi.multithread = True
PATHEXT = '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC'
REQUEST_URI = '/RESTO/autocomplete/lookup/ajax_lookup/TableItemLookup?term=Sam'
HTTP_ACCEPT = 'application/json, text/javascript, /; q=0.01'
WINDIR = 'C:\Windows'
wsgi.version =
GATEWAY_INTERFACE = 'CGI/1.1'
wsgi.run_once = False
wsgi.errors = <mod_wsgi.Log object at 0x04BEA1D8>
REMOTE_PORT = '55837'
HTTP_ACCEPT_LANGUAGE = 'en-US,en;q=0.8,es-419;q=0.6,es;q=0.4'
mod_wsgi.application_group = '192.168.1.101:8999|/resto'
mod_wsgi.script_reloading = '1'
wsgi.file_wrapper = ''
CSRF_COOKIE = u'5ZMf6xaGtSuWG9MASQVagsqPQ61puPAh'
HTTP_ACCEPT_ENCODING = 'gzip, deflate, sdch'

Settings:
Using settings module RESTO.settings
USE_L10N = True
USE_THOUSAND_SEPARATOR = False
CSRF_COOKIE_SECURE = False
LANGUAGE_CODE = 'en-us'
ROOT_URLCONF = 'RESTO.urls'
MANAGERS =
BASE_DIR = 'D:/RESTO/RESTO..'
TEST_NON_SERIALIZED_APPS = []
DEFAULT_CHARSET = 'utf-8'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
STATIC_ROOT = 'D:\RESTO\staticfiles'
ALLOWED_HOSTS = []
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
EMAIL_SUBJECT_PREFIX = '[Django] '
SEND_BROKEN_LINK_EMAILS = False
STATICFILES_FINDERS =
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'sessionid'
ADMIN_FOR =
TIME_INPUT_FORMATS =
DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'AUTOCOMMIT': True, 'ATOMIC_REQUESTS': False, 'NAME': 'RESTO', 'CONN_MAX_AGE': 0, 'TIME_ZONE': 'UTC', 'PORT': '5432', 'HOST': 'localhost', 'USER': 'postgres', 'TEST': {'COLLATION': None, 'CHARSET': None, 'NAME': None, 'MIRROR': None}, 'PASSWORD': u'', 'OPTIONS': {}}}
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None
FILE_UPLOAD_PERMISSIONS = None
FILE_UPLOAD_HANDLERS =
DEFAULT_CONTENT_TYPE = 'text/html'
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
AJAX_SELECT_BOOTSTRAP = True
APPEND_SLASH = True
LOCALE_PATHS =
DATABASE_ROUTERS = []
DEFAULT_TABLESPACE = ''
YEAR_MONTH_FORMAT = 'F Y'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
SERVER_EMAIL = 'root@localhost'
SESSION_COOKIE_PATH = '/'
SILENCED_SYSTEM_CHECKS = []
MIDDLEWARE_CLASSES =
USE_I18N = True
THOUSAND_SEPARATOR = ','
SECRET_KEY = u'**
'
LANGUAGE_COOKIE_NAME = 'django_language'
DEFAULT_INDEX_TABLESPACE = ''
TRANSACTIONS_MANAGED = False
LOGGING_CONFIG = 'logging.config.dictConfig'
TEMPLATE_LOADERS =
FIRST_DAY_OF_WEEK = 0
WSGI_APPLICATION = 'RESTO.wsgi.application'
TEMPLATE_DEBUG = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
CSRF_COOKIE_NAME = 'csrftoken'
FORCE_SCRIPT_NAME = None
USE_X_FORWARDED_HOST = False
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_DOMAIN = None
FILE_CHARSET = 'utf-8'
DEBUG = True
LANGUAGE_COOKIE_DOMAIN = None
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
INSTALLED_APPS =
LANGUAGES =
COMMENTS_ALLOW_PROFANITIES = False
STATICFILES_DIRS =
PREPEND_WWW = False
SECURE_PROXY_SSL_HEADER = None
LANGUAGE_COOKIE_AGE = None
SESSION_COOKIE_HTTPONLY = True
DEBUG_PROPAGATE_EXCEPTIONS = False
INTERNAL_IPS =
CACHE_MIDDLEWARE_ALIAS = 'default'
MONTH_DAY_FORMAT = 'F j'
LOGIN_URL = '/accounts/login/'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
TIME_FORMAT = 'P'
AUTH_USER_MODEL = 'auth.User'
DATE_INPUT_FORMATS =
AUTHENTICATION_BACKENDS = 'django.contrib.auth.backends.ModelBackend'
EMAIL_HOST_PASSWORD = u'**
'
PASSWORD_RESET_TIMEOUT_DAYS = u'**
'
SESSION_FILE_PATH = None
AJAX_LOOKUP_CHANNELS = {'TableItemLookup': ('RESTO_App.lookup', 'ItemLookUp')}
SESSION_SAVE_EVERY_REQUEST = False
NUMBER_GROUPING = 0
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
CSRF_COOKIE_PATH = '/'
LOGIN_REDIRECT_URL = '/accounts/profile/'
DECIMAL_SEPARATOR = '.'
IGNORABLE_404_URLS =
MIGRATION_MODULES = {}
TEMPLATE_STRING_IF_INVALID = ''
LOGOUT_URL = '/accounts/logout/'
EMAIL_USE_TLS = False
FIXTURE_DIRS =
EMAIL_HOST = 'localhost'
DATE_FORMAT = 'N j, Y'
MEDIA_ROOT = ''
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
ADMINS =
FORMAT_MODULE_PATH = None
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
MEDIA_URL = ''
DATETIME_FORMAT = 'N j, Y, P'
TEMPLATE_DIRS =
DISALLOWED_USER_AGENTS =
ALLOWED_INCLUDE_ROOTS =
LOGGING = {}
SHORT_DATE_FORMAT = 'm/d/Y'
AJAX_SELECT_INLINES = 'inline'
CACHE_MIDDLEWARE_KEY_PREFIX = u'**
'
TIME_ZONE = 'UTC'
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_SSL = False
TEMPLATE_CONTEXT_PROCESSORS =
SESSION_COOKIE_AGE = 1209600
SETTINGS_MODULE = 'RESTO.settings'
USE_ETAGS = False
LANGUAGES_BIDI =
FILE_UPLOAD_TEMP_DIR = None
CSRF_COOKIE_AGE = 31449600
STATIC_URL = '/static_resto/'
EMAIL_PORT = 25
USE_TZ = True
SHORT_DATETIME_FORMAT = 'm/d/Y P'
PASSWORD_HASHERS = u'**
***'
ABSOLUTE_URL_OVERRIDES = {}
LANGUAGE_COOKIE_PATH = '/'
CACHE_MIDDLEWARE_SECONDS = 600
CSRF_COOKIE_HTTPONLY = False
DATETIME_INPUT_FORMATS =
EMAIL_HOST_USER = ''
PROFANITIES_LIST = u'**
*****************'

You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will
display a standard 500 page.

Regression? Or UUID PK not supported

I am using UUIDs as my PK, which (if I read earlier bug threads correctly) is currently supported. However, I do get a ValueError invalid literal for long() with base 10: (myUUIDpk)

stacktrace:

Environment:


Request Method: POST
Request URL: http://localhost:8000/admin/api/contest/8b668f5e-78e3-4a47-ae39-6d8670ee8b8c/

Django Version: 1.7.3
Python Version: 2.7.9
Installed Applications:
('utils',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'django.contrib.humanize',
 'timezone_field',
 'ajax_select',
 'corsheaders',
 'noncense',
 'rest_framework',
 'apps.api')
Installed Middleware:
('corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
  583.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
  206.             return view(request, *args, **kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
  1456.         return self.changeform_view(request, object_id, form_url, extra_context)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/db/transaction.py" in inner
  394.                 return func(*args, **kwargs)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
  1403.             if all_valid(formsets) and form_validated:
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/forms/formsets.py" in all_valid
  438.         if not formset.is_valid():
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/forms/formsets.py" in is_valid
  303.         self.errors
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/forms/formsets.py" in errors
  277.             self.full_clean()
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/forms/formsets.py" in full_clean
  326.             self._errors.append(form.errors)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/forms/forms.py" in errors
  154.             self.full_clean()
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  353.         self._clean_fields()
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/django/forms/forms.py" in _clean_fields
  362.             value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/ajax_select/fields.py" in value_from_datadict
  108.             return _to_number(got)
File "/Users/dbinetti/.virtualenvs/barberscore/lib/python2.7/site-packages/ajax_select/fields.py" in _to_number
  26.         return long(got)

Exception Type: ValueError at /admin/api/contest/8b668f5e-78e3-4a47-ae39-6d8670ee8b8c/
Exception Value: invalid literal for long() with base 10: '85b428e2-611c-47d4-9a19-1133d3746665'

'set' object does not support indexing

Hello.

I'm trying to use make_ajax_field() for the autocompletion. I have followed the installation instruction as well as the example app thoroughly. I keep getting the error 'set' object does not support indexing. What is this related to? Any insight would be very helpful.

These are my settings and codes:

settings.py

Settings for ajax_select

AJAX_LOOKUP_CHANNELS = {
'client_lookup': {'client.lookups','ClientLookup'},
'driver_lookup': {'driver.lookups','DriverLookup'},
}

admin.py

class LoadingAdmin(AjaxSelectAdmin):
form = LoadingForm

forms.py

from django import forms
from ajax_select import make_ajax_field
from data_entry.models import Loading

class LoadingForm(forms.ModelForm):

class Meta:
    model = Loading

client = make_ajax_field(Loading, 'client', 'client_lookup')

lookups.py

from django.db.models import Q
from django.utils.html import escape
from client.models import Client
from ajax_select import LookupChannel

class ClientLookup(LookupChannel):

model = Client

def get_query(self, q, request):
    return Client.objects.filter(Q(name__icontains=q)).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 u"%s<div><i>%s</i></div>" % (escape(obj.name), escape(obj.address))
    # 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.name), escape(obj.address))

PS: I have enabled db_index=True in the 'name' field that I'm trying to search.

Does not work with jquery-ui >= 1.10.2

I haven't yet had a chance to investigate in full detail, but noticed when I upgraded to:

http://code.jquery.com/jquery-1.9.1.js
http://code.jquery.com/ui/1.10.2/jquery-ui.js

I get the error:

Uncaught TypeError: Cannot set property '_renderItem' of undefined

As this same code works fine with previous versions of jquery and jquery-ui, I am assuming that something has changed to break this.

Alternatively, I might have broken something too... Need to double check.

Fire the change event on selection

In ajax_select.js, adding the line:

$this.change();

after

$this.val(ui.item.pk);

allows other js elements in the forms to pick up on the changed value. This makes smart_select play nice, for example.

AutoCompleteSelectField has no attribute 'limit_choices_to' in Django 1.7

This error has just happened in the admin.
My code for my ModelAdmin is

form = make_ajax_form([...])

While this worked in Django 1.6, 1.7 has introduced a

limit_choices_to = formfield.limit_choices_to

which is called on the AutoCompleteSelectField (at least), although it has no limit_choices_to attribute. I added this line at the end

f.limit_choices_to = None

in make_ajax_field and it fixes the problem, but I don't know if this is the way to go.

Issue with Ajax-Search on Media-Fields

Hi,
I've got an Issue if I try to use django-ajax-selects on a media-field.
Django breaks with following stack-trace:

File "/home/vagrant/edn-venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  91.                     response = view_func(request, *args, **kwargs)
File "/home/vagrant/edn-venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  21.                 return func(self, *args2, **kwargs2)
File "/home/vagrant/edn-venv/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
  223.                 return func(*args, **kwargs)
File "/home/vagrant/edn-venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
  1127.         media = self.media + adminForm.media
File "/home/vagrant/edn-venv/local/lib/python2.7/site-packages/django/contrib/admin/helpers.py" in _media
  66.             media = media + fs.media

Exception Type: TypeError at /admin/edn_server/location/199737/
Exception Value: unsupported operand type(s) for +: 'AutoCompleteSelectMultipleField' and 'Media'

I found a fix for this issue in the old Bugtracking on google code( https://code.google.com/p/django-ajax-selects/issues/detail?id=80) , but though it works I am not totally happy with it and still do not thoroughly understand the underlying problem.
Also I would not be surprised, if this issue is in my code and I'm kind of 'holding it wrong' :-(

cheers,
nfoonf

Set width of jquery autocomplete widget

The autocompletion options seem match the width of the width of the text box by default: http://i.imgur.com/6YoCj.png

I can't figure out how to make it wider (like in the screenshot from the README.md) besides some ugly css hacks (that involve !important, yuck)...

It looks like the best way to do it in real life is sort of hackish, through the open event: http://jsfiddle.net/salman/gP7Ns/ However, specifying a javascript function through plugin_options isn't possible (it just comes out as an escaped string).

Suggested fix: not sure... Maybe an option to include that open hackage with the width as a parameter...

dj1.4 Error importing template source loader django.template.loaders.filesystem.load_template_source:

Did default installation using ./install.sh. With Django 1.4 shows a problem akin to this - vintasoftware/django-templated-email#11 but does not get fixed on removal of that or other template loaders.

So tried with Django 1.3 and while admin page loads, logging in fails with below error:
ValueError at /admin/
too many values to unpack

  1. algo, salt, hsh = enc_password.split('$')
    

The password used was 9 lettered with 3 digits in it. So changed it to 'dog' and it showed that 'auth_message' did not exist. That must be due to the 1.4 to 1.3 downgrade. So ran syncdb again and there I could log-in.

So while I did get it to work, you might want to add this somewhere for 1.4 compatibility or change install.sh to deploy only django 1.3 unless you can figure out what is causing the template loader issues or password issue.

fixed bug: AutoCompleteSelectMultipleField does not honor 'widget' parameter

AutoCompleteSelectMultipleField overwrites its kwargs['widget'] with its default AutoCompleteSelectMultipleWidget so there it's not possible to customize the widget in your form definition.

This seems to be a bug since the other ajax-select fields: AutoCompleteSelectWidget and AutoCompleteField both allow substituting the default widget with your own, just like django. Widget substitution is useful especially when you want to change placeholder attribute or CSS attributes of the default widget.

I have fixed it in this commit taivo@a24dc27 but not sure how to submit a second pull request since I've already have one in the pipeline.

Last but not least, I find this package to be extremely useful. I wasted a lot of time getting autocomplete done on an adhoc basis, and even more time trying generalize all the adhoc code. Good thing I found ajax-select before going too far into reinventing the wheel. So thanks for maintaining this tool!

Inline won't work with new lines (SOLVED)

Hi,
Recently I've been having troubles with django-ajax-selects and inline forms.
The problem was, that when I add a new line it ajax-selects wont bind to it.
I spent hours for searching the cause in the internet, and maybe fixes. I only found that this issue was once a problem, but now resolved (and from the documentation django-ajax-selects should work with inlines).
So, I started debugging the code.
What I found is that django-ajax-selects DOES bind new lines when you click the 'add another' link, and this code is in the $(document).ready(); function.
However, by alerting one line above this call I saw that the 'add another' link was not yet built. So the binding to the link won't catch.
What I did to fix this issue was to to change the 'on' event to 'delegate' so future selectors (like our 'add another') would be bound.

In ajax_selects.js change lines 206-209 with these:

$('body').delegate( '.inline-group ul.tools a.add, .inline-group div.add-row a, .inline-group .tabular tr.add-row td a', 'click', function() {
$(window).trigger('init-autocomplete');
});

Custom form

Hi,

I am trying to make this work with a custom form and I am having some difficulties...

Here is my forms.py:

class MemberTeamForm(forms.ModelForm):

member = make_ajax_field(MemberTeam, 'member', 'members', help_text=None)

class Meta:
    model = MemberTeam

lookups.py:
class MemberLookup(LookupChannel):

model = Member

def get_query(self, q, request):
    return Member.objects.filter(Q(first_name__icontains=q) | Q(last_name__icontains=q)).order_by('last_name', 'first_name')

def get_result(self, obj):
    return unicode(obj)

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

def format_item_display(self, obj):
    return "%s, %s" % (escape(obj.last_name), escape(obj.first_name))

Here is an example of the field I get in the template:

But for some reason, I don't get any suggestions when I type...

Am I missing something?

Thanks,
Ara

Issues when using django-admin-sortable

My apologies as I'm pretty useless when it comes to the front end but there's an odd problem when running with django-admin-sortable. I don't have a fully understanding of the problem yet.

I'll update when I can get more details.

deck area

could not show the deck area. how to display them? do i need to add some extra information to show them?

callbacks for select doesn't work

It seems that when a choice is selected from the drop down a callback "added" should be triggered, but I'm unable to bind my code to it, neither binding like this:
$("#{{ html_id }}").bind('added', function(){})

or this:
$("#{{ html_id }}_on_deck").bind('added', function(){})

Is this by design or this a bug? Or am I doing smth wrong?

Custom validation with django-ajax-selects

How can I add custom validation in my admin form using ajax-selects? E.g., I need to validate unique together (Django 1.6 don't raise exception in this case, but I think 1.7 do). When I use a custom form, the + button doesn't work.

Initial fields are duplicated when new row added.

This plugin initializes the field using a data-plugin-options attribute, which is a stringified object with a property called initial. The initial array is used to populate the field when instantiated. The bug arises when any new row is added, which kicks off the same javascript that initializes the regions field.

Perhaps after initialization, an attribute could be added to indicate the element should not be initialized again.

Pass `request` to `LookupChannel` methods, make overriding easier

It would be great to have access to the request and the query in LookupChannel methods, for example:

def format_match(self, obj, request, query):
    """ (HTML) formatted item for displaying item in the dropdown """
    html = unicode(obj)
    html = html.replace(query, "<strong>%s</strong>" % query)
    return html

it would also be nice if the ajax_lookup view was a class-based view that got the results to simplejson from a method, making it easier to override instead of replace:

def get(self, *args, **kwargs):
    ...
    return HttpResponse(simplejson.dumps([self.get_item_context(item, query) for item in instances])

def get_item_context(self, item, query):
    return {
        'pk': unicode(getattr(item,'pk',None)),
        'value': lookup.get_result(item, self.request, query),
        'match' : lookup.format_match(item, self.request, query),
        'repr': lookup.format_item_display(item, self.request, query)
    }

Any chance?

Support lookup channels from third-party apps

We have some internal third party apps that we use in other apps in our eco system. The problem is that the AJAX_LOOKUP_CHANNELS is required to be in the settings.py in order for it to work and that means we constantly have to copy those channels in our main app and keep them up to date. So we wrote:

https://github.com/peterfarrell/django-ajax-selects-autodiscover

This allows us to autodiscover any channels in installed apps by looking for a AJAX_LOOKUP_CHANNELS in each lookup.py.

In your settings.py file, replace your AJAX_LOOKUP_CHANNELS with:

from ajax_selects_autodiscover import AutoDiscover

AJAX_LOOKUP_CHANNELS = AutoDiscover()

The lookup.py files is now where you define all your channels. Here is an example:

from ajax_select import LookupChannel

from login.models import Application


class ApplicationLookup(LookupChannel):
    model = Application

    def get_query(self, q, request):
        return Application.objects.find_active_by_name(q)


AJAX_LOOKUP_CHANNELS = {
    'application': ('shared.lookup', 'ApplicationLookup'),
}

avoid warning when installing via pip

when installing using pip this output is posted:

no previously-included directories found matching 'example/AJAXSELECTS
no previously-included directories found matching 'example/ajax_select'

this is harmless, but I'd like to know why it happens. something to do with the Manifest and the purge lines

Autocomplete widget for multiple select not reloading upon form error

My setup includes autoselect for ManyToMany field, which is part of the form. Upon form error, the form is reloaded (displaying e.g. error messages), but the autoselect widget does not show any selected items.
I'm not sure it's a bug, but could be.
(Otherwise, works like charm, so many thanks for your hard work!)

Limit number of results returned by lookup and auto load additional results when user scrolls to bottom of list

@crucialfelix

In our app we have > 100k names of persons that we would like to be able to search for using ajax_selects.

The current implementation would, in worst case scenarios, result in a major performance drop as the lookup would return far too many items.

I am currently working on a PR that will

  • load only a given number of items from the server with each request (limit)
  • load additional items from the server as soon as the user scrolls down to the bottom of the list (offset)

I still need to flesh things out but I wonder whether such a PR would be appreciated and how soon it could be integrated into the master once all issues have been resolved.

Thanks!

django inline formset

Hello,
In the UI django-ajax_select only works with the pre-loaded django-inline-formset rows; It doesn't work with the other rows that are added with "add another".

Any help in this will be appreciated.

Here is the form:


class CoachingForm(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super(CoachingForm, self).__init__(*args, **kwargs)

    def add_fields(self, form, index):
        super(CoachingForm, self).add_fields(form, index)
        form.fields["sport"] = AutoCompleteSelectField('sport', required=True)
        form.fields["high_school"] = AutoCompleteSelectField('high_school', required=True)


CoachingFormSet = inlineformset_factory(Coach, Coaching, formset=CoachingForm, extra=1, can_delete=True )

Thank you

error 'this.data("autocomplete") is undefined'

Hello,

I have an AutoCompleteSelectMultipleField and after rendering, I'm getting the above javascript error in my browser console and the autocomplete field doesn't seem to work at all. As far as I can tell I've included the proper jquery files. I've set AJAX_SELECT_INLINES to True and it seems that ajax_select.js is getting pulled in properly.

Any ideas??

thanks!

format_match did not work with django-ajax-select 1.3.3

class ProductLookup(object):
   ...
    def get_result(self, obj):
        return 'A'

    def format_item_display(self, obj):
        return 'B'

    def format_match(self, obj):
        return 'C'

JSON:

[{"pk": "1", "match": "C", "value": "A", "repr": "B"}] 

Autocomplete 1.3.3 in dropdown lis display only "A" and "B", but not "C".
In django-ajax-select1.2.5 in dropdown list was "C".

What I'm doing wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.