You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django集成Bootstrap Tokenfield搜索功能异常,请求排查问题

Hey Ayanda! Let's work through your Bootstrap Tokenfield + Django autocomplete issue together—I’ve run into similar snags before, so let’s break this down step by step.

First, let’s start with the obvious issues in your code that are likely causing the failure, then fix them one by one:

1. Syntax Error in Your jQuery Code

Looking at your JS snippet, you have an extra }); at the end that’s breaking the script execution. This is probably why you’re seeing browser console errors. Let’s clean that up first.

2. Tokenfield Autocomplete Misconfiguration

You’re manually binding a keyup event to handle AJAX, but Bootstrap Tokenfield uses jQuery UI’s autocomplete under the hood—so you should leverage its built-in source option instead of overriding it with a separate keyup handler. This avoids conflicts and uses the component as intended.

3. Django View Returns Unusable Data

Right now your view returns plain text ("Query completed"), but the frontend needs a JSON list of matching keywords to populate the autocomplete dropdown. We’ll fix that to return valid JSON.


Fixed Code Snippets

Updated jQuery Code

$(function(){
  // Initialize Tokenfield with integrated AJAX autocomplete
  $('#tokenfield').tokenfield({
    autocomplete: {
      source: function(request, response) {
        // Use request.term to get the current input value from Tokenfield
        $.ajax({
          url: "/user_account/auto_complete_search/",
          type: 'POST',
          data: {
            'search_text': request.term,
            'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
          },
          success: function(data) {
            // Pass the returned keyword list to Tokenfield's autocomplete
            response(data);
          },
          dataType: 'json'
        });
      },
      delay: 100
    },
    showAutocompleteOnFocus: true
  });
});

Updated Django View

from django.http import JsonResponse
from .models import Keywords  # Make sure your model is imported correctly

def autocomplete_search_view(request):
    if request.method == 'POST':
        # Use .get() to avoid KeyError if search_text is missing
        search_text = request.POST.get('search_text', '')
    else:
        search_text = ''
    
    # Filter keywords and return only the 'keyword' field as a flat list
    matching_keywords = Keywords.objects.filter(
        keyword__icontains=search_text
    ).values_list('keyword', flat=True)
    
    # Return the list as JSON (safe=False allows non-dict responses)
    return JsonResponse(list(matching_keywords), safe=False)

Updated URL Configuration (Django 2.0+)

If you’re using a newer Django version, switch to path instead of the old url() regex for clarity:

from django.urls import path
from . import views

urlpatterns = [
    path('auto_complete_search/', views.autocomplete_search_view, name='autocomplete_search'),
]

Additional Checks to Ensure Success

  • Dependency Order: Make sure you’re loading scripts in the correct order in your HTML:
    1. jQuery
    2. jQuery UI (CSS + JS)
    3. Bootstrap Tokenfield (CSS + JS)
  • CSRF Validation: Confirm the csrfmiddlewaretoken input is present in your form (you already have this, so that’s good!)
  • Browser Console: Check for remaining errors after applying fixes—this will help catch missing dependencies or URL mismatches.

内容的提问来源于stack exchange,提问作者Ayanda Khanyile

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:49:58