2016-01-22 44 views
0

我有很多具有user字段的對象,我想用當前用戶自動填充該字段。對於這一點,我有一個mixindjango - 驗證當前用戶的ModelAdmin窗體

class AttachUserMixin(object): 

    def save_model(self, request, obj, form, change): 
     """ 
     При сохранении модели присвоить ему текущего юзера 
     """ 
     obj.user = request.user 
     obj.save() 

然而,在我的一些模型的形式,我有一些驗證當前用戶,就像這樣:

def clean(self): 
    data = super(ListForm, self).clean() 
    if data['type'] == ListTypes.ctr0.value: 
     existing_lists = (List.objects 
          .filter(country=data['country'], 
            user=data['user'], 
            ad_network=data['ad_network'], 
            type=data['type']) 
          .exclude(pk=self.instance.pk) 
          .all()) 

如果我從模型的形式取出user場,事情顯然崩潰。那麼如何從clean訪問當前用戶呢?

回答

1

我回答一個例子:

class X_Form(forms.ModelForm): 
    def __init__(self,request,*args,**kwargs): 
     super(X_Form, self).__init__(*args,**kwargs) 
     self.request = request 

    def clean(self): 
     user = self.request.user 
     ... 

和意見

def post_method(request): 
    form = X_Form(data=request.POST or None,request=request) 
    ... 

當然,如果我理解正確的話你的意思