ninapavlich / django-batch-uploader

Django batch uploading
MIT License
8 stars 4 forks source link

Fix for error when trying to save form with select multiple. #9

Open onyekaa opened 6 years ago

onyekaa commented 6 years ago

Okay so this drove me a little crazy for a couple of hours. I added a ManyToMany field in my Image Model, where a user could select multiple users. The field is not required. However whenever I tried to leave the field empty and upload I kept getting

"" is not a valid value for a primary key.

Some experimenting showed that if I selected ONE item, it would upload fine, but then if I tried to select 2+ items, I'd get

"2,3" is not a valid value for a primary key.

Long story short, the error was from the start_upload function, when the field values are attached to new FormData(). Apparently FormaData converts the array of values sent by the select multiple field to a string-like value.

// this
['2', '3']
// becomes 
['2,3']
// once appended

To circumvent this I changed the code to check for arrays.

    var form_data = new FormData();
    for (key in this.data) {
        const value = this.data[key];
        if (Array.isArray(value)) {
          value.forEach(val => {
            form_data.append(`${key}`, val);
        });
      } else {
          form_data.append(key, value);
      }
    }
onyekaa commented 6 years ago

Update: Looks like I haven't completely fixed this. It still fails when the field is empty. I don't know why it thinks "" is a value, and as a variable it keeps returning true. Maybe it's because my JS isn't fantastic, but the only way I could catch that was to literally check for if (value != ""). It feels hacky though.