[英]How to save an image in a directory named on the User?
I am using Django2.2 and I am currently learning Django.我正在使用 Django2.2,目前正在学习 Django。 I have created a model where I have to post an image of a certain thing and that model is connected with a User.
我创建了一个模型,我必须在其中发布某个事物的图像,并且该模型与用户相关联。 I want to save the image on a directory named on that certain user
我想将图像保存在以该特定用户命名的目录中
I have a custom User Model where I created a field called Profile Photo and that profile photo is saved to a directory named on that User.But then I created another application called 'Product' and there I created many fields including an image field.I am trying to save that image on that directory named on that specific User.我有一个自定义用户模型,我在其中创建了一个名为“个人资料照片”的字段,并将该个人资料照片保存到以该用户命名的目录中。然后我创建了另一个名为“产品”的应用程序,并在那里创建了许多字段,包括一个图像字段。我我试图将该图像保存在以该特定用户命名的目录中。
def user_directory_path(instance, filename):
return 'media/%s/%s' % (instance.username, filename)
class Products(models.Model):
title = models.CharField(max_length=100)
body = models.CharField(max_length=1000)
image = models.ImageField(upload_to = user_directory_path)
product_user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
When I try to save a Product and error occurs.当我尝试保存产品并发生错误时。
'Products' object has no attribute 'username'
Is there any successful ways to do it.有没有什么成功的方法可以做到。
A Products
instance indeed has no username
attribute. Products
实例确实没有username
属性。 The product_user
has, you thus can change this to: product_user
有,因此您可以将其更改为:
def user_directory_path(instance, filename):
return 'media/%s/%s' % (
instance.product_user.username, filename)
Note : models have usually singular names, so
Product
, instead of.Products
注意:模型通常具有单数名称,因此
Product
,而不是。Products
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.