I want to dynamically modify a field choices in django form. Because item's list is pretty long (more then 650 items), I store them in django cache.
However, when I want to inject them as field choices, application become unresponsive (sometime returns ERR_EMPTYRESPONSE).
My view:
class HomeView(TemplateView):
template_name = 'web/pages/homepage.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
categories = cache.get_or_set('categories_list', Category.objects.values('uuid', 'code', 'name'), 3600)
categories_choices = [(o['uuid'], '{} ({})'.format(o['name'], o['code'])) for o in categories]
print(categories_choices) #its printing proper choices here
context['form'] = SearchForm()
context['form'].fields['category'].choices = categories_choices #this line causes freeze/timeout
return context
Any idea what is happening there? Maybe 600+ items as dropdown choices is too many?
best the way to use this with ajax. Otherwise there will be some browser loading issue will be there. You can do this with ajax.
forms.py
class ProductForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['category'].queryset = Category.objects.none()
write a function to return dict of the requested category
from django.http import JsonResponse
def suggest_category(request):
category = request.GET.get("category")
category = [{"data":"nothing found"}]
if category:
category = Category.objects.filter(category__icontains=
category).values("uuid", "category")
category = list(category)
return JsonResponse(category, safe=False)
and in you html template add this script
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(document).ready(function(){
$("select[name='category']").select2({
// tags: true,
// multiple: true,
// tokenSeparators: [',', ' '],
minimumInputLength: 2,
minimumResultsForSearch: 10,
ajax: {
url: '{% url 'product:suggest_category' %}',
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
category: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.category,
id: item.uuid
}
})
};
}
}
});
});