我正在尝试使用Django-filetransfer上传文件,我想知道如何导入用户名作为保存上传文件的名称。现在我正在使用User.username,但那是无效。我想最重要的问题是如何从models.py访问用户的属性。下面是我的models.py:
from django.db import models
from django.contrib.auth.models import User, UserManager
class UploadModel(User,models.Model):
title = models.CharField(max_length=64, blank=True)
user = models.ForeignKey(User)
file = models.FileField(upload_to='./uploads/'+str(User.username))
@property
def filename(self):
return self.file.name.rsplit('/', 1)[-1]
更新: 应用程序/上传/ models.py
from django.db import models
from django.contrib.auth.models import User, UserManager
def uploadmodel_file_upload_to(instance, filename):
return 'uploads/%s/%s' % (instance.user.username, filename)
class UploadModel(models.Model):
user = models.ForeignKey('auth.user')
file = models.FileField(upload_to=uploadmodel_file_upload_to)
/ upload上的TemplateSyntaxError 渲染时捕获DatabaseError:列upload_uploadmodel.user_id不存在 第1行:选择“upload_uploadmodel”。“id”,“upload_uploadmodel”。“user ...
答案 0 :(得分:3)
当Python解析models.py代码时,模型属性是正式定义的。您应该使用upload_to 的回调,使用用户相关实例生成上传文件路径,例如:
def uploadmodel_file_upload_to(instance, filename):
return 'uploads/%s/%s' % (instance.user.username, filename)
class UploadModel(models.Model):
user = models.ForeignKey('auth.user')
file = models.FileField(upload_to=uploadmodel_file_upload_to)