20👍
As seen on:
http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany
Unlike normal many-to-many fields, you can’t use add, create, or assignment (i.e., beatles.members = […]) to create relationships
I guess your code trips up on the line “form.save_m2m()”, which is unnecessary since you already manually create a membership.
37👍
If you are allowed to modify class Membership
, adding auto_created = True
might solve your problem,
class Membership(models.Model):
class Meta:
auto_created = True
In Django 1.7, the error message is changed to “Cannot set values on a ManyToManyField which specifies an intermediary model”. The solution is the same.
NOTE: This will remove your intermediate model entirely, and all the additional fields with it.
- [Django]-Is this the right way to do dependency injection in Django?
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-Cannot set Django to work with smtp.gmail.com
4👍
I had a similar error message on a different problem. I post it here just in case it helps others.
I’ve added a new ManyToManyField
on an existing model. This model was used in a ModelForm
built with an exclude
field.
I fixed the problem by add the new field in the excluded ones.
- [Django]-Problems extend change_form.html in django admin
- [Django]-Uninstall Django completely
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
3👍
As of the Django 2.2 release you can also specify a through_defaults
on the field in order to use add, create and assignment:
The
RelatedManager.add()
,create()
,remove()
,set()
,get_or_create()
,
andupdate_or_create()
methods are now allowed on many-to-many
relationships with intermediate models. The newthrough_defaults
argument is used to specify values for new intermediate model
instance(s).
In your case since all the fields already have defaults it might just work in 2.2.
- [Django]-Using django-rest-interface
- [Django]-Django: show the count of related objects in admin list_display
- [Django]-Django substr / substring in templates
0👍
As specified in https://docs.djangoproject.com/en/2.1/topics/db/models/
"Unlike normal many-to-many fields, you can’t use add(), create(), or set() to create relationships"
This means for django version 2.1 ,these methods are impossible. But the same page of django 2.2 documentation https://docs.djangoproject.com/en/2.2/topics/db/models/ tells that:
"You can also use add(), create(), or set() to create relationships, as long as you specify through_defaults for any required fields"
So just update the django to 2.2 or newer versions to use the above methods and while creating objects give the argument ‘through_defaults’ as a python dictionary with keys as your extra field names and values as their default values.
- [Django]-How do I use an UpdateView to update a Django Model?
- [Django]-Filtering using viewsets in django rest framework
- [Django]-Django REST framework post array of objects