0

I have a django model for an appointment to the doctor

class Appointment(models.Model):
    patient=models.ForeignKey(Patient,on_delete=models.SET_NULL,null=True)
    date=models.DateField(default=datetime.date.today)
    doctor=models.ForeignKey(Profile,on_delete=CASCADE)
    status=models.CharField(max_length=12,default="open")
    def __str__(self):
        return self.name

Doctor is one of the roles in the Profile model. My form is defined like so

class AppointmentForm(forms.ModelForm):
    class Meta:
        model=Appointment
        exclude = ['id']
    def __init__(self,*args,**kwargs):
        super().__init__(*args, **kwargs)
        self.helper=FormHelper()
        self.helper.layout=Layout(
            Row(
                Column('patient',css_class="form-control, col-md-4 mb-0"),
                Column('date',css_class="form-group, col-md-4 mb-0"),
                Column('doctor',css_class="form-group, col-md-4 mb-0"),
                css_class='row '
            ),
            Submit('btn_save', 'Save',css_class='btn-success')
        )

When displaying the form using crispy forms, all the users of the Profile models are shown.

How do I display only Profiles with role Doctor?

Monty Swanson
  • 695
  • 16
  • 41

1 Answers1

2

On your init function, you can filter the queryset used to display the doctor choices:

class AppointmentForm(forms.ModelForm):

    def __init__(self,*args,**kwargs):
        super().__init__(*args, **kwargs)

        self.fields['doctor'].queryset = Profile.objects.filter(role="Doctor")

You can further read about this on How do I filter ForeignKey choices in a Django ModelForm?

nicootto
  • 129
  • 8