Forms

Forms can be used either for an Admin or in normal Django views.

Subclass ModelForm as usual and define fields:

from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField

class DocumentForm(ModelForm):

    class Meta:
        model = Document

    category = AutoCompleteSelectField('categories', required=False, help_text=None)
    tags = AutoCompleteSelectMultipleField('tags', required=False, help_text=None)

make_ajax_field

There is also a helper method available here.

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)

Example:

from ajax_select import make_ajax_field

class DocumentForm(ModelForm):

    class Meta:
        model = Document

    category  = make_ajax_field(Category, 'categories', 'category', help_text=None)
    tags  = make_ajax_field(Tag, 'tags', 'tags', help_text=None)

FormSet

There is possibly a better way to do this, but here is an initial example:

forms.py:

from django.forms.models import modelformset_factory
from django.forms.models import BaseModelFormSet
from ajax_select.fields import AutoCompleteSelectMultipleField, AutoCompleteSelectField

from models import Task

# create a superclass
class BaseTaskFormSet(BaseModelFormSet):

    # that adds the field in, overwriting the previous default field
    def add_fields(self, form, index):
        super(BaseTaskFormSet, self).add_fields(form, index)
        form.fields["project"] = AutoCompleteSelectField('project', required=False)

# pass in the base formset class to the factory
TaskFormSet = modelformset_factory(Task, fields=('name', 'project', 'area'), extra=0, formset=BaseTaskFormSet)