简体   繁体   中英

ChoiceField - choices based on boolean field

I am trying to have a choicefield that only displays the users with the ProjectManager boolean field checked as true. I am having some trouble figuring out the way to do it though.

A little background. When a user is created, there is a checkbox that they can select if they are a project manager or not. If they check it, I want the dropdown choice field to display all the project managers (later, when creating a new project).

Here is my code snippets to help.

Project - 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')
...

Clients - 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()

...

Thanks everyone!

Steve

Does this help?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM