2010-12-17 83 views
0

我希望能夠訪問django管理員clean()方法中的請求對象。我怎麼可以自定義此getting the user from a admin validation class使用Django管理員的ModelForm在django中使用change_view向ModelForm構造函數添加額外參數admin

的工作是什麼樣的修改我需要做出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) 
+0

我有點困惑爲什麼GroupForm在這個例子中是相關的mple? – monokrome 2010-12-17 22:33:23

+0

對不起,這是一個錯誤。修復。 – domino 2010-12-18 06:59:19

回答

1

看到沒有人提供過答案,我想我應該強調我是如何解決這個問題的,以防別人可能會發現信息有用。

我最終在定義自定義中間件和使用ThreadLocals時解決了這個問題。

首先在你的forms.py定義ThreadLocals類作爲您settings.py圖所示

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 

然後確保啓用中間件

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 
+1

醜陋地獄,但作品(+1) – Lepi 2012-05-22 14:43:55

相關問題