2014-09-22 89 views
0

我在新的Django,我已經創建了這種結構的一個項目:過濾器通過用戶在Django管理表格ModelChoiceField

model.py

from django.contrib.auth.models import User, Group 

class MyModel(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    created_by = models.ForeignKey(User, null=True, blank=True) 
    group = models.ForeignKey(Group, null=True, blank=True) 
    ... 
    ... 

admin.py

class MyModelAdmin(admin.ModelAdmin): 
    form = MyModelForm 
    ... 

    def queryset(self, request): 
     qs = super(MyModelAdmin, self).queryset(request) 
     # If super-user, show all records 
     if request.user.is_superuser: 
      return qs 
     # If user have group, show all records of the group 
     if request.user.groups.all().count() > 0: 
      return qs.filter(group=(request.user.groups.all())) 
     #Show only the records that the user have been created 
     return qs.filter(created_by=request.user) 

我只想顯示分配給特定組的記錄。沒關係,但是我怎麼能創建在admin.py中使用的相同過濾器來過濾我的Django表單中用戶組的選擇?我怎麼能通過記錄到ModelForm類的實際用戶?

Forms.py

class MyModelForm(forms.ModelForm): 
    group = forms.ModelChoiceField(Group.objects.filter(id=####), 
       label=ugettext_lazy("Groups"), required=True) 

謝謝!

回答

2

您無法在字段定義中執行此操作,因爲您需要請求對象。我認爲這樣做是對管理類中定義formfield_for_dbfield的唯一途徑:

def formfield_for_dbfield(self, db_field, request, **kwargs): 
    field = super(MyModelAdmin, self).formfield_for_dbfield(db_field, request, **kwargs) 
    if db_field.name == 'groups': 
     field.queryset = field.queryset.filter(user=request.user) 
    return field 

沒有測試的代碼,所以它可能是錯誤的:-)

+0

感謝Jaap3! +1,與formfield_for_dbfield我已經創建了答案:) – Avara 2014-09-22 15:41:52

2

隨着formfield_for_dbfield我已經成立了答案:)

admin.py

class MyModelAdmin(admin.ModelAdmin): 
    form = MyModelForm 
    ... 
    def get_form(self, request, obj=None, **kwargs): 
     kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request) 
     return super(MyModelAdmin, self).get_form(request, obj, **kwargs) 

    def formfield_for_dbfield(self, db_field, **kwargs): 
     field = super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs) 
     if db_field.name == 'group': 
      field.queryset = field.queryset.filter(id__in=(kwargs['request'].user.groups.all())) 
     return field