Django 模型引用同一类的属性中的另一个属性

我试图为我的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 = False

AWS_DEFAULT_ACL = None


DEFAULT_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>/



慕容3067478
浏览 92回答 1
1回答

四季花海

您可以将可调用传递给upload_to=...&nbsp;参数 [Django-doc]:class UserDetails(models.Model):&nbsp; &nbsp; def profile_picture_upload(self, filename):&nbsp; &nbsp; &nbsp; &nbsp; return 'profile_pics/{}/{}'.format(self.user_id, filename)&nbsp; &nbsp; # …&nbsp; &nbsp; profilePicture = models.ImageField(blank=True, upload_to=profile_picture_upload)注意:通常 Django 模型中字段的名称是用snake_case编写的,而不是 PerlCase,所以它应该是:而不是配置文件图片。profile_picture
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python