djangopython-3.xdjango-haystackfaceted-searchdjango-oscar

How to pre-select facets (i.e. get selected checkbox on page load) using Django-Haystack?


On the image below you can see how facets look when cpu_producer == "" (i.e. nothing selected).

enter image description here

There are circumstances when cpu_producer may be AMD or INTEL and on a page load appropriate facet's checkbox must be selected. How to select it in backend in order to get in frontend appropriately filtered cpu?

if category.slug == 'cpu':
    possible_sockets = '(socket_exact:"LGA1151" OR socket_exact:"LGA2066" OR socket_exact:"AM4" OR socket_exact:"TR4")'
    sqs = sqs.narrow(possible_sockets)

    possible_producers = '(producer_exact:"AMD" OR producer_exact:"INTEL")'
    sqs = sqs.narrow(possible_producers)

    cpu_producer = RECEIVED_VALUE  # "AMD" or "INTEL" or ""

    # I NEED SOMETHING LIKE THIS.
    if cpu_producer:
        sqs.PRESELECT(producer=cpu_producer)

Solution

  • Source code digging led me to the file haystack/forms.py. It seems that the class FacetedSearchForm should be overridden.

    However in my case it was acceptable just to have a url like:

    <a href="{{request.get_full_path}}cpu/?selected_facets=vendor_exact%3AAMD">
        <img src="{% static 'logo/amd.jpg' %}" alt="{{ cpu_producer.title }}" />
    </a>
    

    which leads to the cpu page and because of the ?selected_facets=vendor_exact%3AAMD part automatically selects Producer facet (i.e. AMD in this case).