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

发布于:2024-05-10 ⋅ 阅读:(24) ⋅ 点赞:(0)

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

http://127.0.0.1:8000/account/my-information/

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

path('my-information/',views.myself, name='my_information')

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

@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

LOGIN_URL = '/account/login/'

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

http://127.0.0.1:8000/account/login/?next=/account/my-information/

为了实现自动跳转,需要修改登录页面的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 不存在或为空,则生成一个普通的登录表单。