1

I need an elegant way of disabling or authorizing related field traversal in Django templates.

Imagine following setup for models.py:

class Person(models.Model):
    pass

class Secret(models.Model):
    owner = models.ForeignKey(Person, related_name="secrets")

Now imagine this simple view that gives the template QuerySet of all Person instances in the system just so the template could put them in a list.

def show_people(request):
    render_to_response("people.html", {people=Person.objects.all()})

Now my problem is that I would not provide the templates myself in this imaginary system and I don't fully trust those who make the templates. The show_people view gives the people.html template the secrets of the Person instances through the related_name="secrets". This example is quite silly but in reality I have model structures where template providers could access all kind of vulnerable data through related managers.

The obvious solution would be not to give models to templates but to convert them in to some more secure data objects. But that would be pain in my case because the system is already quite big and it's up and running.

I think a cool solution to this would be somehow preventing related field traversal in templates. Another solution would be to have such custom related managers that could have access to the request object and filter the initial query set according to the request.user.

4

1 回答 1

1

一个可能的解决方案可能是将自定义 model.Manager 与您的相关模型一起使用。设置use_for_related_fields = True强制 Django 使用它而不是普通的管理器。修改管理器以根据需要过滤数据。

也看看这个:

Django:使用管理器进行相关对象访问(use_for_related_fields 文档)

stackoverflow: use_for_related_fields howto,这里有很好的解释。

于 2013-01-11T09:49:43.920 回答