在我的项目中,我有来自标准auth
Django模型的User
模型和Todo
模型。用户可以有许多待办事项。在
当登录用户创建todo时,必须自动将其分配给todo。我想将当前用户传递给CreateView
的初始数据。在我看来,我走的路是对的。以下是表单对象的外观:
class TodoView(CreateView):
model = Todo
fields = ('name', 'date')
success_url = '/todos/'
def get_initial(self):
return {
'user': self.request.user
}
这是一个模型:
^{pr2}$但这似乎还不够,因为当有效数据来自客户端时,我有一个异常。例外情况是:
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的最佳实践中做到这一点?在
您需要使用^{} 方法而不是
get_initial
。像这样:我从未使用过
get_initial
,但我想它不会做任何事情,因为您没有包含user
字段。这无论如何都没有用,因为您不希望用户能够更改值。在相关问题 更多 >
编程相关推荐