2011-05-11 57 views
4

在这里要疯了...... 从外壳内标签关联,我可以这样做:Django的Taggit - 不从自定义管理表单保存

product.tags.add("a_new_tag") 

标签被添加到数据库,并标记关联产品工作正常。 (即当我做Product.objects.filter(tags__name__in=["a_new_tag"]适当的产品吐出)

我需要做的是在处理表单时在admin中添加一些标签。

这里是我的表单代码(读入行4和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 

我试着做在管理类,而不是储蓄,但是这并不能正常工作或:

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() 

我在做什么错?提前致谢!

回答

1

所以事实证明,form.save_m2m()是罪魁祸首。如果我把它从我自己的代码中取出,并在django.contrib.admin.options.py(第983行)中注释掉它,那么关联和标签都会被保存。

很明显,改变django的代码并不是一个好主意,所以我最终在我的ProductAdmin(以及add_view())中覆盖了change_view()。我在致电super()后添加了标签,因此form.save_m2m()不会覆盖我的标签关联。

这很奇怪,因为它会直接对Django的taggit的文件,强调它是多么的重要调用form.save_m2m()http://django-taggit.readthedocs.org/en/latest/forms.html

嗯,我不知道这是怎么回事,我可能会去的taggit谷歌组,并通知“ EM。在任何情况下,感谢大卫的帮助,如果没有更少的pdb是真棒,我以前不知道它:)

0

您正在使用哪种标记系统?可能你需要使用product.tags.save()

+0

他使用django-taggit – 2011-05-11 19:14:32

+0

嘿大卫,我使用的是django-taggit:https:// github .com/alex/django-taggit ... unforutnately TaggableManager没有save()方法,所以不能... – ruedaminute 2011-05-11 19:16:21

+0

Hrm,好的。在那种情况下,你确定它插入了吗?例如,“类型”是否按照您期望的方式更新?或者,如果您在添加标签后使用'pdb'中断,保存之前,标签是否出现在列表中?它在保存后出现吗? – 2011-05-11 19:26:15