简体   繁体   English

django-重用登录模板

[英]django - reusing a login template

I'm just curious if I'm doing this right. 我很好奇我是否做对了。

I'm coding a private section of a website and wrote a login view which throws up a login window. 我正在编码网站的私有部分,并写了一个登录视图,该视图引发了一个登录窗口。 I want to reuse this view for several urls which all go to a different views once access is granted. 我想将此视图重用于几个URL,一旦授予访问权限,所有这些URL都将转到不同的视图。 It doesn't appear that you can pass arguments in the statements in urls.py, so I gave the login view an extra argument redirect 似乎您无法在urls.py中的语句中传递参数,因此我为登录视图提供了额外的参数redirect

def login(request, redirect):
    code to read the login form and parse the POST input
    if POST and loginSuccessful:
        return redirect(request)
    else:
        return render_to_response('login.html', context)

...and made specific urls each activate a different one-liner such as login_to_admin which simply returns the login view with a redirect argument. ...并使特定的网址分别激活不同的一类login_to_admin ,例如login_to_admin ,它仅返回带有重定向参数的登录视图。

def login_to_admin(request):
    return login(request, admin)

def login_to_beta(beta):
    return login(request, beta)

Everything works, I'm just wondering if this is the proper way to do this. 一切正常,我只是想知道这是否是执行此操作的正确方法。

It doesn't appear that you can pass arguments in the statements in urls.py 看来您无法在urls.py中的语句中传递参数

You can, actually. 您可以,实际上。

The third item in the url conf can be a dictionary of kwargs which will be passed your view function. url conf中的第三项可以是kwargs的字典,将通过您的view函数。

(r'^my_url/$', 'login', {'redirect': admin}),
(r'^my_other_url/$', 'login', {'redirect': beta}),

You could use the login required decorator , as this'll make your code easier to maintain. 您可以使用需要登录的装饰器 ,因为这将使您的代码更易于维护。

There's nothing wrong as such with your approach, but it's less generic and thus more prone to unexpected behaviour and oversights. 您的方法没有什么错,但它的通用性较低,因此更容易发生意料之外的行为和疏忽。

You can also add extra field to login form eg next, which will contain correct url. 您还可以在登录表单中添加额外的字段,例如next,其中将包含正确的url。 And after validating form and logging in redirect user 并在验证表单并登录重定向用户之后

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM