我想将上传的图片保存到单独的文件夹中。因此,例如用户4照片应存储在/ media / images / 4 /
中以下是我提出的功能,模型和观点:
型号:
def get_uplaod_file_name(user,filename):
return 'photos/%s/%s_%s' % str(user.id), (str(time()).replace('.','_'), filename)
class UserPic(models.Model):
user = models.ForeignKey(User, unique=False)
picfile = ImageWithThumbsField(upload_to= get_uplaod_file_name, sizes=((200,200),(1200,1200)))
caption = models.CharField(max_length=200 , blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
@models.permalink
def get_absolute_url(self):
return ('view_pirate', None, {'user': self.account.user})
def __unicode__(self):
return unicode(self.picfile.name)
查看:
@login_required
def upload(request):
# Handle file upload
thisuser =User.objects.get(username = request.user.username)
# Load pics of this user
if request.method == 'POST':
picform = PicForm(request.POST, request.FILES)
if picform.is_valid():
newpic = UserPic(picfile = request.FILES['picfile'])
newpic = picform.save(commit=False)
newpic.user_id = request.user.id
newpic.save()
message = "file %s is uploaded" % newpic
else:
picform = PicForm() # A empty, unbound form
args= {}
args['picform'] = picform
return render_to_response('userpics/upload.html',args,
context_instance=RequestContext(request))
然而,经过get_uplaod_file_name
的许多调整后,它仍然不起作用。我得到的错误如下:
TypeError at /pics/upload/
not enough arguments for format string
感谢您的帮助以解决此问题。
答案 0 :(得分:4)
您应该将元组传递给字符串格式化运算符:
def get_uplaod_file_name(userpic, filename):
return u'photos/%s/%s_%s' % (str(userpic.user.id),
str(time()).replace('.', '_'),
filename)
请注意第一个和最后一个圆括号。
另请注意unicode前缀u'
,如果用户上传名称中包含非ascii符号的文件,则必须使用该字符。{/ p>