2011-09-04 76 views

回答

10

您可以將用戶對象作爲窗體構造函數中的額外參數傳遞。

例如

f = MyForm(user=request.user) 

和構造的樣子:

class MyForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     self.user = kwargs.pop('user',None) 
     super(MyForm, self).__init__(*args, **kwargs) 

,然後使用用戶在clean_XX形式,如你所願

+0

很抱歉在原來的問題沒有澄清這一點,但是我的ModelForm連接到了ModelAdmin子類。我如何從ModelAdmin調用ModelForm的自定義構造函數? – zer0stimulus

+0

所以你想在django管理界面中做到這一點?還沒有嘗試過,但我想你可以嘗試覆蓋窗體的__call__方法。例如類似:http://stackoverflow.com/questions/727928/django-admin-how-to-access-the-request-object-in-admin-py-for-list-display-meth –

7

注:如果您使用基於類的視圖(CBVS),然後在表單構造函數中傳遞額外參數(例如,在get_forms_class中)或在form_class中將不起作用,因爲將顯示<form> object is not callable

爲CBVS的解決方案是使用get_form_kwargs,如:

views.py:

# Sending user object to the form, to verify which fields to display/remove (depending on group) 
def get_form_kwargs(self): 
    kwargs = super(MyView, self).get_form_kwargs() 
    kwargs.update({'user': self.request.user}) 
    return kwargs 

forms.py:

class MyForm(forms.ModelForm): 

    def __init__(self, *args, **kwargs): 
     self.user = kwargs.pop('user') # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole 

     super(MyForm, self).__init__(*args, **kwargs) 

     # If the user does not belong to a certain group, remove the field 
     if not self.user.groups.filter(name__iexact='mygroup').exists(): 
      del self.fields['confidential'] 
相關問題