MarkoZg
MarkoZg

Reputation: 373

Get User id from class based view

I have a class based view:

class PostListViewMojeReported(ListView):

    def get_username(self, **kwargs):
        login_username = request.user.username
        context = {'login_username': login_username}
        return context

    model = Post
    template_name = 'blog/filter_moje_reported.html'
    context_object_name = 'posts'
    queryset = Post.objects.filter(Q(status='Otvorena') & (Q(res_person_1_username=username) | Q(res_person_2_username=username)))
    ordering = ['-date_posted']
    paginate_by = 30

I don't know how to get username from the current logged in user to use as a filter in my queryset. I need to compare the current logged in user with 'res_person_1_username' and 'res_person_2_username'.

Upvotes: 1

Views: 669

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

You can obtain the requerst object with self.request, so:

class PostListViewMojeReported(ListView):
    model = Post
    template_name = 'blog/filter_moje_reported.html'
    context_object_name = 'posts'
    paginate_by = 30

    def get_username(self, **kwargs):
        login_username = self.request.user.username
        context = {'login_username': login_username}
        return context

    def get_queryset(self, *args, **kwargs):
        username = self.request.user.username
        return super().get_queryset(*args, **kwargs).filter(
           Q(res_person_1_username=username) | Q(res_person_2_username=username),
           status='Otvorena'
        ).order_by('-date_posted')

I would however advise to work with two ForeignKeys to the user model, and not store the username, since it is possible that later the user removes their account, and another person then creates an account with that username.

Upvotes: 1

Related Questions