【问题标题】:Django: grab username of auth user foreignkeyDjango:获取身份验证用户外键的用户名
【发布时间】:2014-04-11 20:00:45
【问题描述】:

我想在 localhost/media/$username/image.jpg 下保存一个 jpg 文件 其中 $username 是外键的用户名(用户模型)。

当用户在对象的内容中被引用时,它会返回如下内容:

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

结果,图像保存为:

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

而我希望它是:

images/sinr0202/image.jpg

sinr0202 是用户名

模型.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)

【问题讨论】:

    标签: python django model foreign-keys


    【解决方案1】:

    你不能在那里这样做,因为在执行类定义时没有用户。相反,将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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 2014-04-06
      • 2020-05-02
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多