【问题标题】:Rediect to view or URL from Model in Dajngo从 Django 中的模型重定向到视图或 URL
【发布时间】:2020-07-04 15:55:20
【问题描述】:

当用户尝试暴力攻击超过 10 次不成功的尝试(在登录页面中)时,我将锁定用户。因此,如下面的代码所示,我将用户从登录视图移动到 '/login_lock/' 视图,如 url 所示。但不确定由于某些原因我无法移动到 /login_lock/ 并使用无效的登录凭据验证错误重新迭代登录页面/视图。

您能否帮助我如何通过来自 user_login_failed_callback 的调用(models.py 中的此调用)转移到 login_lock 视图。

@receiver(user_login_failed)
def user_login_failed_callback(sender, credentials,  **kwargs):

        username = credentials['username']
        user = User.objects.get(username=username)
        profile = user.get_profile()

        if profile.failed_login_count <= 9:
            profile.failed_login_count = profile.failed_login_count+1
            profile.last_login_attempt_date_time = timezone.now()
            profile.save()
        else:
            return HttpResponseRedirect('/login_lock/')

    url(r'^login/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login.html'}),
    url(r'^login_lock/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login_lock.html'}),

【问题讨论】:

  • 你能分享你使用的包含登录逻辑的视图吗?您需要从那里重定向用户,因为从信号返回重定向不会做任何事情。 (发送者对信号方法的返回值不做任何事情)。

标签: django django-models django-views django-authentication


【解决方案1】:

不幸的是,这种设计不起作用。您不能在信号处理程序中更改请求的响应。我会考虑包装auth_views.login 并在那里处理逻辑。或者创建您自己的订阅模式,允许从订阅者返回响应。

【讨论】:

    【解决方案2】:

    您应该使用 reverse() 函数,该函数位于 django.urls.reverse 内 你可以像这样使用它,

    from django.urls import reverse
    
    @receiver(user_login_failed)
    def user_login_failed_callback(sender, credentials,  **kwargs):
    
        username = credentials['username']
        user = User.objects.get(username=username)
        profile = user.get_profile()
    
        if profile.failed_login_count <= 9:
            profile.failed_login_count = profile.failed_login_count+1
            profile.last_login_attempt_date_time = timezone.now()
            profile.save()
        else:
            return reverse('/login_lock/')
    

    我建议使用命名空间而不是提供核心 URL。 您可以编写您的网址,例如,

    url(r'^login/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login.html'}, name='account_login'),
    url(r'^login_lock/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login_lock.html'}, name='login_lock'),
    

    【讨论】:

      猜你喜欢
      • 2021-05-26
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 2012-11-25
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多