【问题标题】:Simple Django form with autocomplete带有自动完成功能的简单 Django 表单
【发布时间】:2014-09-15 17:12:45
【问题描述】:

有没有关于如何在 Django 表单中使用自动完成的简单示例:

forms.py
class SimpleForm(forms.form):
    a = forms.ModelChoiceField(Model.objects)

template
form action="" method="post">{% csrf_token %}
{{ simple_form }}

我需要一个字段来自动完成。我找到了this,但这是一个模型形式而不是普通形式。 任何建议。

【问题讨论】:

    标签: jquery django autocomplete


    【解决方案1】:

    这是我用于 Django 3.2 的代码:

    from django.http import JsonResponse
    
    def my_autocomplete(request):
        """Return a json list of suggestions given a prefix in 'term' param"""
        term = request.GET.get('term', None)
    
        qs = MyObject.objects.all()
        if term:
            qs = qs.filter(field__istartswith=term)
        # NOTE: This order is non-deterministic if there are more than 5
        # objects with the same 'order'.  I'm assuming that's okay.
        qs = qs.order_by('order')[:5]
    
        results = [r.field for r in qs]
    
        # NOTE: results is put into json.  safe=False allows an array.
        return JsonResponse(results, safe=False)
    

    【讨论】:

      【解决方案2】:

      Jquery autocomplete 与 django 非常容易集成。您只需要创建一个函数,该函数会在您的查询中返回一个 json。例如:

      def automcomplete(request):
          search_qs = YourObject.objects.filter(title__icontains=request.REQUEST['search'])[:5]
          results = []
          for r in search_qs:
              results.append(r.title)
          resp = request.REQUEST['callback'] + '(' +simplejson.dumps(results) + ');'
          return HttpResponse(resp,content_type='application/json')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 2017-10-06
        • 1970-01-01
        • 2014-06-14
        • 1970-01-01
        • 2020-04-23
        相关资源
        最近更新 更多