dlamotte / django-tagging

Automatically exported from code.google.com/p/django-tagging
Other
0 stars 0 forks source link

Input widget for jQuery TagIt plugin #270

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
Hi,

I integrated django-tagging with the TagIt jQuery plugin 
(http://webspirited.com/tagit/?page=tagit), and want to share the small 
enhancement. 

The TagIt plugin uses a ul/il construct to mark the individual tags and adds 
its own <input> tag.

=================================
from django.forms import Widget
class TagInput(Widget):
    """
    Widget that renders a tag input field for the TagIt jQuery plugin
    http://webspirited.com/tagit/?page=tagit

    I.e., it renders ul/il, but no <input>, which is added in JS by
    the plugin.
    """
    def __init__(self, attrs=None):
        if attrs is not None:
            self.attrs = attrs.copy()
        else:
            self.attrs = {}

    def value_from_datadict(self, data, files, name):
        """
        Given a dictionary of data and this widget's name, returns the
        value of this widget. The value is a comma-separated list of
        tags, which is interpreted by the TagField. 
        """
        return ", ".join(data.getlist(name))

    def render(self, name, value, attrs=None):
        if value is None:
            value = ''

        if "name" in self.attrs:
            name_attr = " name=%s"%self.attrs["name"]
        else:
            name_attr = ""

        return mark_safe(u'<ul class="tags"%s>%s</ul>' % \
                             (name_attr,
                              "".join(["<li>%s</li>"%tag for tag in value.split(" ")])))

==============================

Now you simply add a form to your Form class like so:

my_field = forms.CharField(widget=TagInput({"name":"my_field"}))

And inside your html template you simply use it as usual:

{{ form.my_field }}

Please note that you have to set select=true in the TagIt JS method invocation:
$('.tags').tagit({select:true}); 

Original issue reported on code.google.com by willi.ri...@gmail.com on 8 Jan 2012 at 3:12

GoogleCodeExporter commented 8 years ago
I'm not sure what the demo does.  Where is the tags list populated from the 
database?

Original comment by inactiv...@gmail.com on 30 May 2012 at 7:44