django - 断开连接不会发生

标签 django

我想设置断开连接。我有一个页面,Page 1,只有经过身份验证的用户才能访问。当我断开连接时,我仍然可以访问第 1 页。

我还有其他问题,Django 如何知道执行 logout_user 函数? (我对登录有同样的问题,但由于它有效,我没有问自己这个问题 ^^)。

为什么我们在 html 中已经指示重定向时在返回中指示重定向?

appIdentification/views.py

from django.contrib.auth import authenticate, login, logout
def logout_user(request):
    logout(request)
    messages.success(request, ("You Were Logged Out!"))
    return redirect('home')

appIdentification/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('/login', views.login_user, name="login"),
    path('', views.logout_user, name="logout"),
]

ma​​inApp/template/mainApp/page1.html

<body>
    <h1> PAGE 1 </h1>
    {% if user.is_authenticated %}
    <a href="{% url 'login' %}"> Logout </a>
    {% endif %}
</body>

ma​​inApp/views.py

@login_required
def page1(request):
    return render(request, 'mainApp/p1.html', {})

ma​​inApp/urls.py

from django.urls import path, include
from . import views
path('mainApp', include('django.contrib.auth.urls')),
path('mainApp', include('appIdentification.urls')),
path('home', views.home, name="home"),
path('p1', views.page1, name="p1"),

最佳答案

第一个问题的答案

I have a page, Page 1, that is only accessible to an authenticated user. When i disconnect I can still access page 1.

因为你输入了错误的注销 url,所以应该是

<a href="{% url 'logout' %}"> Logout </a>

代替

<a href="{% url 'login' %}"> Logout </a>

第二个问题

How does Django know to execute the logout_user function ?

Django 使用MVT基本上当你去一些 url 时,这个模式就是这样。 /logout/ 它调用映射到该 url 的 View ,例如。 logout_user() 如果您的 View 需要来自模型的任何数据,那么它会从您的模型中获取。

最后一个问题的答案

And why do we indicate a redirection in the return when in the html we already indicate the redirection ?

因为它是 Post/Redirect/Get网页开发设计模式

当通过 HTTP POST 请求将 Web 表单提交到服务器时,尝试刷新服务器响应可能会导致原始 POST 的内容重新提交,可能会导致不良结果,例如重复的网络购买。一些浏览器通过警告用户他们将要重新发出 POST 请求来减轻这种风险。

关于django - 断开连接不会发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74262020/

相关文章:

python - 如何使用 python/django 从 gmail 或 yahoo 等各种服务导入联系人

database - 基于语言的 URL 和数据库路由

mysql - 每个帖子的单独获取请求和数据库命中以获得类似状态

python - 由于导入机制导致 isinstance() 和 type() 等价失败(python/django)

python - django模型过滤字段的字段

django - 模块未找到错误 : No module named 'polls'

python - Celery 中的异常处理?

python - 我是否必须将我的 django 项目复制到另一台机器上才能在其上执行 celery 任务?

django - 从 Django 运行 unix 命令

django - 检查views.py中的 bool 字段状态