Django 1.11 context must be a dict rather than RequestContext
我正在用Django 1.11编写一个登录页面。 这就是我收到的:
context must be a dict rather than
RequestContext .
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from django.contrib import auth from django.template import RequestContext from django.shortcuts import render_to_response from django.http import HttpResponse def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return HttpResponseRedirect('/index/') else: return render_to_response('login.html', RequestContext(request, locals())) |
这是我的模板:
1 2 3 4 5 6 7 8 9 10 | <!doctype html> <body> <form action="" method="post"> <label for="username">用戶名稱:</label>{% csrf_token %} <input type="text" name="username" value="{{username}}" id="username"><br /> <label for="password">用戶密碼:</label> <input type="password" name="password" value="" id="password"><br /> <input type="submit" value="登入" /> </form> </body> |
不要使用
1 | return render(request, 'login.html', locals()) |
请注意,Django带有登录视图,您不必自己编写。 不建议使用
Django 1.11禁止非字典上下文。
For compatibility with multiple template engines,
django.template.backends.django.Template.render() must receive a dictionary of context rather than Context or RequestContext. If you were passing either of the two classes, pass a dictionary instead – doing so is backwards-compatible with older versions of Django.
因此,您的代码应如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return HttpResponseRedirect('/index/') else: return render(request, 'login.html', locals()) |
我还应该补充一点,我不喜欢使用