django:将每个用户的数据分开 [英] django: keep each users data separate

查看:77
本文介绍了django:将每个用户的数据分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试如何/最好,最安全的方法来在我需要编写的django站点中将用户数据分开.

I am trying to workout how / the best, most secure way to keep a user's data separate within a django site that I need to write.

这是我需要做的一个例子...

Here is an example of what I need to do...

示例应用程序ToDoList

example app ToDoList

使用django contrib.auth来管理用户/密码等,我将拥有以下用户

Using django contrib.auth to manage users / passwords etc, I will have the following users

汤姆吉姆李

会有一个待办事项模型(在我的真实应用中会有其他模型)

There will be a ToDo model (in my real app there will be additional models)

class ToDo(models.Model):
    user = models.ForeignKey(User)
    description = models.CharField(max_length=20)
    details = models.CharField(max_length=50)
    created = models.DateTimeField('created on')

我遇到的问题-可能是在考虑以下问题:如何将其锁定,以便汤姆只能看到汤姆的待办事项列表,李只能看到他的待办事项列表,依此类推...

The issue that I am having - and may be over thinking this: How would this be locked down so tom can only see Tom's todo list, lee can only see his todo list and so on...

我看过几篇文章,指出您可以在每个查询中使用过滤器,也可以使用url,因此url看起来像www.domain.com/username/todo

I have seen a few posts stating that you could use filter in every query, or use urls, so the url could look like www.domain.com/username/todo

但是无论哪种方式,我都不确定这是否是正确的方式/最佳方式,还是在阻止用户看到彼此的数据方面更加疯狂

But either way I am not sure if this is the right way / best way, or bonkers in terms of stopping users seeing each others data

欢呼

理查德

推荐答案

一种方法是按当前登录的用户过滤ToDo项目:

One approach is to filter the ToDo items by the currently logged in user:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from your_app.models import ToDo

@login_required
def todos_for_user(request):
    todos = ToDo.objects.filter(user=request.user)
    return render(request, 'todos/index.html', {'todos' : todos})

这仅锁定已验证用户的视图,并由登录用户根据请求进行过滤,即使已登录,另一个用户也无法访问其他用户的ToDo记录.希望对您有帮助.

This locks down the view for authenticated users only, and filtering by the logged in user from the request, another user, even if logged in, can't access another user's ToDo records. Hope that helps you out.

这篇关于django:将每个用户的数据分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆