我试图为我的django网络应用程序用户的个人资料详细信息构建一个模型,例如:class UserDetails(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) profilePicture = models.ImageField(blank = True, upload_to='profile_pics/'+self.user.id+'/') country = models.CharField(max_length = 50, default='India') gender = models.CharField(max_length=10, default='NA') birthday = models.DateField(default=datetime.now()) phone = models.CharField(max_length=15)我在上面的模型中有一个图像字段,我想将传入的图像上传到我的媒体存储路径中的路径。我试图通过将图像字段的属性指定为 来做到这一点。我正在使用 AWS S3 进行媒体存储,并且我已将设置中的必要设置设为:profile_pics/<id of the user whose profile is being set up>/upload_toupload_to = 'profile_pics/'+self.user.id+'/'AWS_ACCESS_KEY_ID = 'myaccesskeyid'AWS_SECRET_ACCESS_KEY = 'mysecretaccesskey'AWS_STORAGE_BUCKET_NAME = 'mybucketname'AWS_S3_FILE_OVERWRITE = FalseAWS_DEFAULT_ACL = NoneDEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'当我尝试进行迁移时,我收到以下错误:Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv)请帮助我将图像上传到此模型的默认路径设置为 。profile_pics/<id of the user whose profile is being set up>/
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
您可以将可调用传递给upload_to=...
参数 [Django-doc]:
class UserDetails(models.Model):
def profile_picture_upload(self, filename):
return 'profile_pics/{}/{}'.format(self.user_id, filename)
# …
profilePicture = models.ImageField(blank=True, upload_to=profile_picture_upload)
注意:通常 Django 模型中字段的名称是用snake_case编写的,而不是 PerlCase,所以它应该是:而不是配置文件图片。profile_picture
添加回答
举报
0/150
提交
取消