ChoiceField - 基于布尔字段的选择

时间:2010-12-21 15:32:36

标签: python django django-models django-forms

我正在尝试使用选项字段,仅显示将ProjectManager布尔字段选为true的用户。我找不到办法来解决这个问题。

一点背景。创建用户时,如果他们是项目经理,则可以选择一个复选框。如果他们检查它,我希望下拉选择字段显示所有项目经理(稍后,在创建新项目时)。

这是我的代码片段,以帮助。

项目 - Models.py

class Project(models.Model):
client = models.ForeignKey(Clients, related_name='projects')
project_manager = models.ForeignKey(customUser, related_name='Project Manager')
created_by = models.ForeignKey(User, related_name='created_by')
...

客户 - models.py

class Clients(models.Model):

   client_name = models.CharField(max_length=255, verbose_name='Client Name', unique=True)
   ...    

class customUser(User):
   company = models.ForeignKey(Clients, related_name="belongs to")
   pm = models.BooleanField(verbose_name='Project Manager')

Project forms.py

class TimeMaterialsForm(ModelForm):
status = forms.ChoiceField(choices=STATUS_CHOICES)
project_manager = forms.ChoiceField(??)
def __init__(self, *args, **kwargs):
    super(TimeMaterialsForm, self).__init__(*args, **kwargs)
    self.fields['status'].initial = 'T'
    self.fields.keyOrder = ['proj_name', 'client','project_manager','starts_on','desc', 'due_date','completed_on','quote_value','pt_percent','pt_desc','purchase_order','SRED','status', 'notes']
    self.fields['status'].widget=forms.HiddenInput()

...

谢谢大家!

史蒂夫

1 个答案:

答案 0 :(得分:1)

这有帮助吗?

class TimeMaterialsForm(ModelForm):
   status = forms.ChoiceField(choices=STATUS_CHOICES)
   project_manager = forms.forms.ModelChoiceField(queryset=customUser.objects.filter(pm=True))
   ...  

http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield