2011-12-05 77 views
4

我使用的是Django的分頁程序分頁的模板,我希望有多個可用GET參數,如: 頁面= 1 sort_by =價格Django的 - 使用多個GET參數

然而,在我的模板標籤我有:

Showing items sorted by {{ SORT_PARAM }}. 
Showing {{ ITEMS_PER_PAGE }} items per page. 

{% if has_prev %} 
<a href="?page={{ prev_page }}">Previous</a> | 
{% endif %} 

但是,這不會保留其他GET變量。我的意思是,如果我查看

page/?page=1&sort_by=price 

和我點擊上面的模板片段的鏈接,我會去

page=2 

,而不是

page=2&sort_by=price 

我意思是說,一個href不保留其他的GET參數。

一個解決方案是我可以輸入所有的A HREF可能GET參數,如

<a href="?page={{ prev_page }}&items_per_page={{ ITEMS_PER_PAGE }}&sort_param={{ SORT_PARAM }}">Previous</a> 

,但是這將不再是可擴展的更多的參數我想添加到我的瀏覽。我猜應該有一種自動獲取所有GET參數的方法,然後再傳遞這些參數?

+1

嘗試創建特殊的template_tag:ie。 {%pager_url page = page_no items_per_page = ITEMS_PER_PAGE sort_param = SORT_PARAM%}(順便說一句,如果你從設置中獲取一些參數(即ITEMS_PER_PAGE),你不需要明確地傳遞它) – yedpodtrzitko

+0

謝謝。這可能值得一試 –

回答

2

您可以創建一個'參數字符串'。讓我們supose,在你的代碼中有:

my_view(request, page, options): 
    sort_choices = {P:'price',N:'name', ...} 
    n_item_choices = {'S':5, 'L':50, 'XL':100) 
    ascending_descending_choices = {'A':'', 'D':'-'} 
    ... 

那麼你可以concatenat選項:

options='P-S-D' #order by price, 5 items per page, descending order 

編碼opions爲:

<a href="?page={{ prev_page }}&options={{ options }}">Previous</a> 

然後,在urls.py拍攝選項和在視圖中:

my_view(request, page, options): 
    ... #choides .... 
    try: 
     optionsArray = options.split('-') 
     sort_by = sort_choices[ optionsArray[0] ] 
     n_ites_page = n_item_choices[ optionsArray[1] ] 
     asc_or_desc = ascending_descending_choices[ optionsArray[2] ] 
     ... 
    except: 
     somebody is playing .... 

with this方法可以自由添加更多分頁選項,而無需修改urls.py,您只需在字符串選項末尾添加選項即可。這有好處,但也有一些危險:我希望你能識別風險。

0

Django的分頁 - 保留GET params爲簡單。

首頁複印的GET PARAMS一個變量(鑑於):

GET_params = request.GET.copy() 

,並通過語境詞典發送到模板:你需要做

return render_to_response(template, 
         {'request': request, 'contact': contact, 'GET_params':GET_params}, context_instance=RequestContext(request)) 

第二件事是使用它在模板中的url調用(href)中指定它 - 一個示例(擴展基本分頁html以處理額外參數條件):

{% if contacts.has_next %} 
    {% if GET_params %} 
     <a href="?{{GET_params.urlencode}}&amp;page={{ contacts.next_page_number }}">next</a> 
    {% else %} 
     <a href="?page={{ contacts.next_page_number }}">next</a> 
    {% endif %} 
{% endif %} 

Source - 發佈相同的答案。