Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8812481
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T03:36:58+00:00 2026-06-14T03:36:58+00:00

When using Django’s ModelChoiceField , with required=False, an extra choice (”, ‘——–‘) is generated

  • 0

When using Django’s ModelChoiceField, with required=False, an extra choice ('', '--------') is generated automatically. When selecting this option, it ends up as None in the cleaned_data. How do I (idiomatically) reproduce this behavior when using a regular ChoiceField?

Some things I’ve noted:

  • I have not found any way to automatically add the tuple ('', '---------') to the list of choices, so it appears to be required to add it manually. I feel there should be a way to add it to the choices by setting one of the parameters differently, so if that exists I would love to hear it.
  • The conversion from '' to None must still be done manually in the code that uses cleaned_data. This means the code that deals with ModelChoiceFields has to be subtly different from the ChoiceField code, which may possibly lead to subtle bugs. Again: if someone knows better idioms, I’d love to hear that.
  • TypedChoiceField does some magic handling of ''. In particular, it does not offer it to the coerce function like one would expect.

Consider the following code:

def int_or_none(s):
    if s.isnumeric():
        return int(s)
    return None

class NoneForm(forms.Form):
    field = forms.TypedChoiceField(
      choices=[('', '--------'), ('1', 'One'), ('2', 'Two')],
      required=False, coerce=int_or_none)

def home(request):
    if request.method == "POST":
        form = NoneForm(request.POST)
        if form.is_valid():
            assert type(form.cleaned_data['field']) in [int, type(None)]
            print form.cleaned_data['field']

    form = NoneForm()
    return HttpResponse(
      """<form method="POST">""" +
      form.as_table() +
      """<input type="submit"></form>""")

The assertion above fails!

Can it really be this hard to get Django’s various versions of ChoiceField to clean to None in an idiomatic way?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T03:37:00+00:00Added an answer on June 14, 2026 at 3:37 am

    This is the result based on rantanplan’s comment about the empty_value parameter.

    Note especially that the choice for the empty value is implemented as '' in the choices (just like in ModelChoiceField, so that’s good).

    class NoneForm(forms.Form):
        field = forms.TypedChoiceField(
          choices=[('', '--------'), ('1', 'One'), ('2', 'Two')],
          required=False, coerce=int, empty_value=None)
    
    def home(request):
        if request.method == "POST":
            form = NoneForm(request.POST)
            if form.is_valid():
                assert type(form.cleaned_data['field']) in [int, type(None)]
                print form.cleaned_data['field']
    
        form = NoneForm()
        return HttpResponse(
          """<form method="POST">""" +
          form.as_table() +
          """<input type="submit"></form>""")
    

    Now the assertion succeeds.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using django, which is the way to check if data is present? I know
Using django comments framework http://docs.djangoproject.com/en/dev/ref/contrib/comments/ Not sure is there option, to make all comments
Using Django 1.1, I am trying to select the maximum value from a varchar
using django 1.4 I have a model with a datetimefield. I imported django.utils.timezone to
I`m using Django to send some emails with embedded images to my gmail account.
Am using django social-auth authentication for my app.After login to facebook or twitter from
I using Django tagging project. That is was very stable project. Working on django
I am using django-registration and would like to have a different page for failed
I'm using Django's post_save signal to send emails to users whenever a new article
I am using Django Crispy Forms together with Twitter-bootstrap and following this page: http://django-crispy-forms.readthedocs.org/en/d-0/tags.html#bootstrap-layout-objects

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.