无法在Django 1.9中导入用户

时间:2017-12-28 16:51:31

标签: django

我正在使用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'

1 个答案:

答案 0 :(得分:1)

您可能忘记在MIDDLEWARE设置中添加一些必需的中间件项。

正如文档for User authentication in Django中所述,您必须将SessionMiddlewareAuthenticationMiddleware添加到MIDDLEWARE文件中的settings.py设置中。 这将确保在您的请求对象上设置user属性。

请注意,以上情况适用于Django的当前状态(1.10及更高版本),不再支持Django 1.9且不应使用。

如果您仍想使用它,instructions for using django.contrib.auth with django 1.9 can be found here