Reputation: 1555
I'm trying to save a M2M object ( set it to a default value which is the one with id = 1 ).
The problem I'm getting the following error:
"<User: user556>" needs to have a value for field "id" before this many-to-many relationship can be used.
I looked at previous feeds that covered the same error but no one explained when it happens in the form_valid function as it happened to me
My code is as follows :
def form_valid(self,form):
instance = form.instance
instance.groups.set(1)
instance.save()
return super(UserCreateView,self).form_valid(form)
Upvotes: 2
Views: 489
Reputation: 477065
You first need to save your instance, such that it has a primary key, otherwise you can not create a record in the junction table.
You thus implement this with:
from django.http import HttpResponseRedirect
def form_valid(self,form):
instance = form.save()
instance.groups.set(1)
return HttpResponseRedirect(self.get_success_url())
returning a HttpResponseRedirect
is necessary here since a super().form_valid()
will save the form again to the database, and will also set the groups
to the ones specified in the form.
Upvotes: 2