0

我正在嘗試強制註銷不再活動的django用戶。我需要能夠強制用戶通過用戶名註銷。在做了一些研究之後,我發現django可以選擇使用註銷(請求)註銷,但它不允許我選擇基於用戶名的註銷。 任何人有任何想法? 感謝基於用戶名的django註銷用戶

我試圖測試這個下面的代碼我的問題,這是從How to force user logout in django? 採取在我的模型:

from django.contrib.auth.models import User 
from django.db import models 
from datetime import datetime 

class MyUser(User): 
force_logout_date = models.DateTimeField(null=True, blank=True) 

def force_logout(self): 
    self.force_logout_date = datetime.now() 
    self.save() 

然後我在views.py加入這一部分:

from myapp.models import MyUser 
MyUser.objects.get(username='johndoe').force_logout() 
現在

但我下面的錯誤:

MyUser matching query does not exist. 

Request Method:  POST 
Request URL: http://localhost:8000/datatableuser/?  
typeoftask=edit&username=xyzstaff 
Django Version:  1.8.11 
Exception Type:  DoesNotExist 
Exception Value:  

MyUser matching query does not exist. 

Exception Location:  /usr/local/lib/python2.7/dist- 
packages/django/db/models/query.py in get, line 334 
Python Executable: /usr/bin/python 
Python Version:  2.7.6 
Python Path:  

['/home/paul/Desktop/djangoproject/peptidetrackerdatabase/src', 
'/usr/local/lib/python2.7/dist-packages/setuptools-20.3.1-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/pip-8.1.1-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/Sphinx-1.4-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/imagesize-0.7.0-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/alabaster-0.7.7-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/Babel-2.2.0-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/snowballstemmer-1.2.1-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/docutils-0.12-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/Pygments-2.1.3-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/Jinja2-2.8-py2.7.egg', 
'/usr/local/lib/python2.7/dist-packages/MarkupSafe-0.23-py2.7-linux-x86_64.egg', 
'/usr/lib/python2.7', 
'/usr/lib/python2.7/plat-x86_64-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', 
'/usr/lib/python2.7/dist-packages/PILcompat', 
'/usr/lib/python2.7/dist-packages/gtk-2.0', 
'/usr/lib/pymodules/python2.7', 
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] 

Server time: Thu, 14 Apr 2016 22:12:42 -0700 enter code here 

回答

0

它主要取決於您如何進行身份驗證。如果不知道確切的答案,就不可能給你答案。

但是,假設你使用的是默認的Django的認證,這個答案應該還是有效的:

How to force user logout in django?

+0

感謝您的答覆你好。我看到這個解決方案,但無法弄清楚如何實現它,因爲我的Session.objects.all()總是返回空列表,我不知道爲什麼 – Paul85

+0

@ Paul85請檢查'django.contrib.sessions'是在已安裝的應用程序中,您激活的中間件中的「django.contrib.sessions.middleware.SessionMiddleware」,用戶可以登錄並應用遷移。另外,請在數據庫中手動驗證會話表是否存在,並且不是空的。 –

+0

我有檢查和我的settings.py是好的。 – Paul85