I need to override the view add_view()
in django admin that gets called whenever I try to add a new model instance.
What I've tried:
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)
The change_view()
works without any problems, but when I try to add a new model instance using "Add ModelName" button in django admin I always get this exception:
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
I tried checking the source code of django's add_view()
which is placed in: django/contrib/admin/options.py and it seems that it only calls change_view()
with no object_id. Then I tried this:
def add_view(self, request, form_url='', extra_context=None):
return self.changeform_view(request, None, form_url, extra_context)
And it loads the new instance page correctly but does NOT call my BaseMarketModelAdmin.change_view()
view!
Then I tried this:
def add_view(self, request, form_url='', extra_context=None):
return BaseMarketModelAdmin.changeform_view(request, None, form_url, extra_context)
But it results in this exception:
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
Now I need to override that add_view()
view. What is the correct way to do this?
It is missing the return value in the add_view
method
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With