2012-02-14 1 views
3

で汎用ビューを指定するときにログインしているユーザー探査する、私はこのようになりますモデルがあります:ジャンゴ:urlpatterns

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

をそして、私は現在ログインしているユーザー向けのアプリケーションを一覧表示し、一般的なリストビューを使用したいです、 'IP'のステータスを持っています

私は私のurlパターンを書き始めて、私がquerysetプロパティで現在ログインしているユーザーを参照する必要があることに気づきました....これは可能ですか、モデルクエリを処理する標準カスタムビューを記述しますか?

url(r'^application/pending/$', ListView.as_view(
     queryset=Application.objects.filter(status='IP'))), 

答えて

14

URLがロードされたときに、ユーザーを知らないので、あなたは、あなたのurls.pyにユーザーにフィルタを適用することはできません。ここで

は、私が説明のために得た方法遠いです。

代わりにListViewをサブクラス化し、get_querysetメソッドをオーバーライドして、ログインしているユーザーをフィルタします。

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

すごく簡単な解決策です。乾杯! – Ctrlspc