开发者

django - limit users to edit only their own information

开发者 https://www.devze.com 2022-12-09 17:27 出处:网络
I\'m playing around with django and built a small app where a user can access their info via the url http:///localhost:8000/username/info/ . I want to add the ability to edit that info through http://

I'm playing around with django and built a small app where a user can access their info via the url http:///localhost:8000/username/info/ . I want to add the ability to edit that info through http:///localhost:8000/username/info/edit/, but also want to make sure the currently logged in user (using django.contrib.auth) can access only his information. I accomplished this by doing the following in the view (username in the view args is captured from the url):

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

So, obviously, I don't want user 'johnny' to edit the info belonging to user 'jimmy' by simply pointing his browser to /jimmy/info/edit/. The above works, but my concern is that I'm missing something here as far as security goes. Is this the ri开发者_JAVA百科ght way to go about this? Thanks.


This should work for what you are trying to do without any glaring security risks.

But, why show their username if no one else can see at least a profile or something at this location though? Wouldn't this be more like a 'account' page? Then you wouldn't check against the username in the url, the only url you could go to would be account, and it would just load the logged in user's info.


With the @login_required and parsing the request.user they will never end up on anothers profile. My profile view

@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,
                                })

Then in the template simply use stuff like:

Welcome <b>{{ user.first_name }} {{ user.last_name }}</b>
0

精彩评论

暂无评论...
验证码 换一张
取 消