I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:
<option value="">---------</option>
What I'd like to know is:
- What is the cleanest way to remove this auto-generated option from the select box?
What is the cleanest way to customize it so that it shows as:
<option value="">Select Item</option>
In searching for a solution I came across Django ticket 4653 which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.
Thanks for any help,
Jeff
Edit: I've configured the ForeignKey field as such:
verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.
you can do this in admin:
from the docs
so set the default and you're ok
For a
ForeignKey
field, setting thedefault
value to''
on the model will remove the blank option.For other fields like
CharField
you could set thedefault
toNone
, but this does not work forForeignKey
fields in Django 1.11.I was messing around with this today and just came up with a
coward hacknifty solution:Now you can tweak the default
ModelChoiceField
empty label to anything you'd like. :-)PS: No need for downvotes, non-harmful monkey patches are always handy.
For the latest version of django the first answer should be like this
There are lots of great answers here, but I'm still not entirely satisfied with the implementations. I'm also a bit frustrated that select widgets from different sources (foreign keys, choices) yield different behaviours.
I have a design I'm working with where select fields always have a blank option, and if they're required they will have a star next to them and the form will simply not validate if they're left empty. That said, I can only properly override the empty_label for fields that are not
TypedChoiceField
s.Here's what the result should look like. The first result is always the name of the field - in my case, the
label
.Here's what I ended up doing. The following is an overridden
__init__
method of my form: