如何为Django Admin搜索表单添加CSRF防护以符合安全要求?
Absolutely! You can absolutely resolve this security concern by enabling CSRF protection for the Django Admin search form—here are two reliable, easy-to-implement methods that will satisfy your vulnerability scanners and security team:
Method 1: Override the Admin Change List Template (Simplest & Recommended)
Django makes it trivial to override its built-in Admin templates. Here's how to inject the CSRF token into the search form:
- First, create a
templates/admindirectory in your Django project if it doesn’t already exist. - Locate the default
change_list.htmltemplate from Django’s admin package (you’ll find this in your Python environment’sdjango/contrib/admin/templates/admin/folder). Copy this file into your project’stemplates/admindirectory. - Open the copied
change_list.htmlfile and find the<form>element for the Admin search (it typically has the classsearch-form). - Inside this
<form>tag, add the Django template tag{% csrf_token %}. This will automatically render a hidden CSRF token input field, just like it does for all other protected Admin forms.
Save the template, refresh any Admin list page, and check the HTML source—you’ll see the csrfmiddlewaretoken hidden field in the search form. This should immediately clear the scanner’s vulnerability flag.
Method 2: Customize the Admin Class’s Changelist View
If you’d rather avoid template overrides, you can modify the Admin view to pass a CSRF token to the template context:
- In your app’s
admin.py, create a custom Admin class that inherits fromadmin.ModelAdmin. - Override the
changelist_viewmethod to generate a CSRF token and add it to the context. - You’ll then need to update the search form in the template to use this token (though this requires more code than the template override method).
Example code for admin.py:
from django.contrib import admin from django.middleware.csrf import get_token from .models import YourModel class YourModelAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} # Generate and pass the CSRF token to the template extra_context['csrf_token'] = get_token(request) return super().changelist_view(request, extra_context=extra_context) admin.site.register(YourModel, YourModelAdmin)
Then, in your overridden change_list.html, add the hidden token field to the search form:
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
A Quick Note on Why This Works
Django skips CSRF protection for the default Admin search form because it uses a GET request (which shouldn’t modify server-side data). However, many vulnerability scanners flag any form without a CSRF token regardless of the HTTP method. Adding the token won’t break the search functionality—it just adds the extra security layer your team’s policy requires.
Content from Stack Exchange, asked by oyilmaztekin

