使用django admin中的change_view向ModelForm构造函数添加额外的参数

时间:2010-12-17 15:44:51

标签: django django-admin django-forms

我希望能够在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)

1 个答案:

答案 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