0
基於從https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/#models-and-request-user的例子 - 但有許多一對多的關係,而不是一個外鍵關係:類爲本次(CBV),CreateView的和request.user有許多一對多的關係
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)
將輸出
"<Author: test>" needs to have a value for field "id" before this many-to-many relationship can be used.
如何避免這種情況?