将当前用户传递给Django中的CreateView初始化 [英] Pass current user to initial for CreateView in Django
问题描述
在我的项目中,我有用户
模型从标准 auth
Django模型和 Todo
模型。用户可以拥有许多Todo。
In my project I have User
model from standard auth
Django model and the Todo
model. User can have many Todo.
当用户创建一个todo时,他必须自动分配给todo。我想将当前用户传递给 CreateView
的初始数据。在我看来,我是正确的。这是表单对象的外观:
When signed in user creates a todo he must be assigned to the todo automatically. I want to pass current user to initial data of the CreateView
. It seems to me that I'm on right way. This is how the form object looks:
class TodoView(CreateView):
model = Todo
fields = ('name', 'date')
success_url = '/todos/'
def get_initial(self):
return {
'user': self.request.user
}
这是一个模型: p>
And this is a model:
class Todo(models.Model):
user = models.ForeignKey(User)
name = models.TextField()
date = models.DateField()
但似乎这还不够因为当有效数据从客户端发送时,我有异常。这是例外:
But it seems that that's not enough because I have an exception when the valid data goes from the client side. This is the exception:
IntegrityError at /todos/new
todos_todo.user_id may not be NULL
Request Method: POST
Request URL: http://localhost:8000/todos/new
Django Version: 1.6.2
Exception Type: IntegrityError
Exception Value:
todos_todo.user_id may not be NULL
Exception Location: /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 450
Python Executable: /usr/bin/python
Python Version: 2.7.5
是否可以将当前用户传递给 CreateView
的模型?如何在Django的最佳实践中做到这一点?
Is that possible at all to pass the current user to the model of the CreateView
? How to do it in best practice in the Django?
推荐答案
您需要使用 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.
这篇关于将当前用户传递给Django中的CreateView初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!