Django中的LogoutView有问题.当我try 输入"accounts/logout"链接时,django服务器会在cmd中弹出:

Method Not Allowed (GET): /accounts/logout/
Method Not Allowed: /accounts/logout/
[24/Feb/2024 13:48:11] "GET /accounts/logout/ HTTP/1.1" 405 0

以下是查看文件的内容:

从django.urls导入路径,包括 从django.contri.auth将视图导入为auth_views 从.view导入showProfile、logout_user

app_name = 'user'
urlpatterns = [
    path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'),
    path('', include('django.contrib.auth.urls')),
]

而这是‘注册/Logging_out.html’文件内容:

{% extends "generic_base.html" %}

{% block content %}
    <form method="post" action="{% url 'user:logout' %}">
        {% csrf_token %}
        <button type="submit">Logout</button>
    </form>
{% endblock content %}

模板文件位于应用程序‘Account’中.而这app_name = 'user'人 以下是Generic_base.html模板的内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% block title %}
        <title>Donations</title>
    {% endblock title %}
</head>
<body>
    {% block content %}
    {% endblock content %}
</body>
</html>

我try 了很多方法来解决这个问题,但都没有奏效. 我也看到了Stack Overflow中提供的关于这个问题的所有解决方案,但都没有奏效.我也try 了Django built in Logout view Method Not Allowed (GET): /users/logout/中的解决方案,但这不能解决问题.

推荐答案

ALogoutView主要有template_name,因为它是TemplateView YES的子类,但这只有在重定向以某种方式指向LogoutView本身时才使用,但无论如何这可能是一个糟糕的 idea .

因此,您可以使用LogoutView显示要注销的表单,将注销按钮放在其他视图或所有页面上,然后使用问题中提供的表单在那里注销.因此,您可以将此表单放在navbar中,它将注销用户,如果LogoutView中指定了next_page,则重定向到next_page指定的页面;如果没有指定,则重定向到LOGOUT_REDIRECT_URL setting [Django-doc].

Python相关问答推荐

无法定位元素错误404

Python解析整数格式说明符的规则?

Pandas计数符合某些条件的特定列的数量

将JSON对象转换为Dataframe

Scrapy和Great Expectations(great_expectations)—不合作

不能使用Gekko方程'

Plotly Dash Creating Interactive Graph下拉列表

Polars asof在下一个可用日期加入

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

手动设置seborn/matplotlib散点图连续变量图例中显示的值

如何防止Pandas将索引标为周期?

ruamel.yaml dump:如何阻止map标量值被移动到一个新的缩进行?

Discord.py -

比Pandas 更好的 Select

从嵌套极轴列的列表中删除元素

Python—在嵌套列表中添加相同索引的元素,然后计算平均值

需要帮助使用Python中的Google的People API更新联系人的多个字段'

如何使用pytest在traceback中找到特定的异常

EST格式的Azure数据库笔记本中的当前时间戳

用LAKEF划分实木地板AWS Wrangler