Thanks to FilterView, you can simplify and reduce the code for displaying goods, products, and so on. That will reduce the code at times! At first I used ListView and wrote a lot when in order to be able to filter by queries. Until one of my good friends advised me django-filter . After reading more about him, I realized that this is what you need. After, when I wanted to use all my views as an object. This puzzled me a little, until a friend again helped me out with a hint about using FilterView, and now we will discuss it in more detail:
We have a Product model which has a Collection category.
class Collection(models.Model): name = models.CharField(verbose_name='Коллекция', max_length=150, default=None) slug = models.SlugField(verbose_name='ссылка') is_active = models.BooleanField(verbose_name='Статус активности', default=True) class Meta: db_table = 'collection' verbose_name = 'Коллекция' verbose_name_plural = 'Коллекции' ordering = ('name',) def __str__(self): return self.name class Product(models.Model): name = models.CharField('название товара', max_length=200) category = models.ForeignKey(Category, blank=True, null=True, verbose_name='Категория') collection = models.ForeignKey(Collection, blank=True, null=True, verbose_name='Коллекция') price = models.IntegerField(verbose_name='цена в ₸', default=0) discount = models.IntegerField(verbose_name='скидка в %', default=0) recommended = models.BooleanField(verbose_name='Рекомендуемый товар', default=False) ....
We need to display it in the template so that we can filter or sort it however we want. To do this, we will create filters.py where we write:
Ничем не отличается от джанго формы import django_filters from .models import Product CHOICES =[ ["name", "по алфавиту"], ["price", "дешевые сверху"], ["-price", "дорогие сверху"] ] class ProductFilter(django_filters.FilterSet): name = django_filters.CharFilter(name='name', lookup_expr='icontains') category__slug = django_filters.CharFilter() price__gt = django_filters.NumberFilter(name='price', lookup_expr='gt') price__lt = django_filters.NumberFilter(name='price', lookup_expr='lt') ordering = django_filters.OrderingFilter(choices=CHOICES, required=True, empty_label=None,) class Meta: model = Product exclude = [field.name for field in Product._meta.fields] order_by_field = 'name'
Next, create a view that inherits from FilterView
class CollectionViews(FilterView): template_name = 'product/coolections.html' model = Product paginate_by = 10 filterset_class = ProductFilter context_object_name = 'products' def get_queryset(self): qs = self.model.objects.prefetch_related('photo_set') if self.kwargs.get('collec_slug'): qs = qs.filter(collection__slug=self.kwargs['collec_slug']) return qs
If you are using bootstrap you can use #### django-bootstrap3
{% load bootstrap_tags %} {{ form|as_bootstrap }}
Круто, круто ))
Информация полезная, но текст очень похоже на машинный перевод.
Может быть, а может и нет, все имеют различную речь.. не могу отвечать за всех пользователей ресурса.. поскольку каждый пользователь может дополнить материал ресурса статьями.