0

I'm attempting to create a search page for a database that I am maintaining by creating a dynamically maintained select box of all of the unique values of a few of my fields.

After much time and thought, I've decided that the best way to create a search form for my database would be to do so in views, resulting in something equivalent to this:

search_form = modelform_facotry(my_model,
                                fields=('field_one', 'field_two',),
                                widgets={'field_one': Select(choices=((datum.field_one, datum.field_one) for datum in my_model.objects.distinct('field_one'))),
                                         'field_two': Select(choices=((datum.field_two, datum.field_two) for datum in my_model.objects.distinct('field_two'))),
                                }
)

This works great! Except that I can't figure out how to include a blank option... The choices have to be created in a loop like that, so I can't just add a blank choice as many solutions suggest.

I've been pulling out my hair over this for a while now, because it seems like adding a blank option to a select widget would be an easy fix, but evidently not. Any help would be appreciated.

Edit: I should add that my fields are all CharFields

seaturtlecook
  • 243
  • 1
  • 2
  • 5

1 Answers1

1

After playing around with it for a while, I discovered what I needed to do:

FIELD_ONE_CHOICES = (('', '-----'),)
for datum in my_model.objects.distinct('field_one'):
    FIELD_ONE_CHOICES += ((datum.field_one, datum.field_one),)
FIELD_TWO_CHOICES = (('', '-----'),)
for datum in my_model.objects.distinct('field_two'):
    FIELD_TWO_CHOICES += ((datum.field_two, datum.field_two),)

search_form = modelform_factory(my_model,
                                fields=('field_one', 'field_two'),
                                widgets={'field_one': Select(choices=FIELD_ONE_CHOICES),
                                         'field_two': Select(choices=FIELD_TWO_CHOICES),
                                }
)

Tuples can be frustrating...

seaturtlecook
  • 243
  • 1
  • 2
  • 5