Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin --Bulk Staff User Creation/Import from CSV file

I have a question. I have to import all of the users that will be allowed in my Django Admin app from an excel/csv file. Can someone please advice, guide me how i can implement this thing in Django Admin Interface. There is a script i can use? All of them will be allowed to login to my Django app and all of them will be automatically made staff users.

like image 703
Cohen Avatar asked Sep 17 '25 16:09

Cohen


1 Answers

So for those that will be in my shoes, please see bellow what did the trick!

import csv, sys, os, django


project_dir = "/parcare/src/"
sys.path.append(project_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'adp_parking.settings'
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__)
import django
django.setup()


from django.contrib.auth import authenticate
from django.contrib import admin
from django.contrib.auth.models import User

from django.contrib.auth import get_user_model
from django.conf import settings
User = get_user_model()

file = 'import.csv'

data = csv.reader(open(file), delimiter=",")
for row in data:
    if row[0] != "Number":
        # Post.id = row[0]
        Post=User()
        Post.password = row[1]
        Post.last_login = "2018-09-27 05:51:42.521991"
        Post.is_superuser = "0"
        Post.username = row[2]
        Post.first_name = row[3]
        Post.email = row[4]
        Post.is_staff = "1"
        Post.is_active = "1"
        Post.date_joined = "2018-09-27 05:14:50"
        Post.last_name=row[5]
        Post.save()

This is how my import.csv file looks like

enter image description here

And they were added on top of what i had out there enter image description here

Now the single step is to give permissions to all of them. Only the second record which is non admin has the rights.

enter image description here

PS Add a hashed pass, without it, the user will not work. So you have to create a test pass, and use that hash inserted into the pass row field==>and this will work like a charm.

like image 159
Cohen Avatar answered Sep 19 '25 06:09

Cohen