Ошибка разбиения на страницы при фильтрации в список по категориям ListView Django - PullRequest
0 голосов
/ 03 июня 2019

Я новичок в программировании, мой наставник только youtube, и когда я получаю ошибку, я ищу похожую ошибку в stackoverflow, но сейчас не повезло.
У меня проблема с моим кодом или, возможно, с моей логикой. У меня нет большого опыта или знаний о наборе запросов для правильной фильтрации.

Это мой urls.py

urlpatterns = [
     path('', IndexView.as_view(), name='index'),
     path('product/<int:page>', ProductListView.as_view(), name='allproducts'),
     path('<categories>/<int:page>', ProductCategoryListView.as_view(), 
     name='product_category'),
]

У меня есть ProductListView без пагинации ошибок.

class ProductListView(ListView):
    context_object_name = 'product_list'
    template_name = 'product.html'
    model = Product
    paginate_by = 16

    def get_context_data(self, *args, **kwargs):
        context = super(ProductListView, self).get_context_data(*args,**kwargs)
        context ['catlist'] = Category.objects.all()
        return context
  • когда я фильтрую по категории, разбиение на страницы не работает. Сортировать по категория работает нормально, но когда paginate_by больше, чем мой продукт, страница ошибка

Реверс для 'product_category' с аргументами '(' ', 2)' не найден. Попробован 1 шаблон (ов): ['(? P [^ /] +) / (? P [0-9] +) $'] \

class ProductCategoryListView(ListView):
    context_object_name = 'product_list'
    template_name = 'product_list.html'
    model = Product
    paginate_by = 20

    def get_queryset(self):
        self.queryset = self.model.objects.filter(category__name=self.kwargs['categories'])
        return super().get_queryset()

    def get_context_data(self, *args, **kwargs):
        context = super(ProductCategoryListView, self).get_context_data(*args,**kwargs)
        context ['catlist'] = Category.objects.all()
        return context

Это мой models.py

class Category(models.Model):
    name = models.CharField(max_length=125)
    image = models.ImageField(upload_to=upload_location)

class Product(models.Model):
    name = models.CharField(max_length=125)
    category = models.ForeignKey(Category, null=True, on_delete=models.DO_NOTHING)
    image = models.ImageField(upload_to=upload_lokasi)
    slug = models.SlugField(blank=True, editable=False)
    active = models.BooleanField(default=True)

Это мой шаблон для ProductCategoryListView

<div class="...">
            <div class="...">
                <a href="{% url 'products:allproducts' 1%}"...>
                    All Products
                </a>
                {% for cat in catlist %}
                <a href="{% url 'products:product_category' cat.name 1 %}"...>
                    {{ cat.name }}
                </a>
                {% endfor %}
                        <!-- Product List -->
        <div class="row isotope-grid">
            {% for prods in product_list %}
            <div class="...">
                <div class="...">
                    <div class="...">
                        <img src="{{ prods.image.url }}" alt="IMG-PRODUCT">
                        <a href="../{{ prods.slug }}" class="...">
                            Quick View
                        </a>
                    </div>
                    <div class="...">
                        <div class="...">
                            <a href="product-detail.html" class="...">
                                    {{ prods.name }}
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- Pagination -->
        <div class="row">
            <div class="col-md-8">
                {% if is_paginated %}
                    <nav aria-label="productPage">
                        <ul class="pagination">
                        {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="{% url 'products:product_category' category page_obj.previous_page_number %}">Previous</a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a>
                            </li>
                        {% endif %}
                        {% for page in paginator.page_range %}
                            {% if page is page_obj.number %}
                            <li class="page-item active" aria-current="page">
                                <span class="page-link" href="#">{{page}}<span class="sr-only">(current)</span></span>
                            </li>
                            {% else %}
                            <li class="page-item">
                                <a class="page-link" href="{% url 'products:product_category' category page %}">{{page}}</a>
                            </li>
                            {% endif %}
                        {% endfor %}
                        {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="{% url 'products:product_category' category page_obj.next_page_number %}">Next</a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Next</a>
                            </li>
                        {% endif %}
                        </ul>
                    </nav>
                    {% endif %}
                </div>
            </div>

Полагаю, отсюда и ошибка, потому что логика использует разные модели.

def get_context_data(self, *args, **kwargs):
            context = super(ProductCategoryListView, self).get_context_data(*args,**kwargs)
            context ['catlist'] = Category.objects.all()
            return context

мой шаблон

{% for cat in catlist %}
    <a href="{% url 'products:product_category' cat.name 1 %}"...>
        {{ cat.name }}
    </a>
{% endfor %}
  • Я использую Category.objects.all(), потому что я не знаю, как перечислить Категория из продукта, только для названия категории может быть доступ.

Надеюсь, вы, ребята, понимаете, о чем я спрашиваю. Извините за мой плохой английский.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...