【问题标题】:Adding extra arguments to ModelForm Constructor using change_view in django admin在 django admin 中使用 change_view 向 ModelForm 构造函数添加额外的参数
【发布时间】:2010-12-17 15:44:50
【问题描述】:

我希望能够在 django 管理员clean() 方法中访问请求对象。如何自定义此 getting the user from a admin validation class 以使用 django 管理员模型表单

下面的change_view需要做什么样的修改

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)

【问题讨论】:

  • 我有点迷茫,为什么这个例子中 GroupForm 是相关的?
  • 抱歉,这是一个错误。修好了。

标签: django django-admin django-forms


【解决方案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

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多