Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Modifying django form field choices with few hundred items causes freeze / not responsive

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
                    }
                })
            };
        }
    }
});

});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!