Based on the examples from https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/#models-and-request-user - but with a many-to-many relation instead of a foreign key relation:
models.py
from django.contrib.auth.models import User
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=200)
owners = models.ManyToManyField(User, related_name='owners_')
views.py
from django.views.generic.edit import CreateView
from myapp.models import Author
class AuthorCreate(CreateView):
model = Author
fields = ['name']
def form_valid(self, form):
form.instance.owners = self.request.user
return super(AuthorCreate, self).form_valid(form)
Will output
"<Author: test>" needs to have a value for field "id" before this many-to-many relationship can be used.
How to avoid this?
Edit your view somewhat like this,
CreateView
inherits fromModelFormMixin
andFormMixin
. Callingsuper()
would only result in saving the model and redirect to thesuccess_url
. In the case of aManyToManyField
, an object need to have aprimary_key
before creating aManyToMany
relationship(ie, object needs to be saved in database), so, overridingform_valid()
method by explicitly calling the methods from both parent classes can resolve your issue.