How to use "Objects.filter" by selecting only the logged in user in the application?

Asked

Viewed 18 times

0

I am using Django authentication and in HTML templates works very well when I use for example:

{% if user.is_anonymous %}
...
{% else %}
...
{% endif %}

I would like to use this same "user", which refers to the logged in user, to select when loading a view.

Like I’m trying to do:

class IndexView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['tabelas'] = Tabela.objects.filter(**usuario=user.id**)
        return context

I would like to get id of the logged-in user who has a Foreignkey with Table and thus select only the data that matter. But error occurs:

NameError at /
name 'user' is not defined
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.2.4
Exception Type: NameError
Exception Value:    
name 'user' is not defined

Does anyone know how I use the logged-in user in this snippet ?

1 answer

1

Digging a little and filling the code with print(), I discovered a way to do, follows:

class IndexView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        req_user_pk = context["view"].request.user.pk
        context['tabelas'] = Tabela.objects.filter(usuario=req_user_pk)
        #context['tabelas'] = Tabela.objects.order_by('id')
        return context

If anyone has a better suggestion, I’m all ears :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.