python - 使用@login_required 装饰器的 django 注册/登录 View

标签 python django authentication

我正在尝试为用户创建一个单独的注册 View ,但它不起作用,因为我在我的“个人资料” View 上使用了@login_required 装饰器,它应该在登录后重定向到。目前 login_user View 有效美好的。

问题:如何在“个人资料” View 上使用@login_required 装饰器时注册用户?

我的登录和注册 View 代码如下所示:

def login_user(request):
  message = None
  if request.method == 'POST':
    if 'login' in request.POST:
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
            if not user:
                message = "Invalid email or password!"
            else:
                login(request, user)
                return redirect('profile')
  return render(request, 'users/login.html', {'message': message})


def register_user(request):
  message = None
  if request.method == 'POST':
    user_form = RegistrationForm(data=request.POST)
    if user_form.is_valid():
        user_form.save()
        user = authenticate(username=user_form.cleaned_data['email'],
                            password=user_form.cleaned_data['password1'])
        if user:
            login(request, user)
            return redirect('profile')
    else:
        message = "Email already exists or passwords do not match"
  return render(request, 'users/register.html', {'message': message})

为了让我的注册页面绕过 @login_required 装饰器,我使用了 login(request, user) 方法,但这似乎不起作用。

最佳答案

您必须提到后端作为登录函数的第三个参数。 所以在你的 register_user 函数中:

if user:
    # specify the backend as the third argument
    login(request, user, backend='django.contrib.auth.backends.ModelBackend')
    return redirect('profile')

关于python - 使用@login_required 装饰器的 django 注册/登录 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28435313/

相关文章:

python - 具有可变长度列表的 Format()

python - 将 scipy 稀疏行矩阵添加到另一个稀疏矩阵

sql - 类似 Twitter 的帖子时间轴的数据库结构和查询

django - 如何创建一个在 Django 登录时设置 session 变量的中间件?

php - Laravel 5.3 记住我身份验证问题

android - 如何在 Android 上对 MIFARE Ultralight C 进行身份验证

python - 列表项不能成倍增加

java - OCR专用近似字符串匹配库

python - 在不返回 HttpResponse 或使用 URL 的情况下使用 wkhtmltopdf 创建 PDF 文件的任何方法?我只想将 PDF 文件附加到电子邮件

javascript - 在 Django 中使用 SIMPLE javascript 确认删除