2010-05-30 54 views
3

我試圖初始化實例方法中的MyModelAdmin類的窗體屬性的內部,具體如下:傳遞會話數據的ModelForm的ModelAdmin

class MyModelAdmin(admin.ModelAdmin): 
    def queryset(self, request): 
     MyModelAdmin.form = MyModelForm(request.user) 

我的目標是定製基於的MyModelForm編輯表單當前會話。然而,當我嘗試這個時,我總是收到一個錯誤(如下所示)。這是將會話數據傳遞給ModelForm的適當位置嗎?如果是這樣,那麼可能會導致這個錯誤?

類型錯誤在...

異常類型:類型錯誤

異常值:issubclass()ARG 1必須是類

異常位置:/ usr/lib中/ pymodules/python2 .0/django/forms/models.py在,行185

回答

0

我使用queryset fot過濾記錄,也許這個例子幫助你:

..... 
..... 
def queryset(self, request): 
    cuser = User.objects.get(username=request.user) 

    qs = self.model._default_manager.get_query_set() 
    ordering = self.ordering or() # otherwise we might try to *None, which is bad ;) 

    if ordering: 
     qs = qs.order_by(*ordering) 

    qs = qs.filter(creator=cuser.id) 

    return qs 
1

從理論上說,你可以重寫的ModelAdmin的get_form方法:

# In django.contrib.admin.options.py 
def get_form(self, request, obj=None, **kwargs): 
    """ 
    Returns a Form class for use in the admin add view. This is used by 
    add_view and change_view. 
    """ 
    if self.declared_fieldsets: 
     fields = flatten_fieldsets(self.declared_fieldsets) 
    else: 
     fields = None 
    if self.exclude is None: 
     exclude = [] 
    else: 
     exclude = list(self.exclude) 
    exclude.extend(kwargs.get("exclude", [])) 
    exclude.extend(self.get_readonly_fields(request, obj)) 
    # if exclude is an empty list we pass None to be consistant with the 
    # default on modelform_factory 
    exclude = exclude or None 
    defaults = { 
     "form": self.form, 
     "fields": fields, 
     "exclude": exclude, 
     "formfield_callback": curry(self.formfield_for_dbfield, request=request), 
    } 
    defaults.update(kwargs) 
    return modelform_factory(self.model, **defaults) 

注意它返回一個表單類,而不是一種形式的實例。

1

如果一些新手,而我自己,經過這裏:
我不得不定義:

class XForm(forms.ModelForm):  
    request=None  

然後在以前的帖子

mfc=modelform_factory(self.model, **defaults) 
    self.form.request=request #THE IMPORTANT statement 
    return mfc 
1

Izz ad-Din Ruhulessin's answer結合的好點子結束suggestion by Cikić Nenad,我結束了一個非常真棒和簡潔的解決方案如下:

class CustomModelAdmin(admin.ModelAdmin): 
    def get_form(self, request, obj=None, **kwargs): 
     self.form.request = request #so we can filter based on logged in user for example 
     return super(CustomModelAdmin, self).get_form(request,**kwargs) 

然後,只需設置一個自定義窗體對於喜歡的ModelAdmin:

form = CustomAdminForm 

而且在像自定義的ModelForm類訪問請求:

self.request獲取#do與請求的東西與表單關聯

+0

我不會在一個線程可以被多個用戶使用的生產環境中執行此操作。你基本上在表單Class上設置了一個「請求」變量,這個變量可能在多個用戶中共享。併發問題可能會出現。在那裏,這樣做,不建議 - 這種錯誤是一個屁股跟蹤疼痛。 – 2014-10-24 11:38:45

0

這裏是從nemesisfixx溶液生產/線程安全變化:

def get_form(self, request, obj=None, **kwargs): 
    class NewForm(self.form): 
     request = request 
    return super(UserAdmin, self).get_form(request, form=NewForm, **kwargs)