ajax_select package

Submodules

ajax_select.admin module

ajax_select.apps module

class ajax_select.apps.AjaxSelectConfig(app_name, app_module)

Bases: django.apps.config.AppConfig

Django 1.7+ enables initializing installed applications and autodiscovering modules

On startup, search for and import any modules called lookups.py in all installed apps. Your LookupClass subclass may register itself.

name = 'ajax_select'
ready()
verbose_name = 'Ajax Selects'

ajax_select.fields module

ajax_select.helpers module

ajax_select.helpers.make_ajax_field(related_model, fieldname_on_model, channel, show_help_text=False, **kwargs)

Makes an AutoComplete field for use in a Form.

Parameters:
  • related_model (Model) – model of the related object
  • fieldname_on_model (str) – field name on the model being edited
  • channel (str) – channel name of a registered LookupChannel
  • show_help_text (bool) – show or supress help text below the widget Django admin will show help text below the widget, but not for ManyToMany inside of admin inlines This setting will show the help text inside the widget itself.
  • kwargs

    optional args

    • help_text: default is the model db field’s help_text.
      None will disable all help text
    • label: default is the model db field’s verbose name
    • required: default is the model db field’s (not) blank
Returns:

field

Return type:

(AutoCompleteField, AutoCompleteSelectField, AutoCompleteSelectMultipleField)

ajax_select.helpers.make_ajax_form(model, fieldlist, superclass=<class 'django.forms.models.ModelForm'>, show_help_text=False, **kwargs)

Creates a ModelForm subclass with AutoComplete fields.

Parameters:
  • model (type) – Model class for which you are making the ModelForm
  • fieldlist (dict) – {field_name -> channel_name, ...}
  • superclass (type) – optional ModelForm superclass
  • show_help_text (bool) – suppress or show the widget help text
Returns:

a ModelForm suitable for use in an Admin

Return type:

ModelForm

Usage:

from django.contrib import admin
from ajax_select import make_ajax_form
from yourapp.models import YourModel

@admin.register(YourModel)
class YourModelAdmin(Admin):

    form = make_ajax_form(YourModel, {
        'contacts': 'contact',  # ManyToManyField
        'author':'contact'      # ForeignKeyField
    })

Where ‘contacts’ is a ManyToManyField specifying to use the lookup channel ‘contact’ and ‘author’ is a ForeignKeyField specifying here to also use the same lookup channel ‘contact’

ajax_select.lookup_channel module

class ajax_select.lookup_channel.LookupChannel

Bases: object

Subclass this, setting the model and implementing methods to taste.

model

Model

The Django Model that this lookup channel will search for.

plugin_options

dict

Options passed to jQuery UI plugin that are specific to this channel.

min_length

int

Minimum number of characters user types before a search is initiated.

This is passed to the jQuery plugin_options. It is used in jQuery’s UI when filtering results from its own cache.

It is also used in the django view to prevent expensive database queries. Large datasets can choke if they search too often with small queries. Better to demand at least 2 or 3 characters.

can_add(user, other_model)

Check if the user has permission to add a ForeignKey or M2M model.

This enables the green popup + on the widget. Default implentation is the standard django permission check.

Parameters:
  • user (User) –
  • other_model (Model) – the ForeignKey or M2M model to check if the User can add.
Returns:

bool

check_auth(request)

By default only request.user.is_staff have access.

This ensures that nobody can get your data by simply knowing the lookup URL.

This is called from the ajax_lookup view.

Public facing forms (outside of the Admin) should implement this to allow non-staff to use this LookupChannel.

Parameters:request (Request) –
Raises:PermissionDenied
format_item_display(obj)

(HTML) format item for displaying item in the selected deck area.

Parameters:obj (Model) –
Returns:formatted string, may contain HTML.
Return type:str
format_match(obj)

(HTML) Format item for displaying in the dropdown.

Parameters:obj (Model) –
Returns:formatted string, may contain HTML.
Return type:str
get_objects(ids)

This is used to retrieve the currently selected objects for either ManyToMany or ForeignKey.

Note that the order of the ids supplied for ManyToMany fields is dependent on how the objects manager fetches it. ie. what is returned by YourModel.{fieldname}_set.all()

In most situations (especially postgres) this order is indeterminate – not the order that you originally added them in the interface. See Ordered ManyToMany fields for a solution to this.

Parameters:ids (list) – list of primary keys
Returns:list of Model objects
Return type:list
get_query(q, request)

Return a QuerySet searching for the query string q.

Note that you may return any iterable so you can return a list or even use yield and turn this method into a generator.

Parameters:
  • q (str, unicode) – The query string to search for.
  • request (Request) – This can be used to customize the search by User or to use additional GET variables.
Returns:

iterable of related_models

Return type:

(QuerySet, list, generator)

get_result(obj)

The text result of autocompleting the entered query.

For a partial string that the user typed in, each matched result is here converted to the fully completed text.

This is currently displayed only for a moment in the text field after the user has selected the item. Then the item is displayed in the item_display deck and the text field is cleared.

Parameters:obj (Model) –
Returns:The object as string
Return type:str
min_length = 1
model = None
plugin_options = {}

ajax_select.models module

Blank file so that Django recognizes the app.

This is only required for Django < 1.7

ajax_select.registry module

class ajax_select.registry.LookupChannelRegistry

Bases: object

Registry for LookupChannels activated for your django project.

This includes any installed apps that contain lookup.py modules (django 1.7+) and any lookups that are explicitly declared in settings.AJAX_LOOKUP_CHANNELS

get(channel)

Find the LookupChannel class for the named channel and instantiate it.

Parameters:

channel (string) –

  • name that the lookup channel was registered at

Returns:

LookupChannel

Raises:
  • ImproperlyConfigured - if channel is not found.
  • Exception - invalid lookup_spec was stored in registery
is_registered(channel)
load_channels()

Called when loading the application. Cannot be called a second time, (eg. for testing) as Django will not re-import and re-register anything.

make_channel(app_model, arg_search_field)

Automatically make a LookupChannel.

Parameters:
  • app_model (str) – app_name.ModelName
  • arg_search_field (str) – the field to search against and to display in search results
Returns:

LookupChannel

register(lookup_specs)

Register a set of lookup definitions.

Parameters:lookup_specs (dict) – One or more LookupChannel specifications - {‘channel’: LookupChannelSubclass} - {‘channel’: (‘module.of.lookups’, ‘MyLookupClass’)} - {‘channel’: {‘model’: ‘MyModelToBeLookedUp’, ‘search_field’: ‘field_to_search’}}
ajax_select.registry.can_autodiscover()
ajax_select.registry.get_model(app_label, model_name)

Loads the model given an ‘app_label’ ‘ModelName’

ajax_select.registry.register(channel)

Decorator to register a LookupClass.

Example::

from ajax_select import LookupChannel, register

@register(‘agent’) class AgentLookup(LookupClass):

def get_query(self):
...
def format_item(self):
...

ajax_select.urls module

ajax_select.views module

ajax_select.views.ajax_lookup(request, channel)

Load the named lookup channel and lookup matching models.

GET or POST should contain ‘term’

Returns:[{pk: value: match: repr:}, ...]
Return type:HttpResponse - JSON
Raises:PermissionDenied - depending on the LookupChannel’s implementation of check_auth

Module contents

JQuery-Ajax Autocomplete fields for Django Forms.