我在新的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)
謝謝!
感謝Jaap3! +1,與formfield_for_dbfield我已經創建了答案:) – Avara 2014-09-22 15:41:52