8

I have the following code in my models.py:

class Tag(models.Model):
    name = models.CharField(max_length=75)

class Article(models.Model):
    tags = models.ManyToManyField(Tag)

    def save(self, *args, **kwargs):
        for tag in self.tags:
            print tag.name
        super(Article, self).save(*args, **kwargs)

When I try to create an article from the admin panel, I get the following error:

ValueError: "<Article>" needs to have a value for field "id" before this many-to-many relationship can be used.

How can I fix this problem? I need to access and iterate the tags before saving the article. Thanks!

darkhorse
  • 8,192
  • 21
  • 72
  • 148
  • 1
    I believe the issue is that the tags are only created post save in m2m, so your save method override wouldn't work in the default admin behaviour – Mojimi May 02 '17 at 20:38

2 Answers2

3

Your Declaration of

form.save_m2m()

should be after

obj.save()

After saving of object Many to Many field will add

Aditya R
  • 39
  • 7
1

Your models are bellow:

class Tag(models.Model):
    name = models.CharField(max_length=75)

class Article(models.Model):
    tags = models.ManyToManyField(Tag)

    def save(self, *args, **kwargs):
        for tag in self.tags:
            print tag.name
        super(Article, self).save(*args, **kwargs)

when you want to create a Article instance with tags, you should create the instance firstly, then add the tags, like bellow:

article = Article.objects.create()

tags = [tag_instance1, tag_instance2, tag_instance3 ...]

article.tags.set(tags)

or

article.tags.add(tag_instance)
aircraft
  • 25,146
  • 28
  • 91
  • 166