Class Based Views (CBV), CreateView and request.us

2019-08-22 03:07发布

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?

1条回答
Evening l夕情丶
2楼-- · 2019-08-22 03:43

Edit your view somewhat like this,

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 inherits from ModelFormMixin and FormMixin. Calling super() would only result in saving the model and redirect to the success_url. In the case of a ManyToManyField, an object need to have a primary_key before creating a ManyToMany relationship(ie, object needs to be saved in database), so, overriding form_valid() method by explicitly calling the methods from both parent classes can resolve your issue.

查看更多
登录 后发表回答