Class Based Views (CBV), CreateView and request.user with a many-to-many relation

牧云@^-^@ 提交于 2019-12-13 07:26:05

问题


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:


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.



来源:https://stackoverflow.com/questions/46378465/class-based-views-cbv-createview-and-request-user-with-a-many-to-many-relatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!