2016-05-21 27 views
0

我工作我的第一個Django應用程序,更特別是分頁。在我繼續添加分頁之前:Django如何在打網址時獲取物品的第一頁?

http://localhost:8000/posts 

我將顯示所有項目。

但現在我添加了分頁,一切工作正常。我每頁只顯示2個項目,並且我有5個項目。一切工作正常,當我打的頁面:

http://localhost:8000/posts?page=1 
http://localhost:8000/posts?page=2 
http://localhost:8000/posts?page=3 

但是,當我打:

http://localhost:8000/posts 

我有以下錯誤:

That page number is not an integer 

這是我的view.py:

def posts(request): 
    all_posts = Post.objects.order_by('published_date') 
    paginator = Paginator(all_posts, 2) 
    page = request.GET.get("page") 
    try: 
     posts = paginator.page(page) 
    except PageNotAnInteger: 
     posts = paginator.page(page) 
    except EmptyPage: 
     posts = paginator.page(paginator.num_pages) 

    context = { 
     'posts': posts, 
    } 
    return render(request, 'my_blog/posts.html', context) 

我該如何得到這個問題擊中時:具有http://localhost:8000/posts第一頁顯示

回答

4

的問題是在PageNotAnInteger異常處理,應該是1而不是page

try: 
    posts = paginator.page(page) 
except PageNotAnInteger: 
    posts = paginator.page(1) 
except EmptyPage: 
    posts = paginator.page(paginator.num_pages) 
1

嘗試更換:

except PageNotAnInteger: 
     posts = paginator.page(page) 

通過

except PageNotAnInteger: 
     posts = paginator.page(1) 

特別同意