简体   繁体   中英

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.

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

在此处输入图片说明

And they were added on top of what i had out there在此处输入图片说明

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

在此处输入图片说明

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.

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

def userdata(request):
with open('templates/csv/your_file.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)
    
return JsonResponse('user csv is now working', safe=False)

then in your urls.py

path('userdata/', userdata, name='userdata')

##just redirect to the url and all the data will be pushed to the database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM