使用 @login_required修饰的视图函数,在编写登陆视图函数时,如何判断是由@login_required修饰的视图函数跳转而来,而不是直接访问的登录视图函数
时间: 2024-05-05 09:20:38 浏览: 12
可以在登录视图函数中通过`request.META.get('HTTP_REFERER')`获取跳转页面的URL,然后判断这个URL是否是需要登录才能访问的页面,如果是,则说明是由`@login_required`修饰的视图函数跳转而来的,否则就是直接访问登录视图函数。
示例代码如下:
```python
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
# 可以使用 request.user 访问当前登录用户
return render(request, 'my_template.html')
def login(request):
if request.method == 'POST':
# 处理用户登录
# ...
# 获取跳转页面的URL
next_url = request.GET.get('next')
if next_url and next_url.startswith('/'):
# 如果跳转页面需要登录才能访问,则跳转到该页面
return redirect(next_url)
# 如果没有跳转页面,或者跳转页面不需要登录,则跳转到其他页面
return redirect('home')
# 显示登录页面
return render(request, 'login.html')
```
在模板中,可以使用`{% url 'login' %}`获取登录页面的URL,然后在需要登录才能访问的页面中添加`?next={{ request.path }}`参数,即可将当前页面的URL作为参数传递给登录页面,登录成功后就可以跳转回该页面。例如:
```html
{% if user.is_authenticated %}
<p>欢迎,{{ user.username }}!</p>
{% else %}
<p>请先<a href="{% url 'login' %}?next={{ request.path }}">登录</a></p>
{% endif %}
```