I'm currently setting up my Django project which is a search engine and I've been trying to estabish a connection between a custom Django View and a Javascript function but I kept having issues, so I decided to restart this from the beginning and hopefully get someone's help.
I have this Javascript code
const data = [] // Not sure how to get the data from the backend??
let index = 0;
let results = [];
const randomSearchMatchPercentages = ( array ) => {
for ( const element of array ) {
// define a maximum and a minimum range
const maximum = index <= 100 ? 100 - index : 0;
const minimum = maximum > 0 ? maximum - 5 : 0;
element.match = Math.round( Math.random() * ( maximum - minimum ) + minimum ) + "%";
results.push( element );
// decrease the maximum and minimum for the next iteration
index += 5;
}
console.log( results );
}
randomSearchMatchPercentages( data );
That I need to connect with a custom View like this:
def MatchingScore(request):
return JsonResponse(output)
I have established a connection and get the data from the backend for my autocomplete with this View:
def autocomplete(request):
sqs = SearchQuerySet().autocomplete(
content_auto=request.GET.get('query',''))[:5]
destinations = {result.destination for result in sqs}
s = [{"value": dest, "data": dest} for dest in destinations]
output = {'suggestions': s}
return JsonResponse(output)
And with this Javascript Function:
$(function () {
'use strict';
$('#q').autocomplete({
serviceUrl: "http://127.0.0.1:8000/search/autocomplete/",
minChars: 2,
dataType: 'json',
type: 'GET',
onSelect: function (suggestion) {
console.log( suggestion.value + ', data :' + suggestion.data);
}
});
});
But I don't know what code to put inside of my def MatchingScore
and how to adapt the Javascript code to make it work. I assume that I will need to get the data from my database in the same way as my autocomplete View
and pass it to the javascript function.
My goal is farely simple: Generate random number between 100 and 0% and display it to an html list that look like this:
<div>
{% if page_obj.object_list %}
<ol class="row top20">
{% for result in page_obj.object_list %}
<li class="list-item">
<div class="showcase col-sm-6 col-md-4">
<a href="{{ result.object.get_absolute_url }}">
<h3>{{result.object.title}}</h3>
<img src="{{ result.object.image }}" class="img-responsive">
</a>
</div>
<li>
{% endfor %}
</ol>
</div>
{% else %}
<p> Sorry, no result found </p>
{% endif %}
How can I do this?
EDIT:
I have this custom forms.py file that I use with Django-Haystack for the search functionnalities:
from haystack.forms import FacetedSearchForm
class FacetedProductSearchForm(FacetedSearchForm):
def __init__(self, *args, **kwargs):
data = dict(kwargs.get("data", []))
self.ptag = data.get('ptags', [])
super(FacetedProductSearchForm, self).__init__(*args, **kwargs)
def search(self):
sqs = super(FacetedProductSearchForm, self).search()
if self.ptag:
query = None
for ptags in self.ptag:
if query:
query += u' OR '
else:
query = u''
query += u'"%s"' % sqs.query.clean(ptags)
sqs = sqs.narrow(u'ptags_exact:%s' % query)
return sqs
Then I pass the custom form into my Views with this class:
from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView
from .forms import FacetedProductSearchForm
class FacetedSearchView(BaseFacetedSearchView):
form_class = FacetedProductSearchForm
facet_fields = ['ptags']
template_name = 'search_result.html'
paginate_by = 20
context_object_name = 'object_list'
I've tried the first approach but I don't get any search results back, and since I already have pagination
and an object_name
, is there a way to implement both the def MatchingScore
and the def random_search_match_percentages
into this class by indenting it or something else so that I can call the match
within this template tag? :
{% if page_obj.object_list %}
{% for result in page_obj.object_list %}
{% endfor %}
{% else %}
{% endif %}