3

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'))),

1 Answer 1

12

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()),
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that's a great, simple solution! Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.