修改带有几百项的Django表单字段选项会导致冻结/不响应

2024-04-26 04:03:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想动态修改django表单中的字段选项。 因为项目的列表很长(超过650个项目),所以我将它们存储在django缓存中。你知道吗

但是,当我想将它们作为字段选择注入时,应用程序会变得没有响应(有时会返回ERR\u EMPTYRESPONSE)。你知道吗

我的观点:

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

你知道那里发生了什么吗?也许600多个项目作为下拉选择太多了?你知道吗


Tags: 项目djangonameform表单datagetuuid
1条回答
网友
1楼 · 发布于 2024-04-26 04:03:41

最好的方法是使用ajax。否则会出现一些浏览器加载问题。您可以使用ajax来实现这一点。你知道吗

你知道吗表单.py你知道吗

class ProductForm(forms.ModelForm):

     def __init__(self, *args, **kwargs):
         super(ProductForm, self).__init__(*args, **kwargs)
         self.fields['category'].queryset = Category.objects.none()

编写一个函数来返回请求类别的dict

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)

在html模板中添加以下脚本

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

});

相关问题 更多 >