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 不存在或为空,则生成一个普通的登录表单。

相关推荐
BingoGo11 分钟前
FrankenPHP 原生支持 Windows 了
后端·php
Moment12 小时前
Vibe Coding 时代,到底该选什么样的工具来提升效率❓❓❓
前端·后端·github
Victor35612 小时前
MongoDB(27)什么是文本索引?
后端
可夫小子13 小时前
OpenClaw基础-3-telegram机器人配置与加入群聊
后端
IT_陈寒13 小时前
SpringBoot性能飙升200%?这5个隐藏配置你必须知道!
前端·人工智能·后端
aiopencode15 小时前
使用 Ipa Guard 命令行版本将 IPA 混淆接入自动化流程
后端·ios
掘金者阿豪15 小时前
Kavita+cpolar 打造随身数字书房,让资源不再混乱,通勤 、出差都能随心读。
后端
helloweilei15 小时前
python 抽象基类
python
心之语歌15 小时前
Spring Security api接口 认证放行
后端
用户83562907805115 小时前
Python 实现 PPT 转 HTML
后端·python