Django: Accessing Logged in User when specifying Generic View in urlpatterns

倖福魔咒の 提交于 2019-12-23 16:12:54

问题


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:


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


来源:https://stackoverflow.com/questions/9279753/django-accessing-logged-in-user-when-specifying-generic-view-in-urlpatterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!