为什么我在更新数据后在django中注销时出现此错误?

时间:2015-03-10 02:39:40

标签: python django django-views

我是django的新手,我正在尝试创建一个Admin具有CRUD功能的应用程序。我的问题是当管理员更新其他用户,然后注销,注销功能正常工作。但是,当管理员更新他/她自己然后管理员注销时,出现此错误

KeyError at /simofa/logout/
'username'
Request Method: GET
Request URL:    http://localhost:8000/simofa/logout/
Django Version: 1.7.4
Exception Type: KeyError
Exception Value:    
'username'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py in __delitem__, line 56
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:    
['/home/boss/kantor/akun',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-i386-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
Server time:    Tue, 10 Mar 2015 02:24:44 +0000

这是追溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/simofa/logout/

Django Version: 1.7.4
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'simofa',
 'accounts')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/boss/kantor/akun/simofa/views.py" in logout
  174.     del request.session['username']
File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py" in __delitem__
  56.         del self._session[key]

Exception Type: KeyError at /simofa/logout/
Exception Value: 'username'

这是我的观点:(更新和退出)

def update_user(request, pk, template_name='update_user.html'):
    #cek session
    if 'username' in request.session:
        user = get_object_or_404(User, pk=pk) #ambil id dengan get
        profile = UserProfile.objects.filter(user=user).first()
        user_form = UserForm(data=request.POST, instance=user) #gunakan instance untuk mengambil data yang sudah ada
        profile_form = UserProfileForm(data=request.POST, instance=profile) #gunakan instance untuk mengambil data yang sudah ada
        users = User.objects.all()
        if request.POST:
            if user_form.is_valid() and profile_form.is_valid():
                user.set_password(user.password) #hashing
                user.save()
                profile = profile_form.save(commit=False)
                profile.user = user
                profile.save()
                return redirect('manajemen_user')
        else:
            user_form = UserForm(instance=user)
            profile_form = UserProfileForm(instance=profile)

        data = {
                'user_form': user_form,
                'profile_form': profile_form,
                'object_list': users,
        }
        return render(request, template_name, data)
    else:
        return HttpResponseRedirect('/simofa/login')

def logout(request):
    del request.session['username']
    del request.session['password']
    del request.session['hak_akses']
    return HttpResponseRedirect('/simofa/login')

我对此错误感到困惑,为什么当管理员更新自己然后注销它无法正常工作?以及如何解决它?

因为我认为我的更新和注销功能没有任何问题。 我非常感谢你的意见。所以,请帮帮我。非常感谢你

2 个答案:

答案 0 :(得分:1)

您可以执行request.session.flush(),因此会话数据将刷新,请参阅django auth source中的logout function

def logout(request):
    """
    Removes the authenticated user's ID from the request and flushes their
    session data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if hasattr(user, 'is_authenticated') and not user.is_authenticated():
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)

    # remember language choice saved to session
    language = request.session.get(LANGUAGE_SESSION_KEY)

    request.session.flush()

    if language is not None:
        request.session[LANGUAGE_SESSION_KEY] = language

    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()

答案 1 :(得分:0)

更改用户密码时,their session is reset。 Django负责重新注入会话哈希,以便用户不会自动注销,但是你在会话中存储的值将会消失。

我认为您正试图让您的注销视图不会崩溃。在logout中,将每一行更改为:if 'username' in request.session: del request.session['username'](用正确的值替换用户名)。