Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda