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!
A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.
To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.
A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.
The through attribute/field is the way you customize the intermediary table, the one that Django creates itself, that one is what the through field is changing.
Your Declaration of
form.save_m2m()
should be after
obj.save()
After saving of object Many to Many field will add
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With