我希望能够在django admins clean()
方法中访问请求对象。如何自定义此getting the user from a admin validation class以使用django admins modelform
我需要对change_view
下面的<{p}}做出哪些修改
def change_view(self, request, object_id, extra_context=None):
self.form = GroupForm
result = super(GroupsAdmin, self).change_view(request, object_id, extra_context)
return result
以便它调用下面带有request
参数
class GroupForm(forms.ModelForm):
class Meta:
model = Group
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(GroupForm, self).__init__(*args, **kwargs)
答案 0 :(得分:1)
看来没有为此提供任何答案,我想我应该强调我是如何解决这个问题的,以防万一其他人可能会发现这些信息有用。
我最终在定义自定义中间件并使用ThreadLocals
时解决了这个问题。
首先在forms.py
中定义一个ThreadLocals类,如下所示
import threading
_thread_locals = threading.local()
class ThreadLocals(object):
"""
Middleware that gets various objects from the
request object and saves them in thread local storage.
"""
def process_request(self, request):
_thread_locals.request = request
然后在settings.py
中确保启用中间件
MIDDLEWARE_CLASSES = (
'myproject.myapp.forms.ThreadLocals',
)
最后访问请求对象就像
一样简单class GroupForm(forms.ModelForm):
class Meta:
model = Group
def clean(self):
cleaned_data = super(GroupForm, self).clean()
self.request = _thread_locals.request