Reputation: 1596
I have a model that looks like this:
from django.db import models
from django.contrib.auth.models import User
class Application(models.Model):
STATUS_CHOICES = (
(u'IP',u'In Progress'),
(u'C',u'Completed'))
status = models.CharField(max_length=2 ,choices=STATUS_CHOICES, default='IP')
title = models.CharField(max_length = 512)
description = models.CharField(max_length = 5120)
principle_investigator = models.ForeignKey(User, related_name='pi')
And I want to use a generic ListView that lists the applications for the currently logged in user, that have the status of 'IP'
I started writting my urlpattern and realised that I would need to reference the currently logged in user in my queryset property....is this possible or will I need to bite the bullet and write a standard custom view that handles the model query?
Here is how far I got for illustration:
url(r'^application/pending/$', ListView.as_view(
queryset=Application.objects.filter(status='IP'))),
Upvotes: 3
Views: 3261
Reputation: 308909
You can't filter on the user in your urls.py
, because you don't know the user when the urls are loaded.
Instead, subclass ListView
and override the get_queryset
method to filter on the logged in user.
class PendingApplicationView(ListView):
def get_queryset(self):
return Application.objects.filter(status='IP', principle_investigator=self.request.user)
# url pattern
url(r'^application/pending/$', PendingApplicationView.as_view()),
Upvotes: 12