我想设置断开连接。我有一个页面,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"),
]
mainApp/template/mainApp/page1.html
<body>
<h1> PAGE 1 </h1>
{% if user.is_authenticated %}
<a href="{% url 'login' %}"> Logout </a>
{% endif %}
</body>
mainApp/views.py
@login_required
def page1(request):
return render(request, 'mainApp/p1.html', {})
mainApp/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/