Django身份验证和Ajax - 需要登录的URL [英] Django authentication and Ajax - URLs that require login
问题描述
我想将一些 Ajax 添加到我的Django代码网站。
I want to add some Ajax-niceness to my Django-coded website.
在我的Django代码中,我使用 @login_required
装饰器从 django.contrib。 auth.decorators
标记哪个视图需要身份验证。未通过身份验证的用户点击它的默认行为是将其重定向到登录页面,然后传递目标页面。
In my Django code, I use the @login_required
decorator from django.contrib.auth.decorators
to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass the target page.
我在一些网站上看到的真正喜欢的是,当用户点击导致限于只登录用户的地方的链接,而不是被重定向到登录页面,他/她会通过JavaScript弹出窗口,要求他/她登录或注册。没有重定向部分,所以如果他/她决定他/她真的不喜欢网站足以浪费时间注册,则不需要用户使用返回键。
What I saw on some sites, and really liked, is that when user clicks a link leading to a place restricted to logged-only users, instead of getting redirected to a login page, he/she gets a popup window (via JavaScript) asking him/her to log in or register. There's no redirection part, so no need for a user to use the "back" key if he/she decides he/she really doesn't like the website enough to waste the time registering.
所以,这个问题是:你如何管理自动将某些链接标记为受限制的任务,因此JavaScript可以处理他们的 onclick
事件并显示请登录弹出窗口
So, the qestion is: how would you manage the task of automatically marking some links as "restricted" so JavaScript can handle their onclick
event and display a "please log in" popup?
推荐答案
我面临着同样的问题,像你一样,我想要一个简单的装饰器来围绕Django ajax视图为了以与我有其他意见相同的方式处理身份验证。对我来说似乎有希望的一种方法是使用这样一个装饰器与JavaScript一起在响应中寻找一定的值。
I am facing the same issue, and, like you, I would like a simple decorator to wrap around a Django ajax view in order to handle authentication in the same way that I have other views. One approach that seems promising to me is to use such a decorator in conjunction with JavaScript that looks for a certain value in the response.
这是第一个< s>修订者的修订草案:
Here is first revised draft of the decorator:
from functools import wraps
def ajax_login_required(view_func):
@wraps(view_func)
def wrapper(request, *args, **kwargs):
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
json = simplejson.dumps({ 'not_authenticated': True })
return HttpResponse(json, mimetype='application/json')
return wrapper
以下是视图:
@ajax_login_required
def ajax_update_module(request, module_slug, action):
# Etc ...
return HttpResponse(json, mimetype='application/json')
这里是JavaScript(jQuery):
And here is the JavaScript (jQuery):
$.post('/restricted-url/', data, function(json) {
if (json.not_authenticated) {
alert('Not authorized.'); // Or something in a message DIV
return;
}
// Etc ...
});
编辑:我根据建议,我试图使用 functools.wraps
。我没有在工作代码中使用这个装饰器,所以请注意可能出现的错误。
EDIT: I've attempted to use functools.wraps
, as suggested. I have not actually used this decorator in working code, so beware of possible bugs.
这篇关于Django身份验证和Ajax - 需要登录的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!