Giter Site home page Giter Site logo

yourlabs / django-autocomplete-light Goto Github PK

View Code? Open in Web Editor NEW
1.8K 66.0 463.0 12.51 MB

A fresh approach to autocomplete implementations, specially for Django. Status: v4 alpha, v3 stable, v2 & v1 deprecated.

Home Page: https://django-autocomplete-light.readthedocs.io

License: MIT License

Python 82.06% JavaScript 10.58% Shell 0.80% CSS 4.35% HTML 2.21%
python django autocomplete

django-autocomplete-light's Introduction

image

image

image

image

Features

  • Django 4.2 support starting DAL 3.10, support for earlier Django versions in DAL < 3.10
  • Django (multiple) choice support,
  • Django (multiple) model choice support,
  • Django generic foreign key support (through django-querysetsequence),
  • Django generic many to many relation support (through django-generic-m2m and django-gm2m)
  • Multiple widget support: select2.js, easy to add more.
  • Creating choices that don't exist in the autocomplete,
  • Offering choices that depend on other fields in the form, in an elegant and innovative way,
  • Dynamic widget creation (ie. inlines), supports YOUR custom scripts too,
  • Provides a test API for your awesome autocompletes, to support YOUR custom use cases too,
  • A documented automatically tested example for each use case in test_project.

Resources

django-autocomplete-light's People

Contributors

adamchainz avatar andybak avatar bernd-wechner avatar blueyed avatar coredumperror avatar danielmorell avatar emesik avatar eraldo avatar fraimondo avatar fruitschen avatar gagarski avatar huxley avatar jackatomenapps avatar jonashaag avatar jor-rit avatar jpic avatar luzfcb avatar mariocesar avatar melvyn-sopacua avatar mhuailin avatar mitchelljkotler avatar mogost avatar monim67 avatar morenoh149 avatar mpasternak avatar saex avatar ticosax avatar trumpet2012 avatar vibragiel avatar wgordon17 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  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

django-autocomplete-light's Issues

Empty the widget when no matches found

Right now, when you start typing, the widget fills with the choices that match the query. But if you continue typing to the point where no choice matches the query, the widget keeps showing the choices that last matched.

For example, if I type "Austr" in a country autocomplete field, the widget shows Australia and Austria. If I go on and type "Austrafasdlkfjasld", the widget keeps showing Australia and Austria.

Shouldn't it be emptied, perhaps showing a No matches found message?

Not compatible with django-admintools-bootstrap

django-autocomplete-light isn't compatible with django-admintools-bootstrap.
the form on the django admin will produce two input widget next to each-other, One input[text] field which is from autocomplete-light and second one is an empty .

JSON decode Error for test_remote_project demo

Perhaps this is linked to the fact I'm using python 2.6 :

[07/Nov/2012 02:16:50] "GET /cities_light/city/?q=res&limit=20&format=json HTTP/1.0" 404 2222
Internal Server Error: /autocomplete/CityRestAutocomplete/
Traceback (most recent call last):
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/django/views/generic/base.py", line 48, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/django/views/generic/base.py", line 69, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/autocomplete_light/views.py", line 52, in get
    return http.HttpResponse(autocomplete.autocomplete_html())
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/autocomplete_light/autocomplete/base.py", line 94, in autocomplete_html
    for choice in self.choices_for_request():
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/autocomplete_light/autocomplete/rest_model.py", line 71, in choices_for_request
    for choice in self.get_remote_choices(slots):
  File "/home/dom/.virtualenvs/acl/lib/python2.6/site-packages/autocomplete_light/autocomplete/rest_model.py", line 96, in get_remote_choices
    for data in simplejson.loads(body):
  File "/usr/lib/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.6/json/decoder.py", line 338, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Enhance AutocompleteModelBase with a couple of shortcuts

AutocompleteModelBase expects choices to be models.

It could check if choice has a get_absolute_url method, and add a popup link to that.

Also, it could check if choice has a get_absolute_update_url and add a popup link to that too.

field_to parameter in model

Hi,

My problem is a little bit complicated... I'll try to explain it, but english is not my native language...

I've created a model containing buildings, which have addresses. The addresses are connected to an address table. I've as lines as addresses in my address table, pk is declared to an 'id' integer (auto incremental) field.
As I've near 30 000 addresses, I would like to use django-autocomplete-light to perform buildings creation / update, to select the address.

Important : I do not use the admin interface to create/update my buildings, but CreateView / UpdateView !

I would like to record the string address as a string (not an id) into the buildings : I can although select a building with near all data without to select the adress from the related adress table.

As explained in django documentation, I use the 'field_to' parameter in the building.address field, to link this field to the address.address field.

When I tryed to create the a new building, I've an exception :

Request Method: GET
Request URL: http://coati/coati/Batiment/1/Modifier/
Django Version: 1.4.2
Exception Type: ValueError
Exception Value:

invalid literal for int() with base 10: '9 RUE GABRIEL PERI'

Exception Location: /var/www/dae/virtualenv/lib/python2.6/site-packages/django/db/models/fields/init.py in get_prep_value, line 966
Python Executable: /usr/bin/python
...

a slice from the backtraces :

/var/www/dae/virtualenv/lib/python2.6/site-packages/autocomplete_light/widgets.py in render
if values and not autocomplete.validate_values():
/var/www/dae/virtualenv/lib/python2.6/site-packages/autocomplete_light/autocomplete/model.py in validate_values
return len(self.choices_for_values()) == len(self.values)
/var/www/dae/virtualenv/lib/python2.6/site-packages/autocomplete_light/autocomplete/model.py in choices_for_values
return self.order_choices(self.choices.filter(pk__in=self.values or [])

...

As I change primary_key from the id to the address field in the address model, autocomplete works perfectly.

I hope this post will help you, and excuse for my poor english...

Thanks for your great job !

How to register the same model with different autocomplete models?

when I register the same model with an AutoCompleteModelBase model i.e., only enables the last one.
In one app in autocomplete_light_register.py I have ("Ciudad" is the model, "AutocompleteCiudad" is my autocomplete model):
autocomplete_light.register(Ciudad,AutocompleteCiudad)
in another app:
autocomplete_light.register(Ciudad, add_another_url_name='localidades:ciudad_create',
search_fields=('nombre',),
autocomplete_js_attributes={'placeholder': u'Nombre de ciudad ..'},)

always loads the last one. How can I choose which widget to use in a especific form?
sorry for by awful english

Channel refactor with mixins

Usually, I want to hack either the frontend part, either the backend part of a channel, to implement a feature.

If I could compose channels with FrontendMixin (ie. TemplateFontendMixin) and a BackendMixin (ie. ModelBackendMixin, RemoteBackendMixin, ...) it would probably make it easier, since it would divide methods of a channel into backend or frontend part, and you could predict what methods will need override.

jQuery conflict with django grappelli

Hello,

I had a jQuery conflict between django-autocomplete and django-grappelli.

I solved it in next way:

I deleted "{% include 'autocomplete_light/static.html' %}" from admin/base_site.html and added Media class to AutocompleteWidget. It looks like:

class AutocompleteWidget(forms.SelectMultiple):

class Media:
    extend = True
    css = {
        'all': (
            'autocomplete_light/style.css',
            )
        }
    js = (
            'js/jquery-1.7.2.min.js',
            'autocomplete_light/autocomplete.js',
            'autocomplete_light/deck.js',
            'autocomplete_light/remote.js',                
        )

...

And it works perfect. I think, it is more convenient adding Media class instead of modification of admin/base_site.html.

Thank you for your app.

question - non admin

Hello,

I am wondering if django-autocomplete-light can be used on a non admin form,. I have a contact form that I would like to have one field autocomplete a CharField from a single Model

I have been though all of the examples, they are cool but I cannot workout how to get this working out of the admin site.

If anyone has any tips or examples that would be brill.

Cheers

Richard

How to add extra autocomplete field in ModelForm?

Could you please give an example on how to add extra field in ModelForm? I couldn't find this case in test_project.

models.py
class Location(models.Model):
    street = models.CharField(max_length=50, blank=True)
    city = models.ForeignKey('cities_light.City')
    longitude = models.FloatField(blank=True, null=True)
    latitude = models.FloatField(blank=True, null=True)

class Event(models.Model):
    slug = models.CharField(max_length=128, blank=True)
    begin_date = models.DateField(null=True)
    location = models.ForeignKey(Location, blank=True, null=True)
forms.py
class ScheduleForm(forms.ModelForm):
    street = forms.CharField(label=_('Street'), max_length=30, required=False)
    city = ModelChoiceField(label=_('City'), queryset=City.objects.all(),
                widget=autocomplete_light.ChoiceWidget('CityAutocomplete'))

    class Meta:
        model = Event

I'm able to select a city in autocomplete field. But I'm getting an error on form submit:

City: Select a valid choice. That choice is not one of the available choices.

What am I doing wrong?

Selected choice primary key(CharField) stripped from leading zeros resulting in error

If you use autocomplete for a model in the admin interface and the primary key is a CharField holding a number sequence with possible leading zeros - in my case IPTC codes - when you select a choice, the primary key saved in the form is stripped from any leading zeros causing the

I suppose the bug derives from a primary key to integer cast somewhere in the javascript, and probably in the validation code as well.

Autocomplete with Django dev version (1.6)

With project on Django 1.4.2 everything works fine, but when try to implement autocomplete in project on Django dev version a page with autocomplete widgets says every time "Autocomplete needs a url !"
Static files included in template . URL to autocomplete presents in root url, and also in specific app urls.
Also there is a problem in widget.js (// Add a class to ease css selection of autocompletes for widgets this.autocomplete.outerContainer.addClass - Uncaught TypeError)

Remove {% autocomplete_light_static %}

It doesn't handle dependencies so this can be a problem if for example cities_light/autocomplete_light.js is loaded before autocomplete_light/remote.js.

So either we could bloat that, either just remove that tag and let the user do his <script> tags by himself, which looks like the sanest idea.

Clean and document Javascript

The Javascript documentation should be complete now that it builds on rtfd.

Also, autocomplete.js needs a revamp, mainly variables and methods should be renamed to be more relevant.

Legacy code issue: if (!widget.length) return; (was: "Widget must have an id")

Hi,

I hit this bug when I had an admin with a top navigation autocomplete and an inline autocomplete. I also had django-admin-tools installed in my admin.

I added an item and it was OK. The message appeared when I tried to remove an item.

It looked like when I click the remove button, the message appears. I saw in the debugger that the function was called 2 times, on the 2nd time the id was undefined.

I fixed it in my branch, by uncommetingin line 266 of widget.js

I am unable to reproduce this with a minimal code example, as the inline demo I added to my branch does NOT show such behaviour.

If there is anything else you need from me to help us with debugging this issue, just let me know, please.

table.as_p instead of as_table

If you use {{ table.as_p }} in your template, the javascript error occurred and it doesn't work..

The error is TypeError: this.autocomplete is undefined.

inline_autocomplete demo: how to access dynamically added widgets?

Hi,

as you can see, I added the inline_autocomplete demo so I can add more issues for autocomplete inside inlines :-)

I am currently trying to write some code, that uses dependent autocomplete, only in inlines.

To reproduce the problem I am issuing here, first please run the demo and open inlines_autocomplete "add new":
http://localhost:8000/admin/inline_autocomplete/trip/add/

Then, in the browser: launch Firebug or anything you prefer, and then type in console:

>>> $('.autocomplete-light-widget.trip_city_set-0-city').yourlabsWidget()
Object { widget=[1], input=[1], select=[1], więcej...}

As you can see, this works. The widget is found.

Now, please add one more inline, by clicking "Add another Trip_City" link on the page.

Now, let's try to access newly created widget:

>>> $('.autocomplete-light-widget.trip_city_set-1-city').yourlabsWidget()
undefined

... but, when you check all the widgets:

>>> $('.autocomplete-light-widget')

You will see, that there is a with ID id_trip_city_set-1-city-wrapper.

After some time, I found, that:

>>> $('.autocomplete-light-widget.trip_city_set-__prefix__-city')

... will show TWO widgets named like this. One - invisible widget - was copied by django's inlines.js into a new one, which is visible.

Do you have any idea, why the widget retains the original ID (with "prefix" string not updated to an integer)?

Django after copying the invisible row, updates the "prefix" string inside id attributes in inlines.js, line 20 (updateElementIndex).

I suppose I should do something after the widget is copied, like, call a function that will make jQuery to update widget's internal values from id attributes - or something like that. Please help me with this and I will think of creating a sensible patch for that.

If widget's placeholder contains spaces, the message appears

Hi,

in the registry:

autocomplete_light.register(Autor, search_fields=('nazwisko',),
autocomplete_js_attributes={
'placeholder': 'nazwisko... i imię',
'url': '/autocomplete/AutorAutocomplete/'})

... if the placeholder contains SPACES, I get an alert about missing autocomplete URL.

UTF-8 characters not supported in widget's placeholder

autocomplete_light.register(Autor, search_fields=('nazwisko',),
    autocomplete_js_attributes={
        'placeholder': 'Ł',
        'url': '/autocomplete/AutorAutocomplete/'})

Such entry in registry file will cause "Autocomplete needs an URL" alert message box appear when the page is rendered.

Widgets don't work under Windows

Hello,

I tried django-autocomplete-light under Ubuntu and it works perfectly, as seen on Youtube. But when I do just the same steps under Windows, widgets in admin don't work. Why is it so?

ValueError: "invalid literal for int() with base 10" when submitting an empty form POST

Hi,
I've started using autocomplete-light today, for autocompletion of ForeignKey on my custom ModelForm.
however when submitting an empty POST request, mentioned in title ValueError is being thrown, pointing to the template ("widget.html") line:
{% for choice in autocomplete.choices_for_values %}

which leads to the following:
autocomplete/model.py in choices_for_values:

return self.order_choices(self.choices.filter(
pk__in=self.values or []))

I've debugged that line and believe the problem is that, when empty POST is submitted, self.values contains one value, an EMPTY UNICODE STRING (that is, self.values == [u''])

I don't know autocomplete_light internals well enough to find out why is that

updateWidgets puts heavy load on browser with many autocomplete fields

I have an inline form with 2 autocomplete fields per row. With anything more than 20 rows the lag from clicking the mouse or typing becomes noticeable. With more than 40 rows the form becomes difficult to use. The problem appears to be the updateWidgets function which runs every 2(?) seconds and is putting a heavy load on the browser.

Is there any way to mitigate this problem?

test_grappelli "Inline_Autocomplete" demo - extra inlines not working properly

This is pretty complicated to replicate - sorry for redirecting you to an extra site, but this will be way simpler for me to describe it there: http://pokazywarka.pl/3b0wnr/

It looks to me like it has something to do with django-grappelli copying HTML code and not changing "prefix" to a number properly. Perhaps this is django-grappelli bug, but as it occurs with django-autocomplete-light and it requires a bit complex environment to replicate (and we built this environment as a basis for django-autocomplete-light testing and pushing its limits even further :-), I'd like to keep this issue open somewhere around, just in case.

Specification

In documenatation specific that you have to put autodiscover before Form import.

I tell you because not always people (like me!! :P ) make a perfect modular application.. So if in urls.py
you import some form to pass into class based view, it search widget before discover it.. So if you have
MyForm with some widgets and these lines in urls

from app.forms import MyForm

import autocomplete_light
autocomplete_light.autodiscover()
....

it returns no error but no autocomplete textbox are created.

Add 'edit' link next to 'X'

Greetings,

What's the best way to add a link next to the "X" (remove object) that will take the user to the edit screen for a particular object? For example, I have a Person table, and a Volunteer table that has a FK relation to the Person table. In the Django admin I can autocomplete a Volunteer to someone out of Contacts. After I do that, however, I realize I need to correct the Volunteer's address (which, of course, is actually the Contact's address). It would be very handy to have a small pencil icon next to the 'X' that would take the user to the correct edit screen for the Contact.

Thanks.

--cro

Use HTML5's placeholders

Currently, autocomplete.js provides input placeholder feature in pure JS.

Modern browsers support HTML5's placeholder attribute.

Relying directly on the browser for that feature is a great opportunity to reduce our codebase. Also, it would improve performance and thus user experience.

Channel name conflict

I have a Django project containing two apps, Expenses and Sales which both have models named Item. I'm using django-autocomplete-light to ease the selection of Item. This works for either Expenses or Sales depending on which channel I register last but the other one wrongly shows the same Items.

I guess this is a configuration issue and not a bug. I have described the problem and what I'm trying on Stackoverflow:

http://stackoverflow.com/questions/10860524/autocomplete-light-channel-name-conflict

Autocomplete for comma-separated CharField?

I was wondering if it supports autocomplete on a comma separated special CharField? More precisely if it can be used with an app for tagging objects, like django-cms-pagetags (plugin for Django CMS) that uses django-tagging for backend and jQuery UI Autocomplete through a widget for entering a comma-separated list of tags for a specific page.

Validation error when autocompleting model with CharField as primary_key

In my models.py:

class Media(models.Model):
    code = models.CharField(_(u'Code'), max_length=128, null=False, \
        blank=False, primary_key=True)
    name = models.CharField(_('Name'), max_length=128, null=True, \
        blank=True)

class MediaFilter(models.Model):
    media = models.ForeignKey(Media, verbose_name=_("Media"))

In my autocomplete_light_registry.py:

autocomplete_light.register(Media, search_field='name')

In my admin.py:

class MediaFilterAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(MediaFilter)

When, in the admin app, I try to edit a MediaFilter model, I get this ValidationError:

[u"type cannot validate [u'D82F7E4B4E14B00372EDF68D1E49046D']"]

When I create a Media object with a code containing only numbers, it works like a charm. When the code contains letters, I get the aforementioned error. This error is new, the app was working with a previous version of django-autocomplete-light.

Placeholder bug

when selecting option and then deleting it - placeholder text becomes input's value

if (!this.input.is(":focus")) {
this.input.val(this.input.yourlabsAutocomplete().placeholder);
} else {
this.input.val('');
}

what is it for?
why don't just this.input.val(''); ?

Missing license on read the docs and in pypi package

Please include license file in pypi package and on read the docs site so that is is easy to refrence license type / model

Thanks

python -m easy_install django-autocomplete-light
Searching for django-autocomplete-light
Reading http://pypi.python.org/simple/django-autocomplete-light/
Reading http://django-autocomplete-light.rtfd.org
Reading https://github.com/yourlabs/django-autocomplete-light
Best match: django-autocomplete-light 1.0.14
Downloading http://pypi.python.org/packages/source/d/django-autocomplete-light/d
jango-autocomplete-light-1.0.14.tar.gz#md5=86a28f0e95cd76439fa6ea945aef6918
Processing django-autocomplete-light-1.0.14.tar.gz
Running django-autocomplete-light-1.0.14\setup.py -q bdist_egg --dist-dir c:\use
rs\user\appdata\local\temp\easy_install-loo9dl\django-autocomplete-light-1.0.
14\egg-dist-tmp-yqxqo1
processing file django.po in c:\users\user\appdata\local\temp\easy_install-lo
o9dl\django-autocomplete-light-1.0.14\autocomplete_light\locale\fr\LC_MESSAGES
'msgfmt' is not recognized as an internal or external command,
operable program or batch file.
processing file django.po in c:\users\user\appdata\local\temp\easy_install-lo
o9dl\django-autocomplete-light-1.0.14\autocomplete_light\locale\it\LC_MESSAGES
'msgfmt' is not recognized as an internal or external command,
operable program or batch file.
processing file django.po in c:\users\user\appdata\local\temp\easy_install-lo
o9dl\django-autocomplete-light-1.0.14\autocomplete_light\locale\pl\LC_MESSAGES
'msgfmt' is not recognized as an internal or external command,
operable program or batch file.
warning: no files found matching 'README'
warning: no files found matching 'LICENSE'
warning: no files found matching '*.mo' under directory 'autocomplete_light'
Adding django-autocomplete-light 1.0.14 to easy-install.pth file

Installed c:\python27\lib\site-packages\django_autocomplete_light-1.0.14-py2.7.e
gg
Processing dependencies for django-autocomplete-light
Finished processing dependencies for django-autocomplete-light

Documentation review

In 1.3.1 modelform_factory() does not take a widgets parameter:

modelform_factory() got an unexpected keyword argument 'widgets'

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.