Django Taggit - Tag associations are not saved from user admin form

Let's go nuts here ... From the inside of the shell I can do:

product.tags.add("a_new_tag") 

The tag is added to db, and the tag association with the product works correctly. (ie when I do Product.objects.filter(tags__name__in=["a_new_tag"] , the corresponding product spits out)

What I need to do is add tags to the admin when processing the form.

Here is my form code (read the comments on lines 4 and 5):

 class ProductForm(ModelForm): def save(self, commit=True): product = super(ProductForm, self).save(commit=False) product.type="New Type to Confirm Info is being Saved Correctly" //this is saved to the product. product.tags.add('a_new_tag_1') //the tag is saved to the taggit db, but the association with the product isn't kept. product.save() self.save_m2m() return m 

I tried to save in the admin class instead, but this does not work either:

 class ProductAdmin(admin.ModelAdmin): form = ProductForm def save_model(self, request, obj, form, change): obj.type="new_type" //this works obj.tags.add("a_new_tag_2") //tag association not saved obj.save() form.save_m2m() 

What am I doing wrong? Thanks in advance!

+4
source share
2 answers

So it turns out that form.save_m2m() was the culprit. If I extracted it from my own code and commented on it in the django.contrib.admin.options.py file (line 983), the associations were saved, as well as the tag.

Obviously, it is not recommended to change the django code, so I ended up redefining change_view() in my ProductAdmin (as well as add_view() ). I added tags after calling super() , so form.save_m2m() will not overwrite tag associations.

This is strange because it goes directly against the django-taggit documentation, which emphasizes how important it is to name form.save_m2m() : http://django-taggit.readthedocs.org/en/latest/forms.html

Well, I don’t know what will happen, I will probably go to google taggit groups and notify them. In any case, thanks to David for your help, if nothing else, pdb is AMAZING, and I did not know about this before :)

+1
source

What tag system are you using? Perhaps you need to use product.tags.save() ?

0
source

All Articles