Skip to content

Instantly share code, notes, and snippets.

@davidbgk
Created October 28, 2010 10:30
Show Gist options
  • Select an option

  • Save davidbgk/651080 to your computer and use it in GitHub Desktop.

Select an option

Save davidbgk/651080 to your computer and use it in GitHub Desktop.
Easily add an empty choice to a Django ChoiceField
from django import forms
class EmptyChoiceField(forms.ChoiceField):
def __init__(self, choices=(), empty_label=None, required=True, widget=None, label=None,
initial=None, help_text=None, *args, **kwargs):
# prepend an empty label if it exists (and field is not required!)
if not required and empty_label is not None:
choices = tuple([(u'', empty_label)] + list(choices))
super(EmptyChoiceField, self).__init__(choices=choices, required=required, widget=widget, label=label,
initial=initial, help_text=help_text, *args, **kwargs)
@cristihainic

Copy link
Copy Markdown

Thanks!!

ghost commented Apr 24, 2019

Copy link
Copy Markdown

Nice, thanks!

@alex-re

alex-re commented Jan 23, 2021

Copy link
Copy Markdown

thanks for your nice idea after 10 years !

@ddahan

ddahan commented May 10, 2022

Copy link
Copy Markdown

thanks for your nice idea after 12 years !

@davidbgk

Copy link
Copy Markdown
Author

🙌

@OGBoomer

Copy link
Copy Markdown

Still relavant

@sylwester0

Copy link
Copy Markdown

Thanks!!

@iloeza

iloeza commented Jul 12, 2024

Copy link
Copy Markdown

Clever solution for cleaner code. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment