Update user information in bulk

Is there a way to update your user information in bulk? What I want to do is export the user data update information like name etc and then import it back to the database, updating the existing information.

I can download a CSV from the admin panel but I’m wondering how would I get that info back on to Discourse.

I was painstakingly updating each user on the admin side of things (Name field) but when I go back in the updates appear blank

1 Like

The best way is probably with the API, though you could also do it with a script that would read your CSV and update it in rails.

Here’a rake task that updates custom user fields that could be modified to update other stuff:


require "csv"
desc "Import user fields"
task "user_fields:import_csv", [:filename] => [:environment] do |_, args|
  puts "Filename: #{args[:filename]}"
  data = CSV.read(args[:filename], headers: true );
  data.each_entry do |row|
    puts "doing row."
    row.to_h.each do |x|
      user_id = row['user_id']
      if x.first == 'user_id'
        u = User.find(user_id)
        puts "Got user: #{u.username}"
      else
        name = x.first
        val = row[x.first]
        ucf = UserCustomField.find_by(user_id: row['user_id'], name: name)
        if ucf
          if val != ucf.value
            puts "Updating UCF: #{row['user_id']} Name: #{name}, Found #{ucf.value}}"
            ucf.update(value: val)
          end
        else
          if val
            puts "Creating UCF: #{row['user_id']} Name: #{name}, value: #{val}"
            UserCustomField.create(user_id: user_id, name: name, value: val)
          end
        end
      end
    end
  end
end

After modifying it, you’d put it in /var/www/discourse/lib/tasks inside the container and rake user_fields:import_csv["YOUR-CSV.csv"]

If you need help modifying it for your needs, email me your CSV (or at least the headers and first few rows) and I’ll get you an estimate.

3 Likes

Here is that same script in GitHub:

Please note that at the moment it only does user custom fields - not fields such as name.

That was probably because you weren’t hitting save at then end of each edit. Is a UI thing that it would be nice to see addressed one day!!

Does it work with columns that have spaces in them or should the fields have underscores? Also when exported the first column header is id not user_id. Is that a problem?

They have names like user_field_1. That is somewhat explained in the github repo linked above.

The script isn’t designed to consume the user data download. You’ll need to modify several of the column headers. Also, in its current form the script only updates items stored in the custom_fields table.