Uploading users in bulk in Django

Hi @djole,

Lets assume you have some projects already created and are wanting to create users and give them permissions to particular projects. You could create a spreadsheet with the following structure for creating new users (let’s call it users.csv):

username first_name last_name email
johndoe John Doe johndoe@gmail.com

And a second sheet with your projects and permissions for each user (let’s call it permissions.csv):

username project_uid permission
johndoe qWeRtyUiOpAsDfGh view_asset
johndoe pOiKjUhdwzkvkue6h view_submissions

You could then do something like this in the kpi Django shell (if you use pandas, you’ll have to pip install it):

import pandas as pd
# we need to let Django handle the password hashing
from django.contrib.auth.hashers import make_password

users = pd.read_csv('users.csv')
permissions = pd.read_csv('permissions.csv')

# let's create some users with default passwords equal to their username
for i, row in users.iterrows():
    User.objects.create(
		username=row['username'],
		first_name=row['first_name'],
		last_name=row['last_name'],
		email=row['email'],
		password=make_password(row['username'])

# let's assign permissions
for i, row in permissions.iterrows():
    try:
        asset = Asset.objects.get(uid=row['project_uid'])
    except Asset.DoesNotExist:
        print(row['project_uid'])
        continue
    try:
        user = User.objects.get(username=row['username'])
    except User.DoesNotExist:
        print(row['username'])
        continue
    asset.assign_perm(user, row['permission'])

You can find a list of the assignable permissions here and note that some permissions are implied by others, which you can see here.

Hope that helps :slightly_smiling_face:

2 Likes