In other words, why does this work:
if choice==Item.DO_ADD_CAT:
for item in selected_items:
for c in categories:
item.categories.add(Category.objects.get(pk=c))
item.save()
messages.success(request,'Categories have been added.')
and this not:
if choice==Item.DO_REM_CAT:
for item in selected_items:
for c in categories:
item.categories.remove(Category.objects.get(pk=c))
item.save()
messages.success(request,'Categories have been removed.')
Isn’t this supposed to be working?
edit:
here is the Item model:
class Item(models.Model):
#public/private state flags
PRIVATE_STATUS=1
PUBLIC_STATUS=2
RELEASED_STATUS=3
STATUS_CHOICES=((PRIVATE_STATUS ,'private'),
(PUBLIC_STATUS ,'public' ),
(RELEASED_STATUS,'released'))
status = models.IntegerField(choices=STATUS_CHOICES,
default=PRIVATE_STATUS,
)
objects = models.Manager()
name=models.CharField(max_length=50)
tags=TagField()
count=models.IntegerField(blank=True)
def get_user_path(self,filename):
return '%s/%s/%s' %( self.creator_id,
datetime.date.today(),
filename)
file=models.FileField(upload_to=get_user_path)
creator = models.ForeignKey(User, related_name='creator')
categories = models.ManyToManyField(Category,related_name="items",blank=True,null=True)
and the Category Model:
class Category (models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField()
description = models.TextField(blank=True,help_text='Optional')
def __unicode__(self):
return self.name
class Meta:
verbose_name='Category'
verbose_name_plural='Categories'
I guess i see the error… As in the django documentation tell us, you can not use remove on an foreignkey with a null=False definition… Related documentation
So prior to the logic of M2M relations, django set your m2m relation as null=False… So possibilities are: