关键点在于user_group = Group.objects.get(name=‘admin’)和user_group.user_set.add(user)。
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
# 批量上传User
def import_user(self, request, obj, change):
wb = load_workbook(filename=obj.file.path)
ws = wb.get_sheet_names()
ws = wb.get_sheet_by_name(ws[0])
max_row = ws.max_row
headers = ['username', 'password', 'first_name', 'last_name','email']
lists = []
for row in range(2, max_row+1):
r = {}
for col in range(1, len(headers) + 1):
key = headers[col - 1]
r[key] = ws.cell(row=row, column=col).value
lists.append(r)
print('lists',lists)
for cell in lists:
try:
username = str(cell['username'])
password = str(cell['password'])
first_name = str(cell['first_name'])
last_name = str(cell['last_name'])
email = str(cell['email'])
user1 = User.objects.get_or_create(
username = username,
password = password,
first_name = first_name,
last_name = last_name,
email = email,
is_staff = 1,
)
user = User.objects.get(username = username)
user.set_password(password)
user.save()
print('user',user)
user_group = Group.objects.get(name='admin')
user_group.user_set.add(user)
print('给',user,'添加admin权限')
user.save()
except:
print('username',username)
pass
print('上传成功')