我似乎遇到与此问题相同的问题:Django logout problem
我有点怪,它适用于谷歌浏览器......但不适用于Firefox ...
这是我的退出功能:(在views.py中)
def my_logout(request):
logger.debug("Logout called by user")
try:
# Here I do some custom stuff, like logging this action in a database and so on
# For this question it shouldn't matter... because in a try catch
# so whatever goes wrong here, logging out should work anyway
except Exception, e:
logger.info("Logging logout action error: %s" % e)
logout(request)
return HttpResponseRedirect("/")
在settings.py中的我有:
LOGIN_URL = '/desktop/login/'
LOGOUT_URL = '/desktop/logout/'
LOGIN_REDIRECT_URL = '/'
在app iamapps的urls.py中(在项目网址中包含/ desktop /):
url(r'^login/$', 'iamapps.views.my_login', name='iamapps.login'),
url(r'^logout/$', 'iamapps.views.my_logout', name='iamapps.logout'),
进一步信息:
它确实在谷歌浏览器中工作但在Firefox中不起作用这一事实让我感到很困惑。似乎它与firefox有关,一直记住用户登录...
修改 我得到了一个破损的管道....但我似乎没有注销...但是在注销后进入主视图....
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 127, in finish_response
self.write(data)
File "/usr/lib/python2.7/wsgiref/handlers.py", line 210, in write
self.send_headers()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 268, in send_headers
self.send_preamble()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 192, in send_preamble
'Date: %s\r\n' % format_date_time(time.time())
File "/usr/lib/python2.7/socket.py", line 324, in write
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 58684)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 582, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/media/storage/django/sites/iamfloraservice/parts/django/django/core/servers/basehttp.py", line 139, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 641, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 694, in finish
self.wfile.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
[24/Dec/2012 14:33:25] "GET / HTTP/1.1" 200 48247
编辑2 在注销并重定向后,它会转到此视图:
def home(request, template='iamfloraservice/home.html'):
logger.debug("Home view called by user %s" % request.user)
return render_to_response(template,{},context_instance=RequestContext(request))
我认为将请求重定向到此视图会导致问题.... 在日志中,它仍然是用户'michel'(因为视图使用来自重定向的请求,并且有用户michel)...但是...用户michel同时被注销....
编辑3
因为它是由记录器引起的。 取消标记记录没有帮助 它是默认记录器:
import logging
logger = logging.getLogger(__name__)
编辑4 (2012年12月30日)
我的注销来自一个主窗口,我在用户登录时显示注销链接,如果用户注销则显示登录链接。它还包含一个工具栏,根据用户和组的成员身份填充工具。
我认为问题是,它正在重新加载这个主窗口,而缓存和它的请求中的用户尚未清除。不知何故Chrome知道如何处理这个问题,而firefox导致管道错误。在重新加载后,在浏览器中手动清除缓存会产生正确的视图....
解决方案可能是重定向到页面中没有包含用户的任何内容...... 或者找出在合适的时刻清除缓存......
这个问题可能描述的相同......但是我不能指望用户在浏览器中做任何事情只是为了注销?见django 1.4 caching GET to /login/
编辑5 (2012年12月31日)
这似乎是一个缓存问题....但不知道如何解决这个问题。
这些是我的缓存设置:
if not DEBUG:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
但我尝试了没有虚拟缓存
编辑6 (4-jan-2013) 仍然没有解决方案......我改变了我退出django方式的方式,现在我正在使用信号......请参阅下面我自己的答案。
但它仍然提供了brokenpipe错误,导致firefox停止注销。这不是缓存问题。如果我去另一个页面,甚至更糟......管理页面。我还在登录注销的唯一方法是通过管理页面上的注销....如果它不是管理员用户...没有办法让我在firefox浏览器上注销。
使用管理界面注销时,信号正常工作......
我通过关闭信号进行检查....但仍然在firefox中注销不起作用。
结论:返回主页面()会导致问题。
编辑7 (2013年1月4日) 我做了一个简单的登出视图进行测试, 这个模板:
<html>
<head>
<title>
Logged out
</title>
</head>
<body>
You are succesfully logged out.<br>
<br>
<a href="/">Go back to the main page</a>
or<br>
<a href="/desktop/login/?next=/">log in again</a>
</body>
</html>
和退出的视图:
class LoggedOutView(TemplateView):
template_name = "iamapps/logged_out.html"
并将网址更改为:
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/desktop/loggedout/'}, name='iamapps.logout'),
#url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='iamapps.logout'),
url(r'^loggedout/$', LoggedOutView.as_view(),name='iamapps.loggedout'),
然而,简单地说就是......我关掉了信号。
它仍然无法在firefox中运行....但它适用于chrome
在Firefox中,它不会转到已注销的页面
答案 0 :(得分:12)
我通常只使用提供的视图来注销用户。只需将其添加到根urls.py
文件中:
# Would be nice to use settings.LOGIN_URL for `next_page` here, too
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login'}),
你会很高兴。
快乐的Djangoing。
答案 1 :(得分:1)
浏览到stackoverflow ...(做了另一次搜索)
我找到了这个:......见django.contrib.auth.logout in Django ..
但情况更糟......我发现这......惊讶......但是解释了一切: Django, Logout_URL doesn't redirect well
我发现这是一个不会修复bug(@ ## $ %%)不允许在圣诞节前夕诅咒....
所以做我自定义的东西的解决方案是在信号中而不是使用我自己的视图。 做默认视图并重定向... 并使用此文档创建信号.. https://docs.djangoproject.com/en/dev/topics/auth/#login-and-logout-signals
添加信号非常简单,我把它放在我的主应用程序(iamapps)的models.py中:
import logging
from django.contrib.auth.signals import user_logged_out
from django.contrib.auth.signals import user_logged_in
logger = logging.getLogger(__name__)
def iam_logged_out_actions(sender, user, request, **kwargs):
#whatever...
logger.debug("Logging out: user = %s" % user)
user_logged_out.connect(iam_logged_out_actions)
def iam_logged_in_actions(sender, user, request, **kwargs):
#whatever...
logger.debug("Logging in: user = %s" % user)
user_logged_in.connect(iam_logged_in_actions)
这有效....但是它没有解决我认为可能导致登出失败的破管...因此在firefox中注销仍然失败...并且在chrome中它可以工作...... 从django管理页面注销可以在firefox中运行..并且信号还有另一个专家:也是从管理界面注销,信号被调用...
注销我现在使用这个urls.py:
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='iamapps.logout'),
答案 2 :(得分:1)
我怀疑原始注销视图会返回一个清除cookie或类似内容的响应,并且您将该响应丢弃。您可以尝试简单地将响应返回给用户吗?
def my_logout(request):
# something...
return logout(request)
答案 3 :(得分:1)
最后我完全切换到django默认值... 使用:
在views.py中:
from django.contrib.auth.forms import AuthenticationForm
from django.views.generic.edit import FormView
class LoginView(FormView):
"""
This is a class based version of django.contrib.auth.views.login.
"""
form_class = AuthenticationForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'iamapps/login.html'
@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self, *args, **kwargs):
return super(LoginView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
"""
The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we
can check the test cookie stuff and log him in.
"""
self.check_and_delete_test_cookie()
login(self.request, form.get_user())
return super(LoginView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(LoginView, self).get_context_data(**kwargs)
apps_settings=iamapps_settings()
if apps_settings[LOGON_BASE_APP_NAME]:
self.extend_template="%s/base.html" % apps_settings[LOGON_BASE_APP_NAME]
else:
self.extend_template="iamapps/base.html"
context['extend_template']=self.extend_template
return context
def form_invalid(self, form):
"""
The user has provided invalid credentials (this was checked in AuthenticationForm.is_valid()). So now we
set the test cookie again and re-render the form with errors.
"""
self.set_test_cookie()
return super(LoginView, self).form_invalid(form)
def get_success_url(self):
if self.success_url:
redirect_to = self.success_url
else:
redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')
netloc = urlparse.urlparse(redirect_to)[1]
if not redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
# Security check -- don't allow redirection to a different host.
elif netloc and netloc != self.request.get_host():
redirect_to = settings.LOGIN_REDIRECT_URL
return redirect_to
def set_test_cookie(self):
self.request.session.set_test_cookie()
def check_and_delete_test_cookie(self):
if self.request.session.test_cookie_worked():
self.request.session.delete_test_cookie()
return True
return False
def get(self, request, *args, **kwargs):
"""
Same as django.views.generic.edit.ProcessFormView.get(), but adds test cookie stuff
"""
self.set_test_cookie()
return super(LoginView, self).get(request, *args, **kwargs)
和网址:
url(r'^login/$', LoginView.as_view(), name='login'),
这解决了我所有的烦恼...关于登录和登陆......
登录和注销信号正常工作:
from django.contrib.auth.signals import user_logged_out, user_logged_in
# Note, these login and logout signals are registered in imamstats views
def iam_logged_out_actions(sender, user, request, **kwargs):
try:
# ... do my logging out actiosn (stats etc.)
except Exception, e:
logger.error("Logging logout action error: %s" % e)
# Note, these login and logout signals are registered in imamstats views
def iam_logged_in_actions(sender, user, request, **kwargs):
try:
# ... do my log in stats etc. things
except Exception, e:
logger.error("Logging login action error: %s" % e)
答案 4 :(得分:0)
已验证的答案在提到的版本中效果很好,但是在django 2.2版本中不再起作用。因此,要在注销后成功进行重定向,您必须定义属性。
from django.contrib import admin
from django.urls import path, include
from dark_bot import views
from django.contrib.auth import views as v
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name="index"),
path('contact/', views.contact, name="contact"),
path('search/', include('search.urls')),
path('user/', include('accounts.urls')),
path('dashboard/', include('dashboard.urls')),
path('accounts/login/', v.LoginView.as_view(), name="login"),
path('accounts/logout/',v.LogoutView.as_view(next_page='/'),name="logout")
# path('dashboard/', include('dashboard.urls')),
]
''''
This is how you can see i passed the next_page attribute to the class LogoutView which will tell where to redirect or go after successfull logout.
Hope this may help someone.
Happy Coding!