Purpose of `empty_value` in `TypedMultipleChoiceField`?

Dear group,

looking at the docs of TypedMultipleChoiceField (Form fields | Django documentation | Django), I wonder what the purpose of the empty_value parameter is?

The TypedMultipleChoiceField normalizes to list of values, where each value corresponds to one of the choices as returned by coerce – and an empty list if none of the choices was selected, that is, an empty choice was given. Thus, empty_value seems redundant?

I can imagine a couple of different situations where you might want to ensure you have some value in a field - kinda like the difference between an empty string and a null. Since empty_value is of the type for the field, it lets you identify a sentinel value for that purpose.

Disclaimer: I’ve never used it, this is all a mental exercise on my part. But I can see the potential value of allowing the form to return that value instead of me checking the list and injecting it myself.

Thanks for your reply!

Still, this sounds very complicated to me. For example, if we have the cleaned result of a TypedMultipleChoiceField:

    result = form.cleaned_data['my_multi_field']

then result is a (possibly empty) list of coerced choices. Now, if the user didn’t select any of the choices and I wanted something else than the empty list in this case:

    revised_result = result or "the user didn't choose anything"

That seems simple and straightforward to me, whereas I found the empty_value parameter very complicated (I’m still not sure what exactly is does, and when). So I was wondering if I’m overlooking something essential? :thinking:

The source code for the TypedMultipleChoiceField (in django.forms.fields) is your best resource for that. From what I can see quickly, if the submitted value is the empty_value, then it bypasses the _coerce_ and validate methods, raising an exception if the field is marked as “required”.

I’m not sure I’m seeing where the complexities lie. My interpretation is that it’s functionally similar to the default attribute - except that it’s intended to indicate “no selection” instead of a default selection.

If nothing else, it provides consistency with all the other field types. The empty_field attribute is also availble on CharField, IntegerField, etc, etc.