CharField autocompletes

django-tagging and derivates like django-tagging-ng provide a TagField, which is a CharField expecting comma separated tags. Behind the scenes, this field is parsed and Tag model instances are created and/or linked.

A stripped variant of widget.js, text_widget.js, enables autocompletion for such a field. To make it even easier, a stripped variant of Widget, TextWidget, automates configuration of text_widget.js.

Needless to say, TextWidget and text_widget.js have a structure that is consistent with Widget and widget.js.

It doesn’t have many features for now, but feel free to participate to the project on GitHub.

As usual, a working example lives in test_project. in app charfield_autocomplete.

Warning

Note that this feature was added in version 1.0.16, if you have overloaded autocomplete_light/static.html from a previous version then you should make it load autocomplete_light/text_widget.js to get this new feature.

Example

This demonstrates a working usage of TextWidget:

import autocomplete_light
from django import forms
from models import Taggable


class TaggableForm(forms.ModelForm):
    class Meta:
        model = Taggable
        widgets = {
            'tags': autocomplete_light.TextWidget('TagAutocomplete'),
        }

FTR, using the form in the admin is still as easy:

from django.contrib import admin
from forms import TaggableForm
from models import Taggable


class TaggableInline(admin.TabularInline):
    form = TaggableForm
    model = Taggable


class TaggableAdmin(admin.ModelAdmin):
    form = TaggableForm
    list_display = ['name', 'tags']
    inlines = [TaggableInline]

admin.site.register(Taggable, TaggableAdmin)

So is registering an Autocomplete for Tag:

import autocomplete_light
from tagging.models import Tag

autocomplete_light.register(Tag)

Django-tagging

This demonstrates the models setup used for the above example, using django-taggit, which provides a normal CharField behaviour:

import tagging
from django.db import models
from tagging.fields import TagField


class Taggable(models.Model):
    name = models.CharField(max_length=50)
    tags = TagField(null=True, blank=True)
    parent = models.ForeignKey('self', null=True, blank=True)

    def __unicode__(self):
        return self.name

tagging.register(Taggable, tag_descriptor_attr='etags')