Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading