Python 限制对Django通用视图的访问

Python 限制对Django通用视图的访问,python,django,django-generic-views,Python,Django,Django Generic Views,我正在创建一个Django应用程序,用户可以在其中创建帐户,然后向每个帐户添加交易。它是一个允许用户跟踪投资收益的网站的一部分。我正在使用泛型类视图来实现这一点 用户将交易添加到特定帐户(代码未显示),然后他们必须能够使用site/transactions/2/查看该特定帐户的交易,其中2是帐户ID 问题是任何登录的用户都可以更改url以获取其他用户帐户的事务。我可以通过检查给定的帐户id是否属于用户来轻松解决这个问题,但我认为一定有更好的方法。有没有更好的方法来实现这一点?也许我不应该对其进行

我正在创建一个Django应用程序,用户可以在其中创建帐户,然后向每个帐户添加交易。它是一个允许用户跟踪投资收益的网站的一部分。我正在使用泛型类视图来实现这一点

用户将交易添加到特定帐户(代码未显示),然后他们必须能够使用site/transactions/2/查看该特定帐户的交易,其中2是帐户ID

问题是任何登录的用户都可以更改url以获取其他用户帐户的事务。我可以通过检查给定的帐户id是否属于用户来轻松解决这个问题,但我认为一定有更好的方法。有没有更好的方法来实现这一点?也许我不应该对其进行URL编码吗?我不太喜欢用户在DB中看到他们的帐户ID

另外,在稍后的阶段,我想让用户能够在单个列表中查看他们帐户的一些交易。例如,显示其5个帐户中3个帐户的所有交易记录。那么这个URL方法也不会真正起作用。我还有什么其他选择

在models.py中,我有:

class Account(models.Model):
    name = models.CharField(max_length=40, unique=True, db_index=True)
    user = models.ForeignKey(User)

class Transaction(models.Model):
    value = models.DecimalField(max_digits=15, decimal_places=2)
    date = models.DateField('transaction date')
    account = models.ForeignKey(Account)
在URL.py中:

url(r'^(?P<account_id>\d+)/$', views.IndexView.as_view(), name='index'),  
然后我有一个
事务列表
模板


谢谢

如果希望出现404错误,您可以使用helper函数
获取\u对象\u或\u 404()
首先获取account对象

像这样:

def get_queryset(self):
    account_id = self.kwargs['account_id']

    # raise 404 if no account is found for the current user
    account = get_object_or_404(Account, pk=account_id, user=self.request.user)

    queryset = Transaction.objects.filter(account=account)
    return queryset
对于您提到的第二件事,您可以创建一个新视图,或者只检查
'account\u id'
是否在url中,然后重用当前视图。无论哪种方式,您都需要一个新的url

URL.py:

url(r'^(?P<account_id>\d+)/$', views.IndexView.as_view(), name='index'),
url(r'^$', views.IndexView.as_view(), name='index'), 

非常感谢!我认为应该这样做。我对django很陌生,所以我想知道,像这个例子一样在URL中有数据库字段ID是一种好的做法吗?是的,这很标准。更好、更友好的方法可能是使用鼻涕虫。但我不认为使用身份证是不好的做法。
url(r'^(?P<account_id>\d+)/$', views.IndexView.as_view(), name='index'),
url(r'^$', views.IndexView.as_view(), name='index'), 
def get_queryset(self):
    # account_id will be None if the second url was the one that matched.
    account_id = self.kwargs.get('account_id', None) 

    if account_id:
        # raise 404 if no account is found for the current user
        account = get_object_or_404(Account, pk=account_id, user=self.request.user)

        queryset = Transaction.objects.filter(account=account)
    else:
        # we're going to show all transactions for the user, rather than a specific account
        queryset = Transaction.objects.filter(account__user=self.request.user)

    return queryset