• @login_required用法简介


    在django项目中,经常会看到下面这样的代码:

    from django.contrib.auth.decorators import login_required  
     
    @login_required  
    def my_view(request):  
        ...  

    里面有一个@login_required标签。其作用就是告诉程序,使用这个方法是要求用户登录的。

    1.如果用户还没有登录,默认会跳转到‘/accounts/login/’。这个值可以在settings文件中通过LOGIN_URL参数来设定。(后面还会自动加上你请求的url作为登录后跳转的地址,如: /accounts/login/?next=/polls/3/ 登录完成之后,会去请求/poll/3)

    2.如果用户登录了,那么该方法就可以正常执行

    如果LOGIN_URL使用默认值,那么在urls.py中还需要进行如下设置:(加入下面这句)

    (r'^accounts/login/$', 'django.contrib.auth.views.login'),

    这样的话,如果未登录,程序会默认跳转到“templates egistrationlogin.html”这个模板。

    如果想换个路径,那就再加个template_name参数,如下:

    (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),

    这样程序就会跳转到templatesmyapplogin.html”

    除了login这个有用的方法之外,auth模块还提供很多有用的方法,比如:

    logout(request[, next_page, template_name, redirect_field_name])

    password_change(request[, template_name, post_change_redirect, password_change_form])

    password_change_done(request[, template_name])

    password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form,token_generator, post_reset_redirect, from_email])

    password_reset_done(request[, template_name])

     

    用法示例:

    (r'^change_passwd/$', 'django.contrib.auth.views.password_change', {
        'template_name': 'change_passwd.html',
        'post_change_redirect': '/',
    }),
    (r'^reset_passwd/$', 'django.contrib.auth.views.password_reset', {
        'template_name': 'reset_passwd.html',
        'email_template_name': 'reset_passwd_email.html',
        'post_reset_redirect': '/reset_done/',
        'from_email': 'noreply@jihua.in',
    }),
    (r'^reset_confirm/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 
        'django.contrib.auth.views.password_reset_confirm', {
            'template_name': 'reset_confirm.html',
            'post_reset_redirect': '/signin/',
        }
    ),
    (r'^reset_done/$', 'django.views.generic.simple.direct_to_template', {'template': 'message.html', 'extra_context': {
        'msg': _(u'我们已将一封包含恢复密码步骤的邮件发到了您的邮箱,请查收'),
    }}),

    参考:

    Django认证模块(auth) https://docs.djangoproject.com/en/1.3/topics/auth/

    Django设置参数(setting) https://docs.djangoproject.com/en/1.3/ref/settings/#std:setting-LOGIN_URL 

     

  • 相关阅读:
    Host IP地址 is not allowed to connect to this MySQL server
    本地或远程连接mysql:Unable to connect to any of the specified MySQL hosts.
    Table xxx is marked as crashed and should be repaired
    使用Linq 做数据去重
    SharePoint2010与Reporting Services集成方案
    上下左右布局(DIV+CSS)
    .NET 内存管理—CLR的工作
    删除数据库所有用户表
    未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序
    c# 10位数int时间单位换算为datetime
  • 原文地址:https://www.cnblogs.com/robinunix/p/6958402.html
Copyright © 2020-2023  润新知