0

当我尝试登录时,它显示:

KeyError at /admin/

'loggedin'

只有当我使用正确的用户名和密码提交时,它才会显示此错误。所以我认为这是关于我的管理员视图..

这是我的登录视图:

def log_user_in(request):
    if request.method=='POST':
        uname = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=uname, password=password)
        form = LoginForm(request.POST)
        if form.is_valid():
            if user is not None:
                request.session['loggedin']="djangoo"
                login(request, user)
                return HttpResponseRedirect('/admin/')
    else:
        form = LoginForm()

    return render_to_response('login.html',{'form':form,},context_instance=RequestContext(request))

并注销视图:

def log_user_out(request):
    user = request.user
    try:
        del request.session['loggedin']
    except KeyError:
        pass
    logout(request)
    return HttpResponseRedirect('/blog/%s/'%(user))

和管理员视图:

def admin_view(request):

    if request.session['loggedin'] == "djangoo":
    #other codes..

这是我的 urls.py:

urlpatterns = patterns('blog.views',
    url(r'^superadmin/', include(admin.site.urls)),

    url(r'^blog/(?P<username>[-\w]+)/$',view='index', name='index'),
    url(r'^blog/(?P<username>[-\w]+)/post/(?P<postslug>[-\w]+)',view='single_post', name='view_blog_post'),
    url(r'^login/$', view='log_user_in'), # i log in to admin page from this url
    url(r'^admin/$', view='admin_view', name='admin'),# to this url
    url(r'^admin/logout/$', view='log_user_out', name='logout'),
    url(r'^admin/post/add/$', view='add_post',name='addpost'),
    url(r'^admin/post/edit/(?P<post_id>\d+)', view='edit_post', name='editpost'),
    url(r'^admin/post/delete/(?P<post_id>\d+)', view='delete_post', name='deletePost'),

)
4

1 回答 1

4

当您注销时,您手动删除request.session['loggedin']密钥,当您浏览到管理页面时,request.session['loggedin']由于您已经删除了该密钥而失败。

您可以控制是否request.sessionloggedin密钥:

`loggedin` in request.session

因此,编写您的管理视图,如:

def admin_view(request):

    if `loggedin` in request.session and request.session['loggedin'] == "djangoo":
    #other codes..

或者干脆使用

if request.session.get('loggedin') == 'djangoo'

正如@Alexander Larikov 所说

编辑:我需要提一下,最好检查一个键是否存在于字典或类似字典的结构中,特别是如果您也可以在其他地方删除该键。

于 2012-09-14T13:15:33.077 回答