netbox-community / netbox

The premier source of truth powering network automation. Open source under Apache 2. Try NetBox Cloud free: https://netboxlabs.com/free-netbox-cloud/
http://netboxlabs.com/oss/netbox/
Apache License 2.0
16.03k stars 2.57k forks source link

Utility function get_field_value returns last value when used on a multi-value field #17794

Open DanSheps opened 5 days ago

DanSheps commented 5 days ago

Deployment Type

Self-hosted

Triage priority

I volunteer to perform this work (if approved)

NetBox Version

v4.1.4

Python Version

3.10

Steps to Reproduce

  1. Utilize get_field_value on a form field that may produce a single value or multiple values (Ex: tagged_vlans)

Expected Behavior

get_field_value to return multiple values

Observed Behavior

get_field_valueu returns a single value

DanSheps commented 5 days ago

This is expected (but annoying) behaviour as per: https://code.djangoproject.com/ticket/1130

Two options are possible:

  1. Rewrite get_field_value to dynamically determine if the field is capable of returning multiple values
  2. Create a new get_field_values to call getlist() instead of get()
DanSheps commented 5 days ago

Proposed rewrite:

def get_field_value(form, field_name):
    """
    Return the current bound or initial value associated with a form field, prior to calling
    clean() for the form.
    """
    field = form.fields[field_name]

    if form.is_bound:
        # Get list or get single value
        if isinstance(field, MultipleChoiceField):
            data = form.data.getlist(field_name)
        else:
            data = form.data.get(field_name)

        if hasattr(field, 'valid_value') and field.valid_value(data):
            return data

    return form.get_initial_for_field(field, field_name)