2012-07-24 80 views
3

我正在創建一個學校記錄webapp。我希望工作人員能夠通過訪問正確的URL來查看任何學生的用戶數據頁面,但不允許學生訪問彼此的頁面。不過,我爲這兩個網址使用了相同的查看功能。Django:根據引用地址限制對視圖的訪問

我有一個工作@user_is_staff修飾器基於user.staff對象的存在。瞳孔用戶有一個user.pupil對象。由於沒有用戶可以同時擁有.staff.pupil條目,因此這些是自然分散的。

urls.py

(r'^home/(?P<subject>[^/]+)/$', 'myproject.myapp.views.display_pupil') 
(r'^admin/user/(?P<user>\d+)/(+P<subject>[^/]+)/$', 'myproject.myapp.views.display_pupil') 

views.py

@login_required 
def display_pupil(request, subject, pupil=None): 
    if pupil: 
     try: 
      thepupil = get_object_or_404(Pupil, id = pupil, cohort__school = request.user.staff.school) 
     except Staff.DoesNotExist: 
      return HttpResponseForbidden() 
    else: 
     thepupil = request.user.pupil 
    thesubject = get_object_or_404(Subject, shortname = subject) 
    # do lots more stuff here 
    return render_to_response('pupilpage.html', locals(), context_instance=RequestContext(request)) 

這樣做,這樣的作品,但感覺很哈克,特別是我的 '@user_is_staff' 裝飾有一個更優雅的重定向到一個登錄頁面比這裏的403錯誤。

我不知道的是如何將@user_is_staff修飾器應用到該功能,只有當它已經與pupil kwarg訪問。實際視圖函數中有更多的代碼,所以我不想編寫第二個代碼,因爲這將是嚴重的非DRY。

回答

2

聽起來就像你想要兩個單獨的視圖 - 一個用於特定的學生,一個用於當前用戶 - 和一個包含共享邏輯的實用程序函數。

@login_required: 
def display_current_pupil(request, subject): 
    thepupil = request.user.pupil 
    return display_pupil_info(request, subject, thepupil) 

@user_is_staff 
def display_pupil(request, subject, pupil): 
    thepupil = get_object_or_404(Pupil, id=pupil, cohort__school=request.user.staff.school) 
    return display_pupil_info(request, subject, thepupil) 

def display_pupil_info(request, subject, thepupil): 
    thesubject = get_object_or_404(Subject, shortname=subject) 
    # do lots more stuff here 
    return render_to_response('pupilpage.html', locals(), context_instance=RequestContext(request)) 
+0

非常整齊地做它,謝謝 – nimasmi 2012-07-24 21:47:22