基于类的视图(CBV),CreateView和具有多对多关系的request.user

时间:2017-09-23 10:14:40

标签: django django-forms django-views django-class-based-views

基于https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/#models-and-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 个答案:

答案 0 :(得分:1)

编辑您的视图,有点像这样,

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继承自ModelFormMixinFormMixin。调用super()只会导致保存模型并重定向到success_url。对于ManyToManyField,在创建primary_key关系之前,对象需要有ManyToMany(即,对象需要保存在数据库中),因此,覆盖{{1}通过显式调用两个父类中的方法可以解决您的问题。