Search code examples
pythondjangodjango-templates

Is it safe to pass a user object to a Django template?


I have a user model that stores all user data, for example username, password, favorite_color, etc. I pass the data to the template like this

TemplateView
    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        user_object = User.objects.get(email=self.get_object())
        data['user_data'] = user_object
        return data

and I display non-confidential data on the page

<span class="favorite_color">{{ user_data.favorite_color }}</span>

I'm wondering if it's safe to pass a User object to a page, but not display private data through a template (for example, {{user_data.password}}) Do I need to only send the specific data I want to use on the page? Or can I still send the whole user object?

Let's just assume the developer doesn't make any mistakes.


Solution

  • I'm wondering if it's safe to pass a User object to a page, but not display private data through a template (for example, {{user_data.password}}) Do I need to only send the specific data I want to use on the page? Or can I still send the whole user object?

    Yes, it is safe, or at least if the template itself does not expose sensitive data.

    Templates are rendered at the server side. In other words, the browser does not see variables, it never sees {{ user.favorite_color }}, the template replaces that with purple, and so the browser does not know where the purple originates from: it could have been that the template itself mentions purple, or it is the result of a database query, or whatever. But it only sees purple.

    Beware that if you expose data through an API, then you need to be very careful what fields you expose. Furthermore don't allow filtering or ordering or exposing arbitrary data [django-antipatterns].