Django自动补全功能触发404错误的排查与解决请求
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')
4. Optional (But Recommended): Fix Model Typo
Your model has lastaname which is likely a typo for lastname. If you fix this:
- 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 - Run migrations:
python manage.py makemigrations python manage.py migrate - Update the view to use
lastname__icontains=qinstead oflastaname.
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

