覆盖 django admin 的 add_view() 的正确方法

Correct way to override django admin's add_view()

我需要覆盖 django admin 中的视图 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)

change_view() 工作没有任何问题,但是当我尝试在 django 管理中使用“添加模型名称”按钮添加新模型实例时,我总是得到这个异常:

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,它似乎只调用 change_view() 而没有 object_id。然后我试了这个:

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 方法中缺少 return 值

    def add_view(self, request, form_url='', extra_context=None):
    try:
        return super(BaseMarketModelAdmin, self).add_view(
            request, form_url, extra_context
        )
    except ValidationError as e:
        return handle_exception(self, request, e)