如何在Django 2.1中实现分页器?

时间:2018-08-24 08:09:59

标签: django

我的项目的产品页面需要添加分页器。我确实按照Django文档进行操作,但是出现以下错误:

object of type 'InsuranceProducts' has no len()

这是我的views.py:

def farmer_types(request, type_id):

    product_areas = InsuranceProducts.objects.filter(product_type="Фермерам")
    product_types = get_object_or_404(InsuranceProducts, id=type_id)

    paginator = Paginator(product_types, 6)
    page = request.GET.get('page')
    types = paginator.get_page(page)

    context = {'product_types': product_types,
               'product_areas': product_areas,
               'types': types}
    return render(request, 'insurance_products/farmer/farmer_types.html', context)

这是我的模型。py:

class InsuranceProducts(models.Model):
    product_area = models.CharField(max_length=100)
    product_description = models.TextField()
    product_type = models.CharField(max_length=50)

    def __str__(self):
        return "{}-{}".format(self.product_area, self.product_type)


class ProductType(models.Model):
    product_area = models.ForeignKey(InsuranceProducts, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    description = models.TextField()
    body = HTMLField('Content')

    def __str__(self):
        return "{} - {}".format(self.product_area, self.title)

这是模板中的代码:

{% for product in types.producttype_set.all %}
  <div class="btmspace-80">
    <h3>{{ product.title|upper }}</h3>
    <img class="imgr borderedbox inspace-5" src="{% static 'img/imgr.gif' %}" alt="">
    <p>
        {{ product.description|upper }}
    </p>

    <p>
        Подробно вы можете узнать о новости <a href="{% url 'main:farmer_product' product_types.id product.id %}">здесь</a></a>
    </p>
  </div>
{% endfor %}

<div class="pagination">
  <span class="step-links">
    {% if types.has_previous %}
        <a href="?page=1">&laquo; first</a>
        <a href="?page={{ types.previous_page_number }}">previous</a>
    {% endif %}

    <span class="current">
        Page {{ types.number }} of {{ types.paginator.num_pages }}.
    </span>

    {% if types.has_next %}
        <a href="?page={{ types.next_page_number }}">next</a>
            <a href="?page={{ types.paginator.num_pages }}">last &raquo;</a>
    {% endif %}
   </span>
  </div>

  <!-- ################################################################################################ -->
</div>

我按照文档中的说明进行了所有操作。

1 个答案:

答案 0 :(得分:0)

如果使用product_types仅返回一个对象,为什么get_object_or_404是复数?

您的分页正确,但查询错误。如果将paginator = Paginator(product_types, 6)更改为paginator = Paginator(product_areas, 6),您会发现它工作得很好。

您应该阅读documentation,了解如何进行查询,并了解模型之间的关系。