Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Input widget for jQuery TagIt plugin #270

Open
GoogleCodeExporter opened this issue Mar 26, 2015 · 1 comment
Open

Input widget for jQuery TagIt plugin #270

GoogleCodeExporter opened this issue Mar 26, 2015 · 1 comment

Comments

@GoogleCodeExporter
Copy link

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 [email protected] on 8 Jan 2012 at 3:12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant