且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将当前用户传递给Django中的CreateView初始化

更新时间:2023-12-04 10:01:04

您需要使用 form_valid 方法,而不是 get_initial 。这样的东西:

You need to use the form_valid method instead of get_initial. Something like this:

def form_valid(self, form):
    form.instance.user = self.request.user
    return super(TodoView, self).form_valid(form)

get_initial ,但是我猜这不会做任何事情,因为你不包括用户字段。这不会有用,因为您不希望用户能够更改该值。

I have never used get_initial, but I guess it doesn't do anything because you don't include the user field. That wouldn't be useful anyway, because you don't want the user to be able to change the value.