[英]How to modify the author choices field in my generic CreateView with authors(fk) only from the current user?
This is my code, i have read the documentations and it seems this method is the right way, i get no errors but i see no results. 这是我的代码,我已经阅读了文档,看来此方法是正确的方法,我没有收到任何错误,但没有看到任何结果。 Can somebody help me in what i am doing wrong? 有人可以帮我解决我做错的事情吗?
class BookCreate(LoginRequiredMixin, CreateView):
model = Book
fields = ['title', 'isbn', 'year', 'author', 'publisher']
def form_valid(self, form):
form.instance.owner = self.request.user
return super(BookCreate, self).form_valid(form)
def form_valid(self, form):
b = Book.objects.all
form.instance.author = ModelChoiceField(queryset=b.author_set.filter(owner=self.request.user))
return super(BookCreate, self).form_valid(form)
It is much easier to simply exclude the author
from the list of fields, then set it in the form_valid
method: 只需将author
从字段列表中排除,然后在form_valid
方法中进行设置,就form_valid
:
class BookCreate(LoginRequiredMixin, CreateView):
model = Book
fields = ['title', 'isbn', 'year', 'publisher']
def form_valid(self, form):
form.instance.owner = self.request.user
return super(BookCreate, self).form_valid(form)
If you do this, make sure you delete your second form_valid
method, which is replacing the correct form_valid
method above. 如果这样做,请确保删除第二个form_valid
方法,该方法将替换上面的正确form_valid
方法。
If you must include author
as a field with a single option, then the code is much more complicated. 如果必须使用单个选项将author
作为字段包括在内,则代码要复杂得多。 You need a custom form with an __init__
method which takes user
and sets the queryset for the auth
field. 您需要一个带有__init__
方法的自定义表单,该方法接受user
并设置auth
字段的queryset。
Then you need to modify your view to use your custom form, and override get_form_kwargs
to include self.request.user
. 然后,您需要修改视图以使用自定义表单,并覆盖get_form_kwargs
以包括self.request.user
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.