Ernst van der Heijden
Ernst van der Heijden

Reputation: 13

Django 1.10 query a table using username from logged in user

I'm new to Django, creating a site where I want logged in users to see there own data provided in a table. This table has a field username.

I want the users to see there own data in a listview. I can't figure out how I can query, using the username from User. To give you an idea of what I am doing, this is what I have as code: (I tried multiple other ways, but I can't get a string with the User login Name.

from django.contrib.auth.models import User        
from django.views.generic import ListView      

username = User.username

class RoosterListView(LoginRequiredMixin, ListView):
    queryset = Roosters.objects.filter(startvc__range=(DatumStart, DatumEind),username=CurrentUser).order_by("startvc")[:35]

Thanks so much in advance.

Upvotes: 0

Views: 350

Answers (2)

Alasdair
Alasdair

Reputation: 308829

Remove the username = User.username line - User is the model class, not the current user instance.

You can access the current user if you set queryset, as this is loaded when the module is imported, not when the request is made. If you override the get_queryset method, you can access the user with self.request.user.

class RoosterListView(LoginRequiredMixin, ListView):
    def get_queryset(self):
        return Roosters.objects.filter(startvc__range=(DatumStart, DatumEind), username=self.request.user.username).order_by("startvc")[:35]

Upvotes: 1

Bobby
Bobby

Reputation: 1571

you can get the username of your logged in user by

username = request.user

you can simply pass your request parameter around to get all the information of the current session and do whatever query you wanna do.

Upvotes: 0

Related Questions