2009-10-22 44 views
3

我正在玩django,并建立了一个小应用程序,用户可以通过url http:///localhost:8000/username/info/访问他们的信息。我想通过http:///localhost:8000/username/info/edit/添加编辑该信息的功能,但也希望确保当前登录的用户(使用django.contrib.auth)只能访问他的信息。我做到了这一点通过以下操作视图(在视图ARGS用户名是URL中捕获):django - 限制用户只编辑他们自己的信息

@login_required 
def edit_info(request, username=''): 
    if request.user.username == username: 
     # allow accessing and editing the info.. 
    else: 
     # redirect to some error page 

所以,很显然,我不希望用户“约翰尼”编辑的信息属于用户'jimmy'只需将他的浏览器指向/ jimmy/info/edit /。以上的作品,但我担心的是,在安全方面,我错过了一些东西。这是否正确? 谢谢。

+2

我会在你的'else'块,错误代码403响应的粉丝。 – 2009-10-22 10:11:59

回答

2

这应该适用于您正在尝试做的事情而没有任何明显的安全风险。

但是,为什么显示他们的用户名,如果没有其他人可以看到至少一个配置文件或在这个位置的东西虽然?这不会更像是一个'帐户'页面吗?然后,您不会检查URL中的用户名,唯一可以访问的网址就是帐户,它只会加载登录用户的信息。

+0

我明白了。我想让用户查看其他人的信息,但编辑应该只限于个人数据,当然。 – sa125 2009-10-22 09:51:55

0

通过@login_required并解析request.user,他们永远不会终止在他人的个人资料中。我的资料查看

@login_required 
def user_profile(request): 
    """ User profile page """ 
    u = User.objects.get(pk=request.user.pk) 

    return render_to_response('myapp/user_profile.html', { 
           'user': request.user, 
           }) 

然后在模板简单地使用这样的东西:

Welcome <b>{{ user.first_name }} {{ user.last_name }}</b> 
相关问题