简体   繁体   English

Django:获取身份验证用户外键的用户名

[英]Django: grab username of auth user foreignkey

I would like to save a jpg file under localhost/media/$username/image.jpg where $username is the username of the foreignkey (User model). 我想在localhost / media / $ username / image.jpg下保存一个jpg文件,其中$ username是外键的用户名(用户模型)。

When user is referenced in the content of the object, it returns something like the following: 在对象的内容中引用用户时,它返回如下内容:

<django.db.models.fields.related.ForeignKey>

As a result, the image is saved as: 结果,图像被保存为:

images/<django.db.models.fields.related.ForeignKey>;/image.jpg

Whereas I wanted it to be: 而我希望它是:

images/sinr0202/image.jpg

where sinr0202 is the username 其中sinr0202是用户名

model.py: model.py:

class Image(models.Model):
    PRIVACY = (
        ('P', 'Public'),
        ('F', 'Friends'),
        ('O', 'Only Me'),
    )
    user = models.ForeignKey(User)
    name = models.CharField(max_length=255)
    content = models.FileField(upload_to='media/%s' % (user))
    created = models.DateTimeField(auto_now_add=True)
    privacy = models.CharField(max_length=1, choices=PRIVACY)

You can't do that there, because there is no user at the time the class definition is executed. 您不能在那里执行此操作,因为在执行类定义时没有用户。 Instead, set upload_to to a callable, which will be called with the instance and the filename, and returns the full path including filename: 相反,将upload_to设置为可调用对象,将使用实例和文件名进行调用,并返回包含文件名的完整路径:

def content_file_name(instance, filename):
    return os.path.join('media', instance.user.username, filename)

class Image(models.Model):
    ...
    content = models.FileField(upload_to=content_file_name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM