我想动态修改django表单中的字段选项。 因为项目列表很长(超过650项),所以我将它们存储在django缓存中。
但是,当我想将它们作为字段选择注入时,应用程序变得无响应(有时返回ERR_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多个项目作为下拉选项太多了?
答案 0 :(得分:0)
最好使用ajax的方式。否则会出现一些浏览器加载问题。你可以用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()
编写一个函数来返回所请求类别的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
}
})
};
}
}
});
});