How to make dynamic choicefields based on models in django forms?

I have a Group Model that I want to use it's objects in my form. I would like to have a dynamic choices tuple based on Group model objects! How can I do this? I used the code below :

class Employee_Form(forms.Form):
GROUPS = ()
try:
    GROUPS = (
    )
    for i in Group.objects.all():
        GROUPS += ((i.name , i.name),)
except:
    pass
phone = forms.CharField(max_length=12)
name = forms.CharField(max_length=50)
position = forms.CharField(max_length=30)
group = forms.ChoiceField(choices=GROUPS)

This code have a problem . every time you add a new object to your model you have to restart the server after that But it does not recommended! and one important thing is I want to use forms.Form not the modelForm.

What you are trying to do, already exists: a ModelChoiceField form field [Django-doc], this takes a QuerySet, and uses the primary key as identifier to determined the picked item:

class Employee_Form(forms.Form):
    phone = forms.CharField(max_length=12)
    name = forms.CharField(max_length=50)
    position = forms.CharField(max_length=30)
    group = forms.ModelChoiceField(queryset=Group.objects.all())
Back to Top