How to do "choices" from DB in form field without breaking migrations and such

37 views
Skip to first unread message

jason...@gmail.com

unread,
Feb 15, 2018, 9:56:56 AM2/15/18
to Django users
Hello everyone,

I have a form field that is pulling choices from the database:

class FooJBossForm(Form):
    biz_service
= MultipleChoiceField(
        choices
=BizService.objects.filter(
            biz_unit__bu_name
='Foo',
       
).order_by('bs_name').values_list('bs_name', 'bs_name').distinct(),
        required
=False,
        label
='Business Service',
        widget
=SelectMultiple(attrs={'class': 'form-control'}),
   
)

   
...

This worked great until someone else on my team attempted to start with a fresh DB and was getting "relation does not exist" errors trying to do the initial import.

Commenting out these "choices=" parameters in `forms.py` fixes the issue.  What's the right way to go about populating form field choices from the DB at access time?

Thanks,

j



jason...@gmail.com

unread,
Feb 15, 2018, 10:14:42 AM2/15/18
to Django users
I should have included that the reason I'm using a `MultipleChoiceField` instead of a `ModelMultipleChoiceField` here is because I want the POSTed variable to be the business service name (string) not the primary key of the selected record.

j

C. Kirby

unread,
Feb 15, 2018, 10:54:24 AM2/15/18
to Django users
You can set the choices in the form __init__ to handle the issue:

 class FooJBossForm(Form):
    biz_service = MultipleChoiceField(
        choices=[],

        required=False,
        label='Business Service',
        widget=SelectMultiple(attrs={'class': 'form-control'}),
    )

    def __init__(self, *args, **kwargs):
        super(FooJBossForm, self).__init__(*args, **kwargs)
        try:
            self.fields['biz_service'].choices = BizService.objects.filter(
                                   biz_unit__bu_name='Foo',
                                                 ).order_by('bs_name')\
                                                  .values_list('bs_name', 'bs_name')\
                                                  .distinct()
        except ProgrammingError:
            pass #OR Some placeholder choices

Kirby

jason...@gmail.com

unread,
Feb 15, 2018, 12:24:48 PM2/15/18
to Django users
Thank you very much.  This worked perfectly.  Consequently it also fixed my issue of those select boxes not reflecting changes in the list until the web server was restarted since the data is now being pulled at instantiation instead of in the class definition.

j

C Kirby

unread,
Feb 15, 2018, 12:29:31 PM2/15/18
to django...@googlegroups.com
Yeah, I meant to write about that. If you put a database filter in a field definition (model or form) it only runs it on start/restart. Using the method I put, or a callback function in the choices, allows the choices to reflect reality of the data.

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/4DbSczJGJF4/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ff2289b7-630b-4132-8d48-0ffc98715cdc%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages