我正在使用Django 1.9并继续学习本教程: https://www.youtube.com/watch?v=6WkQOlYgkHM&index=15&list=PLEsfXFp6DpzQFqfCur9CJ4QnKQTVXUsRy
当我按照建议输入以下代码时:
def post_list(request):
# return HttpResponse("<h1>Update</h1>")
if request.user.is_authenticated():
context = {
"title": "My User List"
}
else:
context = {
"title": "List"
}
return render(request, "index.html", context)
我收到以下错误消息:
AttributeError: 'WSGIRequest' object has no attribute 'user'
我查阅了文档并试着这样做:
from django.contrib.auth.models import user
但我的pycharm上有user
加下划线,现在我收到的错误信息是
ImportError: cannot import name 'user'
答案 0 :(得分:1)
您可能忘记在MIDDLEWARE
设置中添加一些必需的中间件项。
正如文档for User authentication in Django中所述,您必须将SessionMiddleware
和AuthenticationMiddleware
添加到MIDDLEWARE
文件中的settings.py
设置中。
这将确保在您的请求对象上设置user
属性。
请注意,以上情况适用于Django的当前状态(1.10及更高版本),不再支持Django 1.9且不应使用。
如果您仍想使用它,instructions for using django.contrib.auth
with django 1.9 can be found here