I want to create accounts with usernames and passwords that are student codes stored in Excel spreadsheets, what should I do?
Asked
Active
Viewed 659 times
0
-
Hold on, you store *raw* passwords? – Willem Van Onsem Nov 09 '19 at 12:18
-
Sorry for typing my question,I want to create accounts with usernames and passwords that are student codes stored in Excel spreadsheets but the password will be encrypted as usual. – Trần Huy Nov 09 '19 at 13:25
-
I tried adding the csv table to the database but with a rough password and could not log in – Trần Huy Nov 09 '19 at 13:27
2 Answers
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
-
-
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
-
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
-
Yes, the solution is quite similar to Pedram and it will work, thanks! – Trần Huy Nov 09 '19 at 14:25