0

I want to create accounts with usernames and passwords that are student codes stored in Excel spreadsheets, what should I do?

2 Answers2

0

First, export your Excel data as CSV file. Then you can easily iterate through the CSV file using csv library and insert data to Django.

As an example, let's say the fields in the CSV file are like this:

name, username, password

Then you can use this code to read the CSV file line by line and add users to the database:

def bulk_add_users(path):
    with open('path_to_csv_file', mode='r') as csv_file:
        reader = csv.reader(csv_file)
        _ = next(reader)
        for line in reader:
            name = line[0]
            username = line[1]
            password = line[2]
            if not (name and
                    username and
                    password):
                raise ValueError(f'Invalid User data!')
            user = User(name=name, username=username)
            user.set_password(password)
            user.save()

Edit:

If you are using django model (or extending it), you should use user.set_password('raw_password') so that the password encryption take in place before saving.

Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34
  • I edited the answer based on your login issue, check that. – Pedram Parsian Nov 09 '19 at 13:37
  • use the instructions [here](https://stackoverflow.com/a/18760222/9733868) or you can create a [custom management command](https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/) to run that (if you use this code frequently). – Pedram Parsian Nov 09 '19 at 13:47
  • I just tried it and it worked perfectly, thank you so much Pedram :3 – Trần Huy Nov 09 '19 at 14:21
0

You can create User objects with the username and password. For example by processing a csv file where the first column contains the username, and the second the raw password:

from csv import reader
from django.contrib.auth.models import User

with open('users.csv', 'r') as csv_file:
    csvf = reader(csv_file)
    data = []
    for username, password, *__ in csvf:
        user = User(username=username)
        user.set_password(password)
        data.append(user)
    User.objects.bulk_create(data)

It is important to use .set_password(..) [Django-doc] here, since that will hash the password in the database.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555