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

Django自动补全功能触发404错误的排查与解决请求

Fixing the 404 Error in Django Autocomplete

Let's walk through the issues causing your 404 error and fix them one by one:

1. URL Routing Mismatch (Primary Cause of 404)

Your script is requesting /api/get_teacher/, but your URL pattern might be duplicated or misconfigured. Here's how to fix it:

If your app's URLs are included under an /api/ prefix in the project's urls.py:

Project urls.py:

from django.conf.urls import include, url

urlpatterns = [
    # Maps all /api/ requests to your app's URLs
    url(r'^api/', include('your_app_name.urls')),
]

App urls.py:
Remove the /api/ prefix from the pattern and add a $ to ensure exact matching:

urlpatterns = [
    url(r'^get_teacher/$', views.get_teacher, name='get_teacher'),
]

If you're not using a prefix:

Project urls.py:

urlpatterns = [
    url(r'^api/get_teacher/$', views.get_teacher, name='get_teacher'),
]

2. Template and Form Field Mismatch

Your template uses {{TeacherForm.asesores}}, but your form defines a field named teacher. This means the input's ID is id_asesores, but your script targets #id_teacher. Fix the template:

<table>
  <td class="input-group mb-3">
    <label for="{{ TeacherForm.teacher.id_for_label }}"> Teacher(es): </label>
    <div class="ui-widget"> {{ TeacherForm.teacher }} </div>
  </td>
</table>

3. View Code Fixes

Your view has typos and deprecated code that would break functionality even after fixing the 404:

from django.http import HttpResponse
import json
from .models import Teacher  # Make sure to import your model

def get_teacher(request):
    # Replace deprecated is_ajax() with header check
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        q = request.GET.get('term', '')
        # Fix model name and use partial match (icontains) for autocomplete
        teachers = Teacher.objects.filter(lastaname__icontains=q)
        results = []
        for professor in teachers:
            # Use the correct model field name (lastaname)
            full_name = f"{professor.lastaname} {professor.firstname} {professor.middlename}"
            results.append(full_name)
        data = json.dumps(results)
    else:
        data = json.dumps('fail')  # Ensure we return valid JSON even on failure
    return HttpResponse(data, content_type='application/json')

Your model has lastaname which is likely a typo for lastname. If you fix this:

  1. Update the model:
    class Teacher(models.Model):
        firstname = models.CharField(max_length=50)
        middlename = models.CharField(max_length=30)
        lastname = models.CharField(max_length=30)  # Fixed typo
    
  2. Run migrations:
    python manage.py makemigrations
    python manage.py migrate
    
  3. Update the view to use lastname__icontains=q instead of lastaname.

5. Test the URL Directly

To confirm the 404 is fixed, visit http://localhost:8000/api/get_teacher/?term=Guerrer in your browser. You should see a JSON array of matching teacher names instead of a 404 page.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:28:04