Django用户登录后的‘重定向’

有查看用户信息的url如下:

复制代码
http://127.0.0.1:8000/account/my-information/

在urls.py文件中定义,处理该url的view函数为views.py文件中的myself。

python 复制代码
path('my-information/',views.myself, name='my_information')

处理该url的view函数如下。表明,只有在用户登录的情况下才能执行。

python 复制代码
@login_required() #装饰器函数,只有登录才执行下面代码
def myself(request):

    if hasattr(request.user, 'userprofile'):
        userprofile = UserProfile.objects.get(user=request.user)
    else:
        userprofile = UserProfile.objects.create(user=request.user)

    if hasattr(request.user, 'userinfo'):
        userinfo = UserInfo.objects.get(user=request.user)
    else:
        userinfo = UserInfo.objects.create(user=request.user)

    context = {"user":request.user, "userinfo":userinfo, "userprofile":userprofile}
    return render(request, "account/myself.html", context)

在项目的setting文件中做如下设置。功能为:在没有通过用户登录状态检查时,跳转至该url

python 复制代码
LOGIN_URL = '/account/login/'

注意,此时页面虽然跳转到了登录url,但是其中附加了一个next变量。该变量后面的内容表明在登录完成后希望能够自动跳转的位置。

复制代码
http://127.0.0.1:8000/account/login/?next=/account/my-information/

为了实现自动跳转,需要修改登录页面的html文件,内容如下。

html 复制代码
{% if next %}
    <form class="form-horizontal" action="{% url 'account:user_login' %}?next={{ next }}" method="post">
{% else %}
    <form class="form-horizontal" action="{% url 'account:user_login' %}" method="post">
{% endif %}
        {% csrf_token %}
        <!--以下为表单的具体内容,省略-->

这段代码是 Django 模板语言的代码,用于在模板中根据条件渲染不同的 HTML 表单。

具体来说,它做了以下操作:

  • {% if next %}:检查是否存在名为 next 的变量。如果 next 存在且为真值(不为空),则执行下面的代码块。
  • <form class="form-horizontal" action="{% url 'account:user_login' %}?next={``{ next }}" method="post">:这是一个 HTML 表单元素,它的 action 属性指定了表单提交的目标 URL。在这里,它使用了模板标签 {% url 'account:user_login' %} 来生成登录视图的 URL,并在 URL 后面附加了查询字符串 next={``{ next }}next 是一个变量,它的值是登录后要重定向到的地址(如果有的话)。表单的提交方法为 POST
  • {% else %}:如果上述条件不成立,即 next 不存在或为空,则执行下面的代码块。
  • <form class="form-horizontal" action="{% url 'account:user_login' %}" method="post">:这也是一个 HTML 表单元素,它的 action 属性指定了表单提交的目标 URL。与前面不同的是,这里没有附加查询字符串,所以不会进行重定向。表单的提交方法为 POST

这段代码的作用是,如果存在 next 变量且不为空,则生成一个带有 next 参数的登录表单,用于在登录后重定向到指定的地址;如果 next 不存在或为空,则生成一个普通的登录表单。

相关推荐
鸿芯微控科技4 分钟前
MFC质量流量控制器流量不准怎么排查?设定值、反馈值与参考流量对比,附Python代码
c++·python·mfc
颜进强7 分钟前
前端看后端 14:什么是 CORS?
前端·后端
大尚来也10 分钟前
用 Python 自动整理文件、重命名、分类电脑文件夹
开发语言·python
极序时代GEO品牌优化35 分钟前
杭州极序时代|面向地域、设备与用户画像的动态GEO
人工智能·python·算法·极序时代geo
用户69371750013841 小时前
了解一下 Agent Harness
android·前端·后端
qq_22589174661 小时前
基于Python的外卖订单数据分析可视化系统
python·信息可视化·django
swipe1 小时前
16|(前端转全栈)前端人排查后端问题:curl、traceId、日志、MySQL、Redis 怎么用?
前端·后端·面试
MC皮蛋侠客1 小时前
SQLAlchemy 系列(三):声明式映射与 Schema——让类型、默认值和约束一致
数据库·python
亦暖筑序1 小时前
重新认识 AgentScope-Java 2.0:ReActAgent 负责推理,HarnessAgent 负责运行
java·后端·agent
会博通·代码搬运工1 小时前
会博通API对接实战:工程企业文档分布式采集系统的技术实现与Python SDK详解
开发语言·分布式·python·线性代数·矩阵·架构·电子档案合规