Django modelForm : dynamically adjust field according to related field

I've been working on a hospital project exercice and am wondering how to render a given field (model "doctor") according to a speciality selection: user has to select first a medical speciality and according to that one, the doctor's list will be dynamically updated.

How can I design my modelForm to achieve that goal? Do I need some javascript embedded in the template file?

Here is the related code in my django project:


class Speciality(models.Model):
    specialite_id = models.AutoField(primary_key=True)
    nom = models.CharField(max_length=50, unique=True, verbose_name="Spécialité")

    def __str__(self):
        return f"{self.nom}"

class Doctor(CustomUser):
    medecin_id = models.AutoField(primary_key=True)
    matricule_medecin = models.CharField(max_length=50, unique=True)  
    specialite = models.ForeignKey(Specialite, on_delete=models.CASCADE)
    admin = models.ForeignKey(Administrateur, on_delete=models.SET_NULL, null=Tru

e, blank=True)

    def __str__(self):
        return f"Dr {self.nom} {self.prenom}, spécialité : {self.specialite}"


class CreateSejour(forms.ModelForm):    
    class Meta:
        model = Sejour
        fields = '__all__'
        widgets = {'date_entree': forms.SelectDateWidget(years=range(2015, 2025)),
                   'date_sortie': forms.SelectDateWidget(years=range(2015, 2025)),
                   'motif': forms.Textarea()}

I don't see how to tackle this situation : do I have to implement some logic inside the modelForm or in my view? Thanks for your help. De716

Actually i'm stuck to that stage, my django experience doesn't allow me to address this and I have no experience in javascript

If You don't have any knowledge about js, you should do a multi step form.
In the first view that handles your form, add a condition that checks if values submited are valid. If soo, use redirect() to second step. I recommend you to break it into separate views and ModelForms.

Back to Top