1

在与此问题几乎相同的设置中:Django FileField with upload_to 在运行时确定

class Speaker(models.Model):
    user = models.OneToOneField(User, related_name='speaker')
    middle_name = models.CharField('Middle Name', max_length=40)
    profile_file = models.FileField(upload_to=profile_filename, blank=True, null=True)

def profile_filename(instance, filename):
    speaker = instance
    return "%s.%s.%s.%s.pdf" % (speaker.user.first_name, speaker.official_middle_initial, speaker.user.last_name, "profile")

我收到一个错误:AttributeError: 'User' object has no attribute 'first_name'

这是一个早已保存的对象,并且肯定有一个用户,其值在应用程序的其他任何地方都使用。Speaker是用户的配置文件类。我觉得我在这里遇到了一个错误,不是吗?

额外细节

这里有一些额外的细节。这发生在芹菜任务中,所以也许这是一个重要因素。我将用户传递给 celery 任务。它使用get_profile扬声器对象获取与其关联的配置文件对象。我在扬声器对象上保存了一个文件,这就是我们所在的位置。

当我列出用户对象上的字段时,它们似乎在那里:

[2012-08-19 11:52:40,819: WARNING/PoolWorker-5] ['date_joined', 'email', 'first_name', 'groups', 'id', 'is_active', 'is_staff', 'is_superuser', 'last_login', 'last_name', 'logentry', 'password', 'speaker', 'user_permissions', 'username', 'userpasswordresetrequired']

这是回溯:

[2012-08-19 11:52:40,834: ERROR/MainProcess] Task myapp.tasks.retrieveDocument[a4beb536-76a4-48ea-aaf9-9ca0668f9331] raised exception: 'User' object has no attribute 'first_name'
Traceback (most recent call last):
  File "/Users/bobspryn/lohi/Remedy/remedyenv/lib/python2.7/site-packages/celery/task/trace.py", line 212, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/Users/bobspryn/lohi/Remedy/myapp/tasks.py", line 24, in retrieveDocument
    afile.save(filename, content)
  File "/Users/bobspryn/lohi/Remedy/remedyenv/lib/python2.7/site-packages/django/db/models/fields/files.py", line 85, in save
    name = self.field.generate_filename(self.instance, name)
  File "/Users/bobspryn/lohi/Remedy/myapp/models.py", line 37, in w9_filename
    return "%s.%s.%s.%s.pdf" % (speaker.user.first_name, speaker.official_middle_initial, speaker.official_last_name, DOCUMENT_W9)
AttributeError: 'User' object has no attribute 'first_name'

更新

它似乎确实与它在芹菜内被执行有关。奇怪的。

更新

添加任务代码。

@task()
def retrieveDocument(user, documentKey, documentType):
    echosign = EchoSign(user=user)
    fileData = echosign.getDocumentWithKey(documentKey)
    if not fileData:
        logger.error('Error retrieving document', exc_info=True)
    else:
        speaker = user.get_profile()
        filename = "%s.%s.%s.pdf" % (user.first_name, user.last_name, documentType)
        if documentType == DOCUMENT_TEST:
            afile = speaker.test_file
        elif documentType == DOCUMENT_PROFILE:
            afile = speaker.profile_file

        content = ContentFile(fileData)
        afile.save(filename, content)
        speaker.save()
4

0 回答 0