我编写了一个读取csv文件并一次创建50个以上用户的命令。此外,我还下载了一些计划随机分配给每个用户的化身。这是发生问题的地方。我在下面编写了代码,为每个用户分配一个随机图像作为默认图像。
models.py
def random_image():
directory = os.path.join(settings.BASE_DIR, 'media')
files = os.listdir(directory)
images = [file for file in files if os.path.isfile(os.path.join(directory, file))]
rand = choice(images)
return rand
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars', default=random_image)
def save(self, *args, **kwargs):
# check model is new and avatar is empty
if self.pk is None and self.avatar is not None:
self.avatar = random_image
super(UserProfile, self).save(*args, **kwargs)
但是,该代码似乎仅在用户上传不是我想要的图片时才运行。我想要的是一旦用户登录它,模型应该检查它是否具有化身,如果没有,则分配一个随机图像。所以,我的问题是这些:
**编辑: ProjectName / management / commands / CreateUsers.py
class Command(BaseCommand):
help = 'Creates bulk users given a csv file.'
def handle(self, *args, **options):
## Get the Groups
TopManagement = Group.objects.get(name='TopManagement')
Finance = Group.objects.get(name='Finance')
## Read the csv file
with open(os.path.join(settings.FILES_DIR,'bulkusers.csv'), newline='') as csvfile:
ausers = csv.reader(csvfile, delimiter = ',')
next(ausers, None) # skip the headers
print('Creating Users...')
# Create users
for row in ausers:
newuser = User.objects.create_user(
username = row[0],
password = row[1],
email = row[2],
is_superuser = 0,
is_staff = 0,
is_active = 1,
date_joined = datetime.datetime.now(tz=timezone.utc)
)
# Assign user to group
if row[3] == 'TopManagement':
TopManagement.user_set.add(newuser)
newuser.groups.add(TopManagement)
elif row[3] == 'Finance':
newuser.groups.add(Finance)
print('Users created successfully!')
答案 0 :(得分:2)
在我看来,您的save()
覆盖应该起作用,即它将在用户创建时设置一个随机化身。只需在脚本中使用Django ORM,即可在脚本中使用User
模型创建用户,以便其调用save
方法。
我认为您的情况不正确,我相信您应该检查化身为None
:
if self.pk is None and self.avatar is None:
self.avatar = random_image()
答案 1 :(得分:0)
如果将来有人遇到相同的问题,这是对我有用的解决方案。
from django.db.models.signals import post_save
from django.dispatch import receiver
def random_image():
directory = os.path.join(settings.BASE_DIR, 'media')
files = os.listdir(directory)
images = [file for file in files if os.path.isfile(os.path.join(directory, file))]
rand = choice(images)
return rand
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars', default=random_image)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save()
我不知道为什么未调用save
函数,但是在来自@GProst的一些间接提示后,我设法用receiver
标签对其进行了更改。现在,每当我调用自定义命令python manage.py CreateUsers
时,就会立即激活UserProfile模型,并为每个用户分配一个随机图像。