我想把断网设置好.我有一个页面,页面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的视图,例如.logout_user(),如果您的视图需要来自模型的任何数据,那么它将从您的模型获取.

回答你最后一个问题

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

因为这是一个Post/Redirect/Get%的Web开发设计模式

When a web form is submitted to a server through an 100 request, attempts to refresh the server response can cause the contents of the original 101 to be resubmitted, possibly causing undesired results, such as a duplicate web purchase. Some browsers mitigate this risk by warning the user that they are about to re-issue a 101 request.

Django相关问答推荐

Django的update_or_create失败,尽管指定了kwargs'

如何根据递归ManyToManyField值创建Django查询集?

在Django中使用Generil.ListView类时,分页不起作用

django优化查询

Django为什么我的post.count_view递增2?

Django:作为模型中的列表元素的字段

Django REST框架中如何从另一个视图调用API视图?

在 Django 中按月份和年份对帖子进行分类

如何连接到 docker 容器中的 postgres 数据库?

Django - 将 HTML 输出转换为变量

获取结果集中返回的元素数的 django 模板标签是什么?

多租户 Django 应用程序:根据请求更改数据库连接?

验证 Django 模型对象的正确方法?

通过 django shell 保存图像/文件

使用 scrapy 访问 Django 模型:定义 Django 元素的路径

Django:如何在视图中获取格式日期?

Django - 配置不当:模块django.contrib.auth.middleware

django过滤器超过几天?

在 Django 开发服务器中关闭静态文件的缓存

Django模板过滤器(filters)、标签(tags)、simple_tags和inclusion_tags