Django网站登出功能失效求助:Method Not Allowed(GET)错误
解决Django登出功能405 Method Not Allowed问题
你的问题出在两个地方:
1. 模板URL标签语法错误
你写的href="{% 'logout' url %}"是错误的Django模板语法,正确的URL反向解析格式应该是{% url 'logout' %}——把url关键字放在前面,路由名称放在引号里。
2. LogoutView默认只接受POST请求
Django自带的LogoutView为了安全,默认只允许POST请求,直接通过a标签的GET请求访问/logout/就会触发Method Not Allowed错误。
解决方案(二选一)
方案一:用表单发送POST请求(推荐,更安全)
把base.html里的登出链接改成POST表单,同时加上CSRF令牌:
<form action="{% url 'logout' %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" style="border: none; background: none; color: blue; text-decoration: underline;">登出</button> </form>
(样式可以根据你的页面调整,让按钮看起来像普通链接)
方案二:允许LogoutView处理GET请求(不推荐,安全性较低)
如果一定要用GET请求实现,修改urls.py里的LogoutView配置,添加http_method_names参数允许GET方法:
path('logout/', auth_view.LogoutView.as_view( next_page='login', http_method_names=['get', 'post'] ), name='logout'),
同时记得把模板里的URL标签改成正确格式:
href="{% url 'logout' %}"
内容的提问来源于stack exchange,提问作者Andre Pratama
相关产品推荐
相关产品推荐

