与此问题的设置几乎相同:Django FileField with upload_to determined at runtime
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
是用户的配置文件类。我觉得我在这里遇到了一个错误,不是吗?
以下是一些其他细节。这发生在芹菜任务中,所以这可能是一个重要因素。我将用户传递给芹菜任务。它使用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()