Django models.FileField(upload_to = function1,default = function2)

时间:2015-11-09 20:07:05

标签: django django-models

我正在尝试使用函数在django模型中设置默认图像。我的原因是我生成了图像(一个qrcode),我想用与request.user相关联的模型保存它,它正在使用upload_to =但是默认失败,似乎它没有得到实例。

代码是: - - models.py - -

from django.db import models
from django.contrib.auth.models import User
import django.utils.timezone as timezone
from myproject.settings import MEDIA_ROOT
import os

def function1(instance, filename):
    retun os.path.join(self.uid.username, str(instance.shortname), '.jpg')

def function2(instance):
    return os.path.join(MEDIA_ROOT, str(instance.username), 'tmp.jpg')

class MyModel(models.Model):
    uid = models.ForeignKey(User)
    shortname = models.CharField()
    qr = models.FileField(upload_to=function1, default=function2)

这使得function2()只取1个参数(0给定)

我也尝试将uid作为参数传递给function2,如下所示:

def function2(uid):
    username = uid.username
    return os.path.join(MEDIA_ROOT, username, 'tmp.jpg')

class MyModel(models.Model):
    uid = models.ForeignKey(User)
    shortname = models.CharField()
    qr = models.FileField(upload_to=function1, default=function2(uid))

但这也行不通,给出了一个AttributeError异常: 'ForeignKey'对象没有属性'username'

关于如何告诉django上传本地生成的文件(在django机器上生成MEDIA_ROOT / request.user.username /)的任何想法

谢谢!

3 个答案:

答案 0 :(得分:1)

我找到了一种方法来解决我的问题: Loading Django FileField and ImageFields from the file system

答案 1 :(得分:0)

您需要使用instance代替selfselffunction1范围内不存在function2

def function1(instance, filename):
    return os.path.join(instance.uid.username, str(instance.shortname), '.jpg')

def function2(instance):
    return os.path.join(MEDIA_ROOT, str(instance.username), 'tmp.jpg')

class MyModel(models.Model):
    uid = models.ForeignKey(User)
    shortname = models.CharField()
    qr = models.FileField(upload_to=function1, default=function2)

您可以找到FileField.upload_to here

的文档

您得到function2() takes exactly 1 argument, (0 given),因为function2期待instance param,如果您尝试传递uid,请执行以下操作:

class MyModel(models.Model):
    uid = models.ForeignKey(User)
    shortname = models.CharField()
    qr = models.FileField(upload_to=function1, default=function2(uid))

会引发错误,因为此时uidmodels.ForeignKey个实例。您可以尝试在pre_save信号中执行此操作:

def function2(sender, instance, *args, **kwargs):

    if not instance.qr:
        instance.qr = os.path.join(MEDIA_ROOT, username, 'tmp.jpg')

pre_save.connect(function2, sender=MyModel)

答案 2 :(得分:0)

您需要使用实例而不是self。此外,function2将不会传递实例。