2011-05-20 99 views
0

所以我有這個工作選擇窗體,應該允許用戶:Django窗體和篩選

1)選擇一個過濾器一組單選按鈕。這讓用戶可以選擇他想用哪種方法過濾列表。 (這將使用'filterBy'查詢字符串執行GET 2)允許用戶通過來自作爲#1結果的組合框的對象來過濾列表。這種形式執行與設置爲filterBy對象

這裏的PK的「過濾器」一個POST是代碼我有:

selectForm = JobSelectForm() 
filterByForm = FilterByForm() 
filterForm = FilterForm() 

if request.method == 'POST': 
    #this works just fine 
    if 'job' in request.POST: 
     return HttpResponseRedirect("/portal/jobs/%s/"%(request.POST['job'])) 

    if 'filter' in request.POST: 
     filterForm = FilterForm(initial = {'filter': request.POST['filter']}) 

     ###### The Problem is below here 
     ###### I cant get the 'filterBy' query string 
     ###### because this is a POST and not a GET 
     ###### Is there a better way to write this filtering? 

     if request.GET['filterby'] == 'G': 
      obj = Group.objects.get(pk=request.POST['filter']) 
      selectForm.fields['job'].queryset = Job.objects.filter(group=obj).order_by('name') 
     elif request.GET['filterby'] == 'H': 
      obj = Host.objects.get(pk=request.POST['filter']) 
      selectForm.fields['job'].queryset = Job.objects.filter(host=obj).order_by('name') 
     elif request.GET['filterby'] == 'L': 
      obj = Location.objects.get(pk=request.POST['filter']) 
      selectForm.fields['job'].queryset = Job.objects.filter(colo=obj).order_by('name') 

###### All of this works fine too 
elif request.method == 'GET': 
    if request.GET.has_key('filterby'): 
     if request.GET['filterby']: 
      filterByForm = FilterByForm(initial = {'filterby': request.GET['filterby']}) 
      if request.GET['filterby'] == 'G': 
       filterForm.fields['filter'].queryset = Group.objects.all().order_by('name') 
      elif request.GET['filterby'] == 'H': 
       filterForm.fields['filter'].queryset = Host.objects.all().order_by('name') 
      elif request.GET['filterby'] == 'L': 
       filterForm.fields['filter'].queryset = Location.objects.all().order_by('name') 
+0

爲什麼分開GET和POST?爲什麼不使用GET並使其更簡單? – 2011-05-20 14:56:47

回答

0

你應該把你的問題的代碼形式的overrided __init__方法。

1

使用request.REQUEST(參見:Django Request and Response Objects)。它擁有request.POSTrequest.GET的值。

此外,在Python中使用字典時,應始終驗證您嘗試訪問的密鑰是否存在。這可以通過以下兩種方式之一進行:

1)在詞典

if request.GET.has_key('filterby') and request.GET['filterby'] == 'G': 
    obj = Group.objects.get(pk=request.POST['filter']) 
    selectForm.fields['job'].queryset = Job.objects.filter(group=obj).order_by('name') 

2)使用字典的get方法明確地測試關鍵

if request.GET.get('filterby') == 'G': 
    obj = Group.objects.get(pk=request.POST['filter']) 
    selectForm.fields['job'].queryset = Job.objects.filter(group=obj).order_by('name') 

隨着dict.get你也可以通過一個默認值:

if request.GET.get('filterby', valueIfKeyDoesntExist) == 'G': 
    obj = Group.objects.get(pk=request.POST['filter']) 
    selectForm.fields['job'].queryset = Job.objects.filter(group=obj).order_by('name')