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. 

如何避免這種情況?

回答

1

編輯你的觀點有點像這樣,從ModelFormMixinFormMixin

class AuthorCreate(CreateView): 
    model = Author 
    fields = ['name'] 

    def form_valid(self, form): 
     self.object = form.save() 
     self.object.owners.add(self.request.user) 
     self.object.save() 
     return HttpResponseRedirect(self.get_success_url()) 

CreateView繼承。調用super()只會導致保存模型並重定向到success_url。在ManyToManyField的情況下,對象在創建ManyToMany關係(即對象需要保存在數據庫中)之前需要有一個primary_key,因此,通過顯式調用父類中的方法覆蓋form_valid()方法可以解決您的問題。