awesto / django-shop

A Django based shop system
http://www.django-shop.org
BSD 3-Clause "New" or "Revised" License
3.19k stars 1.04k forks source link

Improvement docs about filters #573

Open vivazzi opened 7 years ago

vivazzi commented 7 years ago

I find better code about filters than in docs which allow write less code when we declare fields. Instead of (see http://django-shop.readthedocs.io/en/latest/reference/filters.html#id3):

from django.forms import forms, widgets
import django_filters
from djng.forms import NgModelFormMixin
from myshop.models.product import MyProduct, Manufacturer

class FilterForm(NgModelFormMixin, forms.Form):
    scope_prefix = 'filters'

class ProductFilter(django_filters.FilterSet):
    manufacturer = django_filters.ModelChoiceFilter(
        queryset=Manufacturer.objects.all(),
        widget=Select(attrs={'ng-change': 'filterChanged()'}),
        empty_label="Any Manufacturer")

    class Meta:
        model = MyProduct
        form = FilterForm
        fields = ['manufacturer']

    @classmethod
    def get_render_context(cls, request, queryset):
        """
        Prepare the context for rendering the filter.
        """
        filter_set = cls()
        # we only want to show manufacturers for products available in the current list view
        filter_field = filter_set.filters['manufacturer'].field
        filter_field.queryset =filter_field.queryset.filter(
            id__in=queryset.values_list('manufacturer_id'))
        return dict(filter_set=filter_set)

I suggest:

...

class FilterForm(NgModelFormMixin, Bootstrap3Form):
    def __init__(self, *args, **kwargs):
        kwargs.update({'scope_prefix': 'filters',
                       'ng_change': 'filterChanged()'})
        super(FilterForm, self).__init__(*args, **kwargs)

class ProductFilter(django_filters.FilterSet):
    manufacturer = django_filters.ModelChoiceFilter(
        queryset=Manufacturer.objects.all(),
        empty_label="Any Manufacturer")

    ...

Other words I changed FilterForm and remove widget=Select(attrs={'ng-change': 'filterChanged()'}), to we don't need write it every time.

I suggest to fix django shop documentation about filters, adding more information about how django-shop auto adds attributes ng-model and ng-change to html inputs. Also I suggest to add this information to http://django-angular.readthedocs.io/en/latest/angular-model-form.html (Excuse me if I miss information about it).

P. S. If you agree with me I can add pull request.

jrief commented 6 years ago

agree on that.