我需要重写Django管理界面中的add_view()
视图,该视图在尝试添加新的模型实例时被调用。
我尝试过:
class BaseMarketModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.creator = request.user
return super().save_model(request, obj, form, change)
def add_view(self, request, form_url='', extra_context=None):
try:
super(BaseMarketModelAdmin, self).add_view(
request, form_url, extra_context
)
except ValidationError as e:
return handle_exception(self, request, e)
def change_view(self, request, object_id, form_url='', extra_context=None):
try:
return super(BaseMarketModelAdmin, self).change_view(
request, object_id, form_url, extra_context
)
except ValidationError as e:
return handle_exception(self, request, e)
< p > < code > change_view() 没有任何问题,但是当我尝试在 Django 管理界面中使用“添加 ModelName”按钮添加新的模型实例时,总是会出现以下异常:
AttributeError at /admin/market/exchange/add/
'NoneType' object has no attribute 'has_header'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/market/exchange/add/
Django Version: 3.0.3
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'has_header'
Exception Location: /usr/local/lib/python3.7/site-packages/django/utils/cache.py in patch_response_headers, line 243
Python Executable: /usr/local/bin/python
Python Version: 3.7.7
我尝试检查Django的add_view()
源代码,它位于:django/contrib/admin/options.py,看起来它只是调用了没有object_id参数的change_view()
方法。然后我尝试了以下代码:
def add_view(self, request, form_url='', extra_context=None):
return self.changeform_view(request, None, form_url, extra_context)
它能够正确加载新实例页面,但是没有调用我的BaseMarketModelAdmin.change_view()
视图!
然后我尝试了这个:
def add_view(self, request, form_url='', extra_context=None):
return BaseMarketModelAdmin.changeform_view(request, None, form_url, extra_context)
但是会导致以下异常:
AttributeError at /admin/market/exchange/add/
'NoneType' object has no attribute 'COOKIES'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/market/exchange/add/
Django Version: 3.0.3
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'COOKIES'
Exception Location: /usr/local/lib/python3.7/site-packages/django/middleware/csrf.py in _get_token, line 170
Python Executable: /usr/local/bin/python
Python Version: 3.7.7
现在我需要覆盖那个
add_view()
视图。正确的方法是什么?
add_view(...)
做什么吗? - JPG