django - django-taggit form
Asked Answered
N

3

9

I would like to use django-taggit (click here ). The documentation ( click here) talks about using ModelForm to generate the form but I have already my form that I would like to use.

Let's say if I have something like this:

forms.py

class MyForm(forms.Form):
    ......
    tags = forms.CharField(max_length=200, widget=forms.Textarea)

how do I save the the tags coming from the tags field? What goes in my views.py? A real example would be truly appreciated.

Naxos answered 19/3, 2011 at 2:48 Comment(0)
S
13

I'm not too familiar with the django taggit app, but it looks like if you want to use the same field and widget setup the app uses, you can import them from the taggit.forms (https://github.com/alex/django-taggit/blob/master/taggit/forms.py):

your models.py:

from django.db import models

from taggit.managers import TaggableManager

class Food(models.Model):
    name = models.CharField(max_length=20)

    tags = TaggableManager()

your forms.py

from taggit.forms import *

class MyForm(forms.Form):
    name = forms.CharField()
    m_tags = TagField()

The TagField will return the processed input using the parse_tags method from utils.py in the taggit app. The return looks to be a cleaned up list(set(words))

your views.py

if form.is_valid():
    name = form.cleaned_data['name']
    m_tags = form.cleaned_data['m_tags']
    object = Food(name=name)
    object.save()
    for m_tag in m_tags:
        object.tags.add(m_tag)
    return HttpResponseRedirect('/thanks/')
Seifert answered 19/3, 2011 at 10:23 Comment(1)
this of course doesn't remove tags, if you've marked them for deletion.Benzel
B
7

I can't comment on the used/"green ticked" answer. But I would change the Block

for m_tag in m_tags:
    object.tags.add(m_tag)

to

object.tags.add(*m_tags)
Brainwork answered 23/12, 2011 at 1:34 Comment(0)
I
4

See instructions here: https://github.com/alex/django-taggit/blob/master/docs/forms.txt

If, when saving a form, you use the commit=False option you'll need to call save_m2m() on the form after you save the object, just as you would for a form with normal many to many fields on it::

if request.method == "POST":
    form = MyFormClass(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = request.user
        obj.save()
        # Without this next line the tags won't be saved.
        form.save_m2m()
Iota answered 7/4, 2012 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.