Django为django 2分页

时间:2018-05-21 12:50:43

标签: python django

我需要对Django列表使用分页,但我无法在线找到任何帮助,只有来自Django 1.3版本的旧文档

这是我的档案:

views.py

def home(request):
    all_dress = Item.objects.all().filter(dress_active=True)
    all_good_dress = Item.objects.all().filter(dress_special=True)
    current_user = request.user
    context = {
        'all_dress': all_dress,
        'current_user': current_user,
        'all_good_dress':all_good_dress,
    }
    return render(request, 'fostania/home.html', context)

模板(HTML)

 {% for item in all_dress %}

        <div class="card border-info" style="width: 18rem;">
  <a href="{% url 'dress_details' item.pk%}"><img class="card-img-top" src="{{ item.dress_image1.url }}" alt="Card image cap"></a>
  <div class="card-body" align="right">
      <h5 class="card-title"><a href="{% url 'dress_details' item.pk%}">{{ item.dress_name }}</a>
          <br>{{ item.dress_action }}<br>{{ item.dress_price }} جنيه </h5>
    <p class="card-text">المقاس : {{ item.dress_size }}
    <br>{{ item.dress_city }}<br> {{ item.created_at|date:"SHORT_DATE_FORMAT" }}
    </p>
  </div>
</div>
        <br>
        <br>
                              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

      {% endfor %}

2 个答案:

答案 0 :(得分:0)

在此链接https://docs.djangoproject.com/en/2.0/topics/pagination/

上找到了完整的文档和明确的方法

答案 1 :(得分:0)

在views.py中导入paginator

from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator

功能:

def home(request):
all_dress = Item.objects.all().filter(dress_active=True)
all_good_dress = Item.objects.all().filter(dress_special=True)
current_user = request.user
paginator  = Paginator(all_dress, 10)
page = request.GET.get('page')

try: 
    all_dress = paginator.page(page)
except PageNotAnInteger:
    all_dress = paginator.page(1)
except EmptyPage:
    all_dress = paginator.page(Paginator.num_pages)
context = {
    'all_dress': all_dress,
    'current_user': current_user,
    'all_good_dress':all_good_dress,
}
return render(request, 'fostania/home.html', context)

模板: enter image description here

如果用户登录,您可以直接在模板中访问他的信息,例如{{request.user.email}}