django中的@login_required

转:http://www.cnblogs.com/ccorz/p/Django-zhong-loginrequired-yong-fa-jian-jie.html

1、网站开发时的登录需求:

===用户登录系统才可以访问某些页面

===如果用户没有登录而直接访问就会跳转到登录界面,而不能访问其他页面

===用户在跳转的登录界面中完成登录后,自动访问跳转到之前访问的地址

实现上面的需求可以使用下面的方法

?===使用django自带的装饰器@login_required

?===在相应的view方法的前面添加@login_required

?==并在settings.py中配置LOGIN_URL参数

?===修改login.html中的表单action参数

views.py设置:

from django.contrib.auth.decorators import login_required

from djangp.shortcuts import render_to_response

from django.http import HttpResponse

@login_required

def myview(request):

  return render_to_response("index.html")

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

setting.py设置

LOGIN_URL="/accounts/login/"#这个路径需要根据你网站的实际登录地址来设置

urls.py设置:

from django.conf.urls import url

from django.contrib import admin

from app01 import views

urlpatterns=[

  url(r"^admin/",admin.site.urls),

  url(r"^accounts/login/",views.acc_login)

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

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

这样的话,如果未登录,程序会默认跳转到"templates/registration/login.html"这个模板

如果想换个路径,另一种方式:那就再加个template_name参数,如下:

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

这样程序就会跳转到template/myapp/login.html

login.html设置

原文地址:https://www.cnblogs.com/yingqml/p/6594856.html