為什么我在更新數據后在django中注銷時出現此錯誤?

[英]Why when i logout in django after i updated my data appears this error?


i'm new in django and i'm trying to create an application that Admin have CRUD function. My problem is when admin updated other user, and then logged off, log off function worked properly. But, when admin updated him/her self then admin logout, appears this error

我是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

This is the traceback:

這是追溯:

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'

This is my views: (update and logout)

這是我的觀點:(更新和注銷)

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')

I've confused with this error, why when admin update his self then logout it can't work properly? And how to fix it ?

我對此錯誤感到困惑,為什么當管理員更新自己然后注銷它無法正常工作?以及如何解決它?

Because i think nothing wrong with my update and logout function. I will very grateful for your input. So, please help me. Thank you very much

因為我認為我的更新和注銷功能沒有任何問題。我非常感謝你的意見。所以,請幫幫我。非常感謝你

2 个解决方案

#1


0  

When you change the user's password, their session is reset. Django takes care of reinjecting the session hash so that the user isn't automatically logged out, but values you stored in the session will be gone.

更改用戶密碼時,會話將重置。 Django負責重新注入會話哈希,以便用戶不會自動注銷,但存儲在會話中的值將會消失。

I think you're trying to keep your logout view from crashing. In logout, change each line to look like this: if 'username' in request.session: del request.session['username'] (replacing username with the correct value).

我認為你試圖讓你的注銷視圖不會崩潰。在注銷時,將每行更改為如下所示:if request.session中的'username':del request.session ['username'](用正確的值替換username)。

#2


1  

You can perform request.session.flush(), so session data will be flushed, see logout function from django auth source

您可以執行request.session.flush(),因此會刷新會話數據,請參閱django auth source的logout函數

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()

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/03/10/9c0cc5532bd0cfd787c0706ebb39b233.html



 
  © 2014-2022 ITdaan.com 联系我们: